diff --git a/.gitignore b/.gitignore index c8a07d74bb..51980485d0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,84 +2,105 @@ .idea .DS_Store -target/ -assembly/target +out/ +linkis.ipr +linkis.iws + +linkis-commons/linkis-common/target/ +linkis-commons/linkis-hadoop-common/target/ +linkis-commons/linkis-httpclient/target/ +linkis-commons/linkis-message-scheduler/target/ +linkis-commons/linkis-module/target/ +linkis-commons/linkis-mybatis/target/ +linkis-commons/linkis-protocol/target/ +linkis-commons/linkis-rpc/target/ +linkis-commons/linkis-scheduler/target/ +linkis-commons/linkis-storage/target/ + +linkis-computation-governance/linkis-computation-client/target/ +linkis-computation-governance/linkis-computation-governance-common/target/ +linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/target/ +linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/target/ +linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/target/ + +linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/target/ +linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/target/ +linkis-computation-governance/linkis-entrance-client/target/ +linkis-computation-governance/linkis-entrance/target/ +linkis-computation-governance/linkis-manager/label-common/target/ +linkis-computation-governance/linkis-manager/label-manager/target/ +linkis-computation-governance/linkis-manager/linkis-application-manager/target/ +linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-manager-common/target/ +linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-manager-service-common/target/ +linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-resource-manager-common/target/ +linkis-computation-governance/linkis-manager/linkis-manager-monitor/target/ +linkis-computation-governance/linkis-manager/linkis-manager-persistence/target/ +linkis-computation-governance/linkis-manager/linkis-resource-manager/target/ + + + +linkis-public-enhancements/linkis-bml/linkis-bml-client/target/ +linkis-public-enhancements/linkis-bml/linkis-bml-common/target/ +linkis-public-enhancements/linkis-bml/linkis-bml-server/target/ +linkis-public-enhancements/linkis-bml/linkis-bml-engine-hook/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-cache/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-client/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-common/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-engine-support/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-highavailable/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-listener/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-persistence/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-search/target/ +linkis-public-enhancements/linkis-context-service/linkis-cs-server/target/ +linkis-public-enhancements/linkis-datasource/datasourcemanager/common/target/ +linkis-public-enhancements/linkis-datasource/datasourcemanager/server/target/ +linkis-public-enhancements/linkis-datasource/linkis-metadata/target/ +linkis-public-enhancements/linkis-datasource/metadatamanager/common/target/ +linkis-public-enhancements/linkis-datasource/metadatamanager/server/target/ +linkis-public-enhancements/linkis-datasource/metadatamanager/service/elasticsearch/target/ +linkis-public-enhancements/linkis-datasource/metadatamanager/service/hive/target/ +linkis-public-enhancements/linkis-datasource/metadatamanager/service/mysql/target/ +linkis-public-enhancements/linkis-publicService/linkis-configuration/target/ +linkis-public-enhancements/linkis-publicService/linkis-instance-label/client/target/ +linkis-public-enhancements/linkis-publicService/linkis-instance-label/target/ +linkis-public-enhancements/linkis-publicService/linkis-jobhistory/target/ +linkis-public-enhancements/linkis-publicService/linkis-script-dev/linkis-storage-script-dev-client/target/ +linkis-public-enhancements/linkis-publicService/linkis-script-dev/linkis-storage-script-dev-server/target/ +linkis-public-enhancements/linkis-publicService/linkis-udf/target/ +linkis-public-enhancements/linkis-publicService/linkis-variable/target/ +linkis-public-enhancements/linkis-publicService/target/ + -core/cloudModule/target/ -core/cloudMybatis/target/ -core/cloudProtocol/target/ -core/cloudRPC/target/ -core/common/target/ -core/httpclient/target/ -core/scheduler/target/ -eurekaServer/target/ -gateway/core/target/ -gateway/gateway-httpclient-support/target/ -gateway/gateway-ujes-support/target/ -gateway/springcloudgateway/target/ - - -metadata/target/ -publicService/application/target/ -publicService/configuration/target/ -publicService/jobhistory/target/ -publicService/target/ -publicService/udf/target/ -publicService/variable/target/ -publicService/workspace/target/ -resourceManager/resourcemanagerclient/target/ -resourceManager/resourcemanagercommon/target/ -resourceManager/resourcemanagerserver/target/ -storage/storage/target/ - -contextservice/cs-cache/target -contextservice/cs-client/target -contextservice/cs-common/target -contextservice/cs-highavailable/target -contextservice/cs-listener/target -contextservice/cs-persistence/target -contextservice/cs-search/target -contextservice/cs-server/target -contextservice/cs-ujes-client/target - -datasource/datasourcemanager/common/target -datasource/datasourcemanager/server/target -datasource/metadatamanager/common/target -datasource/metadatamanager/server/target -datasource/metadatamanager/service/elasticsearch/target -datasource/metadatamanager/service/hive/target -datasource/metadatamanager/service/mysql/target - - - -ujes/client/target/ -ujes/definedEngines/hive/engine/target/ -ujes/definedEngines/hive/enginemanager/target/ -ujes/definedEngines/hive/entrance/target/ -ujes/definedEngines/jdbc/entrance/target/ -ujes/definedEngines/pipeline/engine/target/ -ujes/definedEngines/pipeline/enginemanager/target/ -ujes/definedEngines/pipeline/entrance/target/ -ujes/definedEngines/python/engine/target/ -ujes/definedEngines/python/enginemanager/target/ -ujes/definedEngines/python/entrance/target/ -ujes/definedEngines/spark/engine/target/ -ujes/definedEngines/spark/enginemanager/target/ -ujes/definedEngines/spark/entrance/target/ -ujes/definedEngines/presto/entrance/target/ -ujes/engine/target/ -ujes/enginemanager/target/ -ujes/entrance/target/ - -ujes/definedEngines/mlsql/entrance/target/ +linkis-spring-cloud-services/linkis-service-discovery/linkis-eureka/target/ +linkis-spring-cloud-services/linkis-service-gateway/linkis-gateway-core/target/ +linkis-spring-cloud-services/linkis-service-gateway/linkis-gateway-httpclient-support/target/ +linkis-spring-cloud-services/linkis-service-gateway/linkis-gateway-server-support/target/ +linkis-spring-cloud-services/linkis-service-gateway/linkis-spring-cloud-gateway/target/ + + + + +linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-cache/target/ +linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-core/target/ +linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-loader/target/ +linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-server/target/ +linkis-engineconn-plugins/engineconn-plugins/jdbc/target/ +linkis-engineconn-plugins/engineconn-plugins/hive/target/ +linkis-engineconn-plugins/engineconn-plugins/io_file/target/ +linkis-engineconn-plugins/engineconn-plugins/python/target/ +linkis-engineconn-plugins/engineconn-plugins/spark/target/ +linkis-engineconn-plugins/engineconn-plugins/pipeline/target/ +linkis-engineconn-plugins/engineconn-plugins/shell/target/ + +linkis-orchestrator/plugin/linkis-orchestrator-ecm-plugin/target/ + +assembly/target assembly/public-module/target/ -bml/bml-engine-hook/target/ -bml/bmlclient/target/ -bml/bmlcommon/target/ -bml/bmlserver/target/ -core/hadoop-common/target/ -publicService/workspace/client/workspace-httpclient/target/ -userControl/target/ diff --git a/README-ZH.md b/README-ZH.md new file mode 100644 index 0000000000..1cb9df30b2 --- /dev/null +++ b/README-ZH.md @@ -0,0 +1,149 @@ +Linkis +============ + +[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) + +[English](README.md) | 中文 + +# 引言: + +Linkis 在上层应用和底层引擎之间构建了一层计算中间件,上层应用只需对接 Linkis 提供的 REST/WS/JDBC 等标准接口,就能连接到 MySQL/Spark/Hive/Presto/Flink 等各种底层计算存储引擎,并实现上层应用间的互通。 + +作为计算中间件,提供强大的连通,复用,扩展和管控能力。并通过解耦应用层和引擎层,简化复杂的网状调用关系,降低整体复杂度和开发、运维成本。 + +自2019年开源以来,累计试用企业近 **700** 家,沙箱试用用户 **1000+**,涉及 互联网、金融、通信等多个行业,被很多企业用作大数据平台底层计算存储引擎组件的统一入口。 + +没有 Linkis 之前如下: + +![原大数据生态图](docs/zh_CN/images/ch3/原大数据生态图.jpg) + +有了 Linkis 之后如下: + +![Linkis效果图](docs/zh_CN/images/ch3/解决方案.jpg) + + + +基于Linkis计算中间件的架构设计理念,我们在上层构建了很多的应用系统。目前已开源的有: + +- [**DataSphere Studio - 数据应用开发管理门户**](https://github.com/WeBankFinTech/DataSphereStudio) + +- [**Qualitis - 数据质量工具**](https://github.com/WeBankFinTech/Qualitis) + +- [**Scriptis - 数据研发IDE工具**](https://github.com/WeBankFinTech/Scriptis) + +- [**Visualis - 数据可视化工具**](https://github.com/WeBankFinTech/Visualis) + +- [**Schedulis - 工作流调度工具**](https://github.com/WeBankFinTech/Schedulis) + +更多工具准备开源中,敬请期待! + +---- + +# 核心特点: + +- **丰富的底层计算存储引擎支持度**。 + + **目前支持的计算存储引擎**有:Spark、Hive、Python、Presto、ElasticSearch、MLSQL、TiSpark、JDBC和Shell等。 + + **正在支持中的计算存储引擎**有:Flink、Impala和Clickhouse等。 + + **支持的脚本语言有**:SparkSQL、Scala、Pyspark、R、Python、JDBC、HiveQL和Shell等; + +- **强大的计算治理能力**。Linkis 1.0 总体分为三大模块:公共增强服务、计算治理服务、微服务治理服务。三大模块简介如下: + + 1. 公共增强服务为 Linkis 0.X 已经提供的物料库服务、上下文服务、数据源服务和公共服务等; + + 2. 微服务治理服务为 Linkis 0.X 已经提供的Spring Cloud Gateway、Eureka和Open Feign,同时 Linkis1.0 还会提供对 Nacos 的支持; + + 3. 计算治理服务是 Linkis 1.0 的核心重点,从 提交 —> 准备 —> 执行三个阶段,来全面升级Linkis 对 用户任务的执行管控能力。 + +- **全栈计算存储引擎架构支持**。作为计算中间件,将接收、执行和管理针对各种计算存储引擎的任务和请求,包括离线批量任务、交互式查询任务、实时流式任务和存储型任务,并提供强大的复用、预热、限流、切换、全生命周期管理等计算治理能力; + +- **更强大的资源管理能力**。 ResourceManager 不仅具备 Linkis0.X 对 Yarn 和 Linkis EngineManager 的资源管理能力,还将提供基于标签的多级资源分配和回收能力,让 ResourceManager 具备跨集群、跨计算资源类型的强大资源管理能力。 + +- **全流程标签化**。基于多级组合标签,提供跨IDC、跨集群的计算任务路由管控能力,和EngineConnManager, EngineConn 的多租户隔离能力; + +- **统一上下文服务**。统一用户和系统资源文件(JAR、ZIP、Properties等),跨用户、系统、计算引擎的参数和变量统一管理,一处设置,处处自动引用; + +- **统一物料**。系统和用户级物料管理,可分享和流转,跨用户、系统共享物料,支持全生命周期自动管理; + + +---- + +# 文档列表 + +### Linkis1.0 常用文档 + +[**Linkis1.0 快速安装使用文档**](https://github.com/WeBankFinTech/Linkis/wiki/%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8Linkis-1.0-RC1) + +[**Linkis1.0 用户使用文档**](https://github.com/WeBankFinTech/Linkis/wiki/Linkis1.0%E7%94%A8%E6%88%B7%E4%BD%BF%E7%94%A8%E6%96%87%E6%A1%A3) + +[**快速了解 Linkis1.0 全新架构**](https://github.com/WeBankFinTech/Linkis/wiki/Linkis1.0%E4%B8%8ELinkis0.X%E7%9A%84%E5%8C%BA%E5%88%AB%E7%AE%80%E8%BF%B0) + +### Linkis0.X 常用文档 + +[Linkis0.X 快速安装使用文档](https://github.com/WeBankFinTech/Linkis/wiki/%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8Linkis) + +[Linkis0.X 上层前端应用的HTTP接入文档](https://github.com/WeBankFinTech/Linkis/wiki/%E4%B8%8A%E5%B1%82%E5%89%8D%E7%AB%AF%E5%BA%94%E7%94%A8HTTP%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3) + +[Linkis0.X 上层前端应用的WebSocket接入文档](https://github.com/WeBankFinTech/Linkis/wiki/%E4%B8%8A%E5%B1%82%E5%89%8D%E7%AB%AF%E5%BA%94%E7%94%A8WebSocket%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3) + +[Linkis0.X 架构文档](https://github.com/WeBankFinTech/Linkis/wiki/%E6%80%BB%E4%BD%93%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1%E4%BB%8B%E7%BB%8D) + +**更多关于 Linkis1.0 和 Linkis0.X 的文档,请 [点我访问](https://github.com/WeBankFinTech/Linkis/wiki)** + +---- + +# Architecture: + +![introduction_new](images/zh_CN/Linkis1.0/architecture/Linkis1.0-architecture.png) + +---- + +# RoadMap + +### 1. 实现 Orchestrator 编排架构,提供丰富的计算策略支持 + +- 支持多活 +- 支持主备 +- 支持事务 +- 支持重放 +- 支持多数据源混算 +- 支持多数据源异构 + +### 2. Linkis1.0 管理台优化 + +- 统一数据源模块优化 +- UDF模块优化 +- JobHistory优化,支持展示Orchestrator所有编排任务的详细Metrics信息。 + +### 3. Linkis1.0 支持Flink引擎,完成所有未适配引擎的新架构适配 + +- 适配 Presto 引擎 +- 适配 ElasticSearch 引擎 +- 适配 Impala 引擎 + + + + +**如果您有任何需求,欢迎给我们提issue,我们将会及时给您回复。** + +---- + +# Contributing + +非常欢迎广大的社区伙伴给我们贡献新引擎和代码! + +---- + +# Communication + +如果您想得到最快的响应,请给我们提issue,或者您也可以扫码进群: + +![introduction05](docs/zh_CN/images/introduction/introduction05.png) + +---- + +# License + +**Linkis is under the Apache 2.0 license. See the [LICENSE](/LICENSE) file for details.** diff --git a/README.md b/README.md index 60430007ba..9aa18cb591 100644 --- a/README.md +++ b/README.md @@ -3,15 +3,15 @@ Linkis [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) -English | [中文](docs/zh_CN/README.md) +English | [中文](README-ZH.md) -## Introduction +# Introduction -Linkis helps easily connect to various back-end computation/storage engines(Spark, Python, TiDB...), exposes various interfaces(REST, JDBC, Java ...), with multi-tenancy, high performance, and resource control. + Linkis builds a layer of computation middleware between upper applications and underlying engines. By using standard interfaces such as REST/WS/JDBC provided by Linkis, the upper applications can easily access the underlying engines such as MySQL/Spark/Hive/Presto/Flink, etc., and achieve the intercommunication of user resources like unified variables, scripts, UDFs, functions and resource files at the same time. -Linkis connects with computation/storage engines(Spark, Hive, Python and HBase), exposes REST/WS interface, and executes multi-language jobs(SQL, Pyspark, HiveQL and Scala), as a computation middleware. +As a computation middleware, Linkis provides powerful connectivity, reuse, expansion, and computation governance capabilities. By decoupling the application layer and the engine layer, it simplifies the complex network call relationship, and thus reduces the overall complexity and saves the development and maintenance costs as well. -Based on the microservices architecture, Linkis provides enterprise-level features of multi-tenant isolation, resource management and access control. It also offers convenient support to manage unified variables, UDFs, functions and resource files. it is also guaranteed with sophisticated task/job lifecycle management capabilities under high-concurrency, high-performance and high-availability scenarios. +Since the first release of Linkis in 2019, it has accumulated more than **700** trial companies and **1000+** sandbox trial users, which involving diverse industries, from finance, banking, tele-communication, to manufactory, internet companies and so on. Lots of companies have already used Linkis as a unified entrance for the underlying computation and storage engines of the big data platform. ![linkis-intro-01](https://user-images.githubusercontent.com/11496700/84615498-c3030200-aefb-11ea-9b16-7e4058bf6026.png) @@ -20,44 +20,59 @@ Based on the microservices architecture, Linkis provides enterprise-level featur -Based on the concept of the computation middleware architecture of Linkis, we have built a large amount of applications and systems on top of it.Currently available open-source project: - - [**DataSphere Studio - Data Application Development& Management Portal**](https://github.com/WeBankFinTech/DataSphereStudio) +Based on Linkis the computation middleware, we've built a lot of applications and systems on top of it. The following are the currently available open-source projects: + + - [**DataSphere Studio - Data Application Development & Management Framework**](https://github.com/WeBankFinTech/DataSphereStudio) + - [**Qualitis - Data Quality Tool**](https://github.com/WeBankFinTech/Qualitis) + - [**Scriptis - Data Development IDE Tool**](https://github.com/WeBankFinTech/Scriptis) - - [**Visualis - Data Visualization Tool**](https://github.com/WeBankFinTech/Visualis) - There will be more tools released as open-source projects, please stay tuned! + - [**Visualis - Data Visualization Tool**](https://github.com/WeBankFinTech/Visualis) -## Features + - [**Schedulis - Workflow Task Scheduling Tool**](https://github.com/WeBankFinTech/Schedulis) -- Unified Job Execution Services: A distributed REST/WebSocket service for processing scripts execution requests from user. +More upcoming tools to release, please stay tuned! - Available computation engines so far: Spark, Python, TiSpark, Hive and Shell. +# Features - Available languages so far: SparkSQL, Spark Scala, PySpark, R, Python, HQL and Shell. +- **Support for diverse underlying computation storage engines**. -- Resource Management Services: Available for real-time control/limit of resource usage from both perspectives of amount and load for both systems and users. With dynamic charts of resource statistics, it is convenient to monitor and manage resource usage for systems and users. + **Currently supported computation/storage engines**: Spark, Hive, Python, Presto, ElasticSearch, MLSQL, TiSpark, JDBC, Shell, etc; + + **Computation/storage engines to be supported**: Flink, Impala, Clickhouse, etc; + + **Supported script languages**: SparkSQL, Scala, Pyspark, R, Python, JDBC, HiveQL and Shell, etc. - Available resource types so far: Yarn queue resources, server(CPU and memory), number of concurrent instances per user. +- **Powerful computation governance capabilities**. Linkis 1.0 services could be divided into three categories: public enhancement services, computation governance services, and microservice governance services. + + 1. The public enhancement service including the material library service, context service, data source service and public services already provided by Linkis 0.X; + + 2. The microservice governance services including Spring Cloud Gateway, Eureka and Open Feign already provided by Linkis 0.X, with extra Nacos support which will be provided by Linkis 1.0; + + 3. The computation governance services. It could be divided into three stages: submission -> preparation -> execution, to comprehensively upgrade the ability of Linkis to execute, manage and control user tasks. +- **Support for full stack computation storage engine**. As a computation middleware, it will receive, execute and manage tasks and requests for various computation storage engines, including batch tasks, interactive query tasks, real-time streaming tasks and storage tasks, and provide powerful computation governance capabilities such as reuse, warm-up , current-limiting, engine-switching, and full life cycle management of engines; -- Application Management Services: Manages global user applications, including offline batch applications, interactive query applications and real-time streaming applications. Also provides powerful reusability especially for offline and interactive applications, with complete lifecycle management which automatically releases idle applications for users. +- **More powerful resource management capabilities**. ResourceManager is not only capable of managing resources for Yarn and Linkis EngineManger as in Linkis 0.X, but also extends its capabilities to providing tag-based multi-level resource allocation and recycling, allowing itself to have powerful resource management capabilities across mutiple Yarn clusters and mutiple computation resource types; -- Unified Storage Services: The generic IO architecture can quickly integrate with various storage systems and provide a unified invokable entrance. It is also highly integrated with most common data formats and easy to use. +- **Whole-process label support**. Based on multi-level combined tags, Linkis 1.0 provides cross-IDC and cross-cluster computation task routing and control capabilities, and multi-tenant capabilities for EngineConnManager and EngineConn; -- Unified Context Services: Unite resources files of users and systems (JAR, ZIP, Properties). With unified management of arguments/variables for users, systems and engines, it is achieved that modification in random place will reflect in all the other places automatically. +- **Unified Context Service**. Unified user and system resource files (JAR, ZIP, Properties, etc.), unified management of parameters and variables across users, systems and engines. Setting once, reference anywhere; +- **Unified materials**. System and user-level unified material management, which can be shared and transferred across users and systems, and support automatic management of the material life cycle. +# Documentations: -- Material Library: System and user-level material management, capable of sharing, transferring materials and automatic lifecycle management. +### Linkis 1.0 documentations -- Metadata Services: Real-time display of dataset table structure and partitions. +[**Linkis 1.0 Quick Deploy**](https://github.com/WeBankFinTech/Linkis/wiki/%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8Linkis-1.0-RC1) - **Compared with similar systems** +[**Linkis 1.0 User Documentation**](https://github.com/WeBankFinTech/Linkis/wiki/Linkis1.0%E7%94%A8%E6%88%B7%E4%BD%BF%E7%94%A8%E6%96%87%E6%A1%A3) -![introduction01](https://user-images.githubusercontent.com/11496700/84625630-403b7080-af16-11ea-8816-392dda3584d1.png) +[**Quickly understand the new architecture of Linkis 1.0**](https://github.com/WeBankFinTech/Linkis/wiki/Linkis1.0%E4%B8%8ELinkis0.X%E7%9A%84%E5%8C%BA%E5%88%AB%E7%AE%80%E8%BF%B0) -# Documentations: +### Linkis 0.X documentations [Linkis, make big data easier](docs/en_US/ch3/Linkis_Introduction.md) @@ -75,15 +90,45 @@ Based on the concept of the computation middleware architecture of Linkis, we ha # Architecture: -![introduction02](https://user-images.githubusercontent.com/11496700/84615549-e9c13880-aefb-11ea-870e-6d2e9b8fa08d.png) +![architecture](images/en_US/Linkis1.0/architecture/Linkis1.0-architecture.png) ---- -## Communication -If you desire immediate response, please kindly raise issues to us or scan the below QR code by WeChat and QQ to join our group: +# RoadMap + +### 1. Implement Orchestrator architecture and support for rich computation and orchestration strategies: + +- Support multi-activation for engines and clusters +- Support active and standby +- Support transaction +- Support playback +- Support mixed computation of multiple data sources +- Support heterogeneous computation of multiple data sources + +### 2. Linkis 1.0 management console optimization + +- Unified data source module optimization +- UDF module optimization +- JobHistory is planned to support the display of detailed Metrics information of all orchestration tasks of one job in Orchestrator. + +### 3. Linkis 1.0 supports Flink engine and completes the new architecture adaptation for all unadapted engines + +- Optimize Presto engine for new architecture +- Optimize ElasticSearch engine for new architecture +- Optimize Impala engine for new architecture + + If you have any needs, please submit an issue, and we will reply to you in time. + +# Contributing + + We welcome all community partners to contribute new computation storage engines and other codes to us! + +# Communication + + If you desire immediate response, please kindly raise issues to us or scan the below QR code by WeChat and QQ to join our group: ![introduction05](https://user-images.githubusercontent.com/11496700/84615565-f2197380-aefb-11ea-8288-c2d7b0410933.png) -## License +# License -Linkis is under the Apache 2.0 license. See the [LICENSE ](http://www.apache.org/licenses/LICENSE-2.0)file for details. \ No newline at end of file + Linkis is under the Apache 2.0 license. See the [LICENSE ](http://www.apache.org/licenses/LICENSE-2.0)file for details. diff --git a/assembly/pom.xml b/assembly/pom.xml index 3cda062654..2a7706a278 100644 --- a/assembly/pom.xml +++ b/assembly/pom.xml @@ -1,13 +1,10 @@ + + io.protostuff + protostuff-runtime + 1.6.2 + + + + io.protostuff + protostuff-api + 1.6.2 + + @@ -114,7 +173,7 @@ false - module + out false false diff --git a/assembly/public-module/src/main/assembly/distribution.xml b/assembly/public-module/src/main/assembly/distribution.xml index 865b4a9a34..5568d90d9f 100644 --- a/assembly/public-module/src/main/assembly/distribution.xml +++ b/assembly/public-module/src/main/assembly/distribution.xml @@ -1,12 +1,9 @@ @@ -36,11 +33,11 @@ true true - io.netty:netty-buffer* - io.netty:netty-codec* - io.netty:netty-common* - io.netty:netty-handler* - io.netty:netty-transport* + + + + + diff --git a/assembly/src/main/assembly/assembly.xml b/assembly/src/main/assembly/assembly.xml index 1c19030b68..9c811ef5c0 100644 --- a/assembly/src/main/assembly/assembly.xml +++ b/assembly/src/main/assembly/assembly.xml @@ -1,12 +1,9 @@ + - ${project.parent.basedir}/ujes/definedEngines/spark/entrance/target/ + ${project.parent.basedir}/linkis-engineconn-plugins/engineconn-plugins/spark/target/out/ - share/linkis/ujes/spark + lib/linkis-engineconn-plugins/ - *.zip + **/* + - ${project.parent.basedir}/ujes/definedEngines/spark/enginemanager/target/ + ${project.parent.basedir}/linkis-engineconn-plugins/engineconn-plugins/hive/target/out/ - share/linkis/ujes/spark + lib/linkis-engineconn-plugins/ - *.zip + **/* - + - ${project.parent.basedir}/ujes/definedEngines/hive/entrance/target/ + ${project.parent.basedir}/linkis-engineconn-plugins/engineconn-plugins/python/target/out/ - share/linkis/ujes/hive + lib/linkis-engineconn-plugins/ - *.zip + **/* + - ${project.parent.basedir}/ujes/definedEngines/hive/enginemanager/target/ + ${project.parent.basedir}/linkis-engineconn-plugins/engineconn-plugins/shell/target/out/ - share/linkis/ujes/hive + lib/linkis-engineconn-plugins/ - *.zip + **/* - - - - ${project.parent.basedir}/ujes/definedEngines/python/entrance/target/ - - share/linkis/ujes/python - - *.zip - - - - - ${project.parent.basedir}/ujes/definedEngines/python/enginemanager/target/ - - share/linkis/ujes/python - - *.zip - - + + + + + + ${project.parent.basedir}/linkis-spring-cloud-services/linkis-service-gateway/linkis-gateway-server-support/target/out/lib + + + lib/linkis-spring-cloud-services/linkis-mg-gateway + + + *.jar + + - - - - ${project.parent.basedir}/ujes/definedEngines/shell/entrance/target/ - - share/linkis/ujes/shell - - *.zip - - + + + ${project.parent.basedir}/linkis-spring-cloud-services/linkis-service-gateway/linkis-gateway-server-support/target/out/conf + + + conf/linkis-spring-cloud-services/linkis-mg-gateway + + + * + + - - - ${project.parent.basedir}/ujes/definedEngines/shell/enginemanager/target/ - - share/linkis/ujes/shell - - *.zip - - + + + + ${project.parent.basedir}/linkis-spring-cloud-services/linkis-service-discovery/linkis-eureka/target/out/lib + + + lib/linkis-spring-cloud-services/linkis-mg-eureka + + + *.jar + + + + + ${project.parent.basedir}/linkis-spring-cloud-services/linkis-service-discovery/linkis-eureka/target/out/conf + + + conf/linkis-spring-cloud-services/linkis-mg-eureka + + + * + + - - - - - - ${project.parent.basedir}/ujes/definedEngines/jdbc/entrance/target/ - - share/linkis/ujes/jdbc - - *.zip - - + + + + + + ${project.parent.basedir}/assembly/public-module/target/out/lib + + lib/linkis-commons/public-module/ + + *.jar + + - + + + + + + ${project.parent.basedir}/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/target/out/lib + + + lib/linkis-computation-governance/linkis-cg-engineconnmanager + + + *.jar + + - - - - ${project.parent.basedir}/ujes/definedEngines/es/entrance/target/ - - share/linkis/ujes/es - - *.zip - - + + + ${project.parent.basedir}/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/target/out/conf + + + conf/linkis-computation-governance/linkis-cg-engineconnmanager + + + * + + - - - - ${project.parent.basedir}/ujes/definedEngines/presto/entrance/target/ - - share/linkis/ujes/presto - - *.zip - - + + + + ${project.parent.basedir}/linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-server/target/out/lib/ + + + lib/linkis-computation-governance/linkis-cg-engineplugin + + + *.jar + + - - - - ${project.parent.basedir}/resourceManager/resourcemanagerserver/target/ - - share/linkis/rm/ - - *.zip - - + + + ${project.parent.basedir}/linkis-engineconn-plugins/linkis-engineconn-plugin-framework/linkis-engineconn-plugin-server/target/out/conf/ + + + conf/linkis-computation-governance/linkis-cg-engineplugin + + + * + + - - - - ${project.parent.basedir}/bml/bmlserver/target/ - - share/linkis/linkis-bml/ - - *.zip - - + + + + ${project.parent.basedir}/linkis-computation-governance/linkis-manager/linkis-application-manager/target/out/lib + + + lib/linkis-computation-governance/linkis-cg-linkismanager + + + *.jar + + - - - - ${project.parent.basedir}/gateway/gateway-ujes-support/target/ - - share/springcloud/gateway/ - - *.zip - - - - ${project.parent.basedir}/eurekaServer/target/ + ${project.parent.basedir}/linkis-computation-governance/linkis-manager/linkis-application-manager/target/out/conf - share/springcloud/eureka/ + + conf/linkis-computation-governance/linkis-cg-linkismanager + - *.zip + * - + + - ${project.parent.basedir}/assembly/public-module/target/ + ${project.parent.basedir}/linkis-computation-governance/linkis-entrance/target/out/lib - share/linkis/module/ + + lib/linkis-computation-governance/linkis-cg-entrance + - *.zip + *.jar - - - - ${project.parent.basedir}/publicService/target/ - - share/linkis/linkis-publicservice/ - - *.zip - - - - - - ${project.parent.basedir}/metadata/target/ - - share/linkis/linkis-metadata/ - - *.zip - - - - - - ${project.parent.basedir}/contextservice/cs-server/target/ - - share/linkis/linkis-cs-server/ - - *.zip - - - - - - ${project.parent.basedir}/datasource/datasourcemanager/server/target - - share/linkis/datasource/linkis-dsm-server/ - - *.zip - - + + + ${project.parent.basedir}/linkis-computation-governance/linkis-entrance/target/out/conf + + + conf/linkis-computation-governance/linkis-cg-entrance + + + * + + - - - - ${project.parent.basedir}/datasource/metadatamanager/server/target - - share/linkis/datasource/linkis-mdm-server/ - - *.zip - - - + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-bml/linkis-bml-server/target/out/lib + + + lib/linkis-public-enhancements/linkis-ps-bml + + + *.jar + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-bml/linkis-bml-server/target/out/conf + + + conf/linkis-public-enhancements/linkis-ps-bml + + + * + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-publicservice/target/out/lib + + + lib/linkis-public-enhancements/linkis-ps-publicservice + + + *.jar + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-publicservice/target/out/conf + + + conf/linkis-public-enhancements/linkis-ps-publicservice + + + * + + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-datasource/linkis-metadata/target/out/lib + + + lib/linkis-public-enhancements/linkis-ps-datasource + + + *.jar + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-datasource/linkis-metadata/target/out/conf + + + conf/linkis-public-enhancements/linkis-ps-datasource + + + * + + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-context-service/linkis-cs-server/target/out/lib + + + lib/linkis-public-enhancements/linkis-ps-cs + + + *.jar + + + + + + ${project.parent.basedir}/linkis-public-enhancements/linkis-context-service/linkis-cs-server/target/out/conf + + + conf/linkis-public-enhancements/linkis-ps-cs + + + * + + + + @@ -342,4 +410,4 @@ - + \ No newline at end of file diff --git a/bin/checkEnv.sh b/bin/checkEnv.sh old mode 100755 new mode 100644 diff --git a/bin/checkServices.sh b/bin/checkServices.sh index 7e53bb5b2b..561277b129 100644 --- a/bin/checkServices.sh +++ b/bin/checkServices.sh @@ -29,11 +29,9 @@ MICRO_SERVICE_NAME=$1 MICRO_SERVICE_IP=$2 MICRO_SERVICE_PORT=$3 - -source ${workDir}/bin/common.sh local_host="`hostname --fqdn`" -ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}'|awk 'NR==1') +ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') function isLocal(){ if [ "$1" == "127.0.0.1" ];then @@ -60,7 +58,6 @@ function executeCMD(){ } - echo "Start to Check if your microservice:$MICRO_SERVICE_NAME is normal via telnet" echo "--------------------------------------------------------------------------------------------------------------------------" echo $MICRO_SERVICE_NAME diff --git a/bin/common.sh b/bin/common.sh old mode 100755 new mode 100644 index c0ba755210..49d5cf7a90 --- a/bin/common.sh +++ b/bin/common.sh @@ -20,7 +20,7 @@ source ~/.bash_profile local_host="`hostname --fqdn`" -ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}' | awk 'NR==1') +ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') function isLocal(){ if [ "$1" == "127.0.0.1" ];then diff --git a/bin/install.sh b/bin/install.sh old mode 100755 new mode 100644 index b646689abf..be8cfeecdc --- a/bin/install.sh +++ b/bin/install.sh @@ -17,7 +17,6 @@ #Actively load user env source ~/.bash_profile - shellDir=`dirname $0` workDir=`cd ${shellDir}/..;pwd` @@ -45,7 +44,14 @@ else exit 1 fi -source ${workDir}/bin/common.sh +function isSuccess(){ +if [ $? -ne 0 ]; then + echo "Failed to " + $1 + exit 1 +else + echo "Succeed to" + $1 +fi +} function checkPythonAndJava(){ python --version @@ -83,8 +89,8 @@ fi } function checkSpark(){ - spark-submit --version - isSuccess "execute spark-submit --version" + spark-submit --version + isSuccess "execute spark-submit --version" } say() { @@ -113,52 +119,66 @@ isSuccess "check env" ##load config echo "step1:load config " -export LINKIS_CONFIG_PATH=${LINKIS_CONFIG_PATH:-"${workDir}/conf/config.sh"} +export LINKIS_CONFIG_PATH=${LINKIS_CONFIG_PATH:-"${workDir}/conf/linkis-env.sh"} export LINKIS_DB_CONFIG_PATH=${LINKIS_DB_CONFIG_PATH:-"${workDir}/conf/db.sh"} -export DISTRIBUTION=${DISTRIBUTION:-"${workDir}/conf/config.sh"} source ${LINKIS_CONFIG_PATH} source ${LINKIS_DB_CONFIG_PATH} -source ${DISTRIBUTION} isSuccess "load config" +local_host="`hostname --fqdn`" + +ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') + +function isLocal(){ + if [ "$1" == "127.0.0.1" ];then + return 0 + elif [ $1 == "localhost" ]; then + return 0 + elif [ $1 == $local_host ]; then + return 0 + elif [ $1 == $ipaddr ]; then + return 0 + fi + return 1 +} +function executeCMD(){ + isLocal $1 + flag=$? + if [ $flag == "0" ];then + echo "Is local execution:$2" + eval $2 + else + echo "Is remote execution:$2" + ssh -p $SSH_PORT $1 $2 + fi +} +function copyFile(){ + isLocal $1 + flag=$? + src=$2 + dest=$3 + if [ $flag == "0" ];then + echo "Is local cp " + eval "cp -r $src $dest" + else + echo "Is remote cp " + scp -r -P $SSH_PORT $src $1:$dest + fi -##install mode choice -if [ "$INSTALL_MODE" == "" ];then - echo "Please enter the mode selection such as: 1" - echo " 1: Lite" - echo " 2: Simple" - echo " 3: Standard" - echo "" - read -p "Please input the choice:" idx - INSTALL_MODE=$idx -fi +} -if [[ '1' = "$INSTALL_MODE" ]];then - echo "You chose Lite installation mode" - checkPythonAndJava -elif [[ '2' = "$INSTALL_MODE" ]];then - echo "You chose Simple installation mode" - checkPythonAndJava - checkHadoopAndHive -elif [[ '3' = "$INSTALL_MODE" ]];then - echo "You chose Standard installation mode" - checkPythonAndJava - checkHadoopAndHive - checkSpark -else - echo "no choice,exit!" - exit 1 -fi ##env check echo "Do you want to clear Linkis table information in the database?" echo " 1: Do not execute table-building statements" echo " 2: Dangerous! Clear all data and rebuild the tables" +echo " other: exit" echo "" MYSQL_INSTALL_MODE=1 +#使用read参数[-p]后,允许在[-p]后面跟一字符串,在字符串后面跟n个shell变量。n个shell变量用来接收从shell界面输入的字符串 read -p "Please input the choice:" idx if [[ '2' = "$idx" ]];then MYSQL_INSTALL_MODE=2 @@ -171,7 +191,6 @@ else exit 1 fi - echo "create hdfs directory and local directory" if [ "$WORKSPACE_USER_ROOT_PATH" != "" ] then @@ -183,6 +202,7 @@ then elif [[ $WORKSPACE_USER_ROOT_PATH == hdfs://* ]];then localRootDir=${WORKSPACE_USER_ROOT_PATH#hdfs://} hdfs dfs -mkdir -p $localRootDir/$deployUser + hdfs dfs -chmod -R 775 $localRootDir/$deployUser else echo "does not support $WORKSPACE_USER_ROOT_PATH filesystem types" fi @@ -190,491 +210,147 @@ fi isSuccess "create $WORKSPACE_USER_ROOT_PATH directory" -if [ "$HDFS_USER_ROOT_PATH" != "" ] -then - localRootDir=$HDFS_USER_ROOT_PATH - if [[ $HDFS_USER_ROOT_PATH == file://* ]];then - localRootDir=${HDFS_USER_ROOT_PATH#file://} - mkdir -p $localRootDir/$deployUser - sudo chmod -R 775 $localRootDir/$deployUser - elif [[ $HDFS_USER_ROOT_PATH == hdfs://* ]];then - localRootDir=${HDFS_USER_ROOT_PATH#hdfs://} - hdfs dfs -mkdir -p $localRootDir/$deployUser - else - echo "does not support $HDFS_USER_ROOT_PATH filesystem types" - fi -fi -isSuccess "create $HDFS_USER_ROOT_PATH directory" - +######################## init hdfs and db ################################ + if [ "$HDFS_USER_ROOT_PATH" != "" ] + then + localRootDir=$HDFS_USER_ROOT_PATH + if [[ $HDFS_USER_ROOT_PATH == file://* ]];then + localRootDir=${HDFS_USER_ROOT_PATH#file://} + mkdir -p $localRootDir/$deployUser + sudo chmod -R 775 $localRootDir/$deployUser + elif [[ $HDFS_USER_ROOT_PATH == hdfs://* ]];then + localRootDir=${HDFS_USER_ROOT_PATH#hdfs://} + hdfs dfs -mkdir -p $localRootDir/$deployUser + hdfs dfs -chmod -R 775 $localRootDir/$deployUser + else + echo "does not support $HDFS_USER_ROOT_PATH filesystem types" + fi + fi + isSuccess "create $HDFS_USER_ROOT_PATH directory" + + + if [ "$RESULT_SET_ROOT_PATH" != "" ] + then + localRootDir=$RESULT_SET_ROOT_PATH + if [[ $RESULT_SET_ROOT_PATH == file://* ]];then + localRootDir=${RESULT_SET_ROOT_PATH#file://} + mkdir -p $localRootDir/$deployUser + sudo chmod -R 775 $localRootDir/$deployUser + elif [[ $RESULT_SET_ROOT_PATH == hdfs://* ]];then + localRootDir=${RESULT_SET_ROOT_PATH#hdfs://} + hdfs dfs -mkdir -p $localRootDir/$deployUser + hdfs dfs -chmod -R 775 $localRootDir/$deployUser + else + echo "does not support $RESULT_SET_ROOT_PATH filesystem types" + fi + fi + isSuccess "create $RESULT_SET_ROOT_PATH directory" -if [ "$RESULT_SET_ROOT_PATH" != "" ] +## sql init +if [ "$YARN_RESTFUL_URL" != "" ] then - localRootDir=$RESULT_SET_ROOT_PATH - if [[ $RESULT_SET_ROOT_PATH == file://* ]];then - localRootDir=${RESULT_SET_ROOT_PATH#file://} - mkdir -p $localRootDir/$deployUser - sudo chmod -R 775 $localRootDir/$deployUser - elif [[ $RESULT_SET_ROOT_PATH == hdfs://* ]];then - localRootDir=${RESULT_SET_ROOT_PATH#hdfs://} - hdfs dfs -mkdir -p $localRootDir/$deployUser - else - echo "does not support $RESULT_SET_ROOT_PATH filesystem types" - fi + sed -i ${txt} "s#@YARN_RESTFUL_URL#$YARN_RESTFUL_URL#g" $workDir/db/linkis_dml.sql fi -isSuccess "create $RESULT_SET_ROOT_PATH directory" -##init db -if [[ '2' = "$MYSQL_INSTALL_MODE" ]];then - mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD --default-character-set=utf8 -e "CREATE DATABASE IF NOT EXISTS $MYSQL_DB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;" - mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD -D$MYSQL_DB --default-character-set=utf8 -e "source ${workDir}/db/linkis_ddl.sql" - isSuccess "source linkis_ddl.sql" - mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD -D$MYSQL_DB --default-character-set=utf8 -e "source ${workDir}/db/linkis_dml.sql" - isSuccess "source linkis_dml.sql" - echo "Rebuild the table" -fi +common_conf=$workDir/conf/linkis.properties +SERVER_IP=$local_host -##Deal special symbol '#' -HIVE_META_PASSWORD=$(echo ${HIVE_META_PASSWORD//'#'/'\#'}) -MYSQL_PASSWORD=$(echo ${MYSQL_PASSWORD//'#'/'\#'}) - -##Eurkea install -SERVER_NAME=eureka -SERVER_IP=$EUREKA_INSTALL_IP -SERVER_PORT=$EUREKA_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -echo "$SERVER_NAME-step1: create dir" -if test -z "$SERVER_IP" +##Label set start +if [ "$SPARK_VERSION" != "" ] then - SERVER_IP=$local_host -fi -EUREKA_URL=http://$SERVER_IP:$EUREKA_PORT/eureka/ - -if ! executeCMD $SERVER_IP "test -e $SERVER_HOME"; then - executeCMD $SERVER_IP "sudo mkdir -p $SERVER_HOME;sudo chown -R $deployUser:$deployUser $SERVER_HOME" - isSuccess "create the dir of $SERVER_HOME" + sed -i ${txt} "s#spark-2.4.3#spark-$SPARK_VERSION#g" $workDir/db/linkis_dml.sql + executeCMD $SERVER_IP "sed -i ${txt} \"s#\#wds.linkis.spark.engine.version.*#wds.linkis.spark.engine.version=$SPARK_VERSION#g\" $common_conf" fi -echo "$SERVER_NAME-step2:copy install package" -copyFile $SERVER_IP ${workDir}/share/springcloud/$SERVER_NAME/$SERVER_NAME.zip $SERVER_HOME -isSuccess "copy $SERVER_NAME" -executeCMD $SERVER_IP "cd $SERVER_HOME/;rm -rf eureka;unzip $SERVER_NAME.zip > /dev/null;cd -" -echo "$SERVER_NAME-step3:subsitution conf" -eureka_conf_path=$SERVER_HOME/$SERVER_NAME/conf/application-$SERVER_NAME.yml -executeCMD $SERVER_IP "sed -i ${txt} \"s#port:.*#port: $SERVER_PORT#g\" $eureka_conf_path" -executeCMD $SERVER_IP "sed -i ${txt} \"s#defaultZone:.*#defaultZone: $EUREKA_URL#g\" $eureka_conf_path" -executeCMD $SERVER_IP "sed -i ${txt} \"s#hostname:.*#hostname: $SERVER_IP#g\" $eureka_conf_path" -isSuccess "subsitution conf of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##Eurkea install end - - - -##function -function installPackage(){ -echo "$SERVER_NAME-step1: create dir" -if test -z "$SERVER_IP" +if [ "$HIVE_VERSION" != "" ] then - SERVER_IP=$local_host + sed -i ${txt} "s#hive-1.2.1#hive-$HIVE_VERSION#g" $workDir/db/linkis_dml.sql + executeCMD $SERVER_IP "sed -i ${txt} \"s#\#wds.linkis.hive.engine.version.*#wds.linkis.hive.engine.version=$HIVE_VERSION#g\" $common_conf" fi -if ! executeCMD $SERVER_IP "test -e $SERVER_HOME"; then - executeCMD $SERVER_IP "sudo mkdir -p $SERVER_HOME;sudo chown -R $deployUser:$deployUser $SERVER_HOME" - isSuccess "create the dir of $SERVER_NAME" +if [ "$PYTHON_VERSION" != "" ] +then + sed -i ${txt} "s#python-python2#python-$PYTHON_VERSION#g" $workDir/db/linkis_dml.sql + executeCMD $SERVER_IP "sed -i ${txt} \"s#\#wds.linkis.python.engine.version.*#wds.linkis.python.engine.version=$PYTHON_VERSION#g\" $common_conf" fi -if ! executeCMD $SERVER_IP "test -e $SERVER_HOME/module"; then - copyFile $SERVER_IP ${workDir}/share/linkis/module/module.zip $SERVER_HOME - isSuccess "cp module.zip" - executeCMD $SERVER_IP "cd $SERVER_HOME/;unzip -o module.zip > /dev/null;cd -" - isSuccess "unzip module.zip" -fi +##Label set end -echo "$SERVER_NAME-step2:copy install package" -copyFile $SERVER_IP ${workDir}/share/$PACKAGE_DIR/$SERVER_NAME.zip $SERVER_HOME -isSuccess "copy ${SERVER_NAME}.zip" -executeCMD $SERVER_IP "cd $SERVER_HOME/;rm -rf $SERVER_NAME-bak; mv -f $SERVER_NAME $SERVER_NAME-bak;cd -" -executeCMD $SERVER_IP "cd $SERVER_HOME/;unzip -o $SERVER_NAME.zip > /dev/null; cd -" -isSuccess "unzip ${SERVER_NAME}.zip" -echo "$SERVER_NAME-step3:subsitution conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/application.yml -executeCMD $SERVER_IP "sed -i ${txt} \"s#port:.*#port: $SERVER_PORT#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#defaultZone:.*#defaultZone: $EUREKA_URL#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#hostname:.*#hostname: $SERVER_IP#g\" $SERVER_CONF_PATH" -isSuccess "subsitution conf of $SERVER_NAME" -} -##function end -##cp module to em lib -function emExtraInstallModule(){ - executeCMD $SERVER_IP "cd $SERVER_HOME/;cp -f module/lib/* $SERVER_HOME/$SERVER_NAME/lib/;cd -" - isSuccess "copy module" -} -##replace conf 1. replace if it exists 2.not exists add -function replaceConf(){ - option=$1 - value=$2 - file=$3 - executeCMD $SERVER_IP "grep -q '^$option' $file && sed -i ${txt} 's/^$option.*/$option=$value/' $file || echo '$option=$value' >> $file" - isSuccess "copy module" -} +#init db +if [[ '2' = "$MYSQL_INSTALL_MODE" ]];then + mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD --default-character-set=utf8 -e "CREATE DATABASE IF NOT EXISTS $MYSQL_DB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;" + mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD -D$MYSQL_DB --default-character-set=utf8 -e "source ${workDir}/db/linkis_ddl.sql" + isSuccess "source linkis_ddl.sql" + mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD -D$MYSQL_DB --default-character-set=utf8 -e "source ${workDir}/db/linkis_dml.sql" + isSuccess "source linkis_dml.sql" + echo "Rebuild the table" +fi +########################################################################### +#Deal special symbol '#' +HIVE_META_PASSWORD=$(echo ${HIVE_META_PASSWORD//'#'/'\#'}) +MYSQL_PASSWORD=$(echo ${MYSQL_PASSWORD//'#'/'\#'}) +#Deal common config +echo "Update common config..." -##GateWay Install -PACKAGE_DIR=springcloud/gateway -SERVER_NAME=linkis-gateway -SERVER_IP=$GATEWAY_INSTALL_IP -SERVER_PORT=$GATEWAY_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -if test -z "$SERVER_IP" +if test -z "$GATEWAY_INSTALL_IP" then - GATEWAY_INSTALL_IP=$local_host + export GATEWAY_INSTALL_IP="`hostname --fqdn`" fi -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.ldap.proxy.url.*#wds.linkis.ldap.proxy.url=$LDAP_URL#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.ldap.proxy.baseDN.*#wds.linkis.ldap.proxy.baseDN=$LDAP_BASEDN#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.gateway.admin.user.*#wds.linkis.gateway.admin.user=$deployUser#g\" $SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##GateWay Install end - -##publicservice install -PACKAGE_DIR=linkis/linkis-publicservice -SERVER_NAME=linkis-publicservice -SERVER_IP=$PUBLICSERVICE_INSTALL_IP -SERVER_PORT=$PUBLICSERVICE_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.workspace.filesystem.localuserrootpath.*#wds.linkis.workspace.filesystem.localuserrootpath=$WORKSPACE_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.workspace.filesystem.hdfsuserrootpath.prefix.*#wds.linkis.workspace.filesystem.hdfsuserrootpath.prefix=$HDFS_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##publicservice end - -##ResourceManager install -PACKAGE_DIR=linkis/rm -SERVER_NAME=linkis-resourcemanager -SERVER_IP=$RESOURCEMANAGER_INSTALL_IP -SERVER_PORT=$RESOURCEMANAGER_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "rm $SERVER_HOME/$SERVER_NAME/lib/json4s-*3.5.3.jar" -echo "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##ResourceManager install end - - -##PythonEM install -PACKAGE_DIR=linkis/ujes/python -SERVER_NAME=linkis-ujes-python-enginemanager -SERVER_IP=$PYTHON_INSTALL_IP -SERVER_PORT=$PYTHON_EM_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -emExtraInstallModule -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.enginemanager.sudo.script.*#wds.linkis.enginemanager.sudo.script=$SERVER_HOME/$SERVER_NAME/bin/rootScript.sh#g\" $SERVER_CONF_PATH" -SERVER_ENGINE_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis-engine.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_ENGINE_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" - - -##PythonEntrance install -PACKAGE_DIR=linkis/ujes/python -SERVER_NAME=linkis-ujes-python-entrance -SERVER_PORT=$PYTHON_ENTRANCE_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.entrance.config.logPath.*#wds.linkis.entrance.config.logPath=$WORKSPACE_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.resultSet.store.path.*#wds.linkis.resultSet.store.path=$RESULT_SET_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##PythonEntrance install end - -if [[ '1' = "$INSTALL_MODE" ]];then - echo "Lite install end" - exit 0 -fi +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.version.*#wds.linkis.server.version=$LINKIS_SERVER_VERSION#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.gateway.url.*#wds.linkis.gateway.url=http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.eureka.defaultZone.*#wds.linkis.eureka.defaultZone=$EUREKA_URL#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $common_conf" + +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.ldap.proxy.url.*#wds.linkis.ldap.proxy.url=$LDAP_URL#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.ldap.proxy.baseDN.*#wds.linkis.ldap.proxy.baseDN=$LDAP_BASEDN#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.ldap.proxy.userNameFormat.*#wds.linkis.ldap.proxy.userNameFormat=$LDAP_USER_NAME_FORMAT#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.admin.user.*#wds.linkis.gateway.admin.user=$deployUser#g\" $common_conf" +# hadoop config +executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $common_conf" +#hive config +executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hive.config.dir.*#hive.config.dir=$HIVE_CONF_DIR#g\" $common_conf" + +#spark config +executeCMD $SERVER_IP "sed -i ${txt} \"s#spark.config.dir.*#spark.config.dir=$SPARK_CONF_DIR#g\" $common_conf" -##BML install -PACKAGE_DIR=linkis/linkis-bml -SERVER_NAME=linkis-bml -SERVER_IP=$BML_INSTALL_IP -SERVER_PORT=$BML_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVERNAME" -echo "<----------------$SERVER_NAME:end------------------->" -##BML end - -##linkis-metadata install -PACKAGE_DIR=linkis/linkis-metadata -SERVER_NAME=linkis-metadata -SERVER_IP=$METADATA_INSTALL_IP -SERVER_PORT=$METADATA_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hive.config.dir.*#hive.config.dir=$HIVE_CONF_DIR#g\" $SERVER_CONF_PATH" if [ "$HIVE_META_URL" != "" ] then - executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.url.*#hive.meta.url=$HIVE_META_URL#g\" $SERVER_CONF_PATH" + executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.url.*#hive.meta.url=$HIVE_META_URL#g\" $common_conf" fi if [ "$HIVE_META_USER" != "" ] then - executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.user.*#hive.meta.user=$HIVE_META_USER#g\" $SERVER_CONF_PATH" + executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.user.*#hive.meta.user=$HIVE_META_USER#g\" $common_conf" fi if [ "$HIVE_META_PASSWORD" != "" ] then HIVE_META_PASSWORD=$(echo ${HIVE_META_PASSWORD//'#'/'\#'}) - executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.password.*#hive.meta.password=$HIVE_META_PASSWORD#g\" $SERVER_CONF_PATH" -fi -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##metadata end - -##linkis-cs-server install -PACKAGE_DIR=linkis/linkis-cs-server -SERVER_NAME=linkis-cs-server -SERVER_IP=$CS_INSTALL_IP -SERVER_PORT=$CS_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##cs end - -##HiveEM install -PACKAGE_DIR=linkis/ujes/hive -SERVER_NAME=linkis-ujes-hive-enginemanager -SERVER_IP=$HIVE_INSTALL_IP -SERVER_PORT=$HIVE_EM_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -emExtraInstallModule -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.enginemanager.sudo.script.*#wds.linkis.enginemanager.sudo.script=$SERVER_HOME/$SERVER_NAME/bin/rootScript.sh#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hive.config.dir.*#hive.config.dir=$HIVE_CONF_DIR#g\" $SERVER_CONF_PATH" -SERVER_ENGINE_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis-engine.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hive.config.dir.*#hive.config.dir=$HIVE_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_ENGINE_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -executeCMD $SERVER_IP "rm $SERVER_HOME/$SERVER_NAME/lib/guava-25.1-jre.jar" -executeCMD $SERVER_IP "rm $SERVER_HOME/$SERVER_NAME/lib/servlet-api-2.5.jar" -echo "<----------------$SERVER_NAME:end------------------->" -##HiveEM install end - -##HiveEntrance install -PACKAGE_DIR=linkis/ujes/hive -SERVER_NAME=linkis-ujes-hive-entrance -SERVER_PORT=$HIVE_ENTRANCE_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.entrance.config.logPath.*#wds.linkis.entrance.config.logPath=$WORKSPACE_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.resultSet.store.path.*#wds.linkis.resultSet.store.path=$RESULT_SET_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##HiveEntrance install end - - -if [[ '2' = "$INSTALL_MODE" ]];then - echo "Simple install end" - exit 0 + executeCMD $SERVER_IP "sed -i ${txt} \"s#hive.meta.password.*#hive.meta.password=$HIVE_META_PASSWORD#g\" $common_conf" fi -if [[ '3' != "$INSTALL_MODE" ]];then - exit 0 + +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.filesystem.root.path.*#wds.linkis.filesystem.root.path=$WORKSPACE_USER_ROOT_PATH#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.filesystem.hdfs.root.path.*#wds.linkis.filesystem.hdfs.root.path=$HDFS_USER_ROOT_PATH#g\" $common_conf" + +# engineconn +if test -z $ENGINECONN_ROOT_PATH +then + ENGINECONN_ROOT_PATH=$workDir/engineroot fi +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.engineconn.root.dir.*#wds.linkis.engineconn.root.dir=$ENGINECONN_ROOT_PATH#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.engineconn.home.*#wds.linkis.engineconn.home=${workDir}/lib/linkis-engineconn-plugins#g\" $common_conf" +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.engineconn.plugin.loader.store.path.*#wds.linkis.engineconn.plugin.loader.store.path=${workDir}/lib/linkis-engineconn-plugins#g\" $common_conf" + +# common lib +executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.public_module.path.*#wds.linkis.public_module.path=${workDir}/lib/linkis-commons/public-module#g\" $common_conf" + +echo "Congratulations! You have installed Linkis $LINKIS_VERSION successfully, please use sbin/start-all.sh to start it!" + + + -##SparkEM install -PACKAGE_DIR=linkis/ujes/spark -SERVER_NAME=linkis-ujes-spark-enginemanager -SERVER_IP=$SPARK_INSTALL_IP -SERVER_PORT=$SPARK_EM_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -emExtraInstallModule -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -ENGINE_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis-engine.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.enginemanager.sudo.script.*#wds.linkis.enginemanager.sudo.script=$SERVER_HOME/$SERVER_NAME/bin/rootScript.sh#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.enginemanager.core.jar.*#wds.linkis.enginemanager.core.jar=$SERVER_HOME/$SERVER_NAME/lib/linkis-ujes-spark-engine-$LINKIS_VERSION.jar#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.spark.driver.conf.mainjar.*#wds.linkis.spark.driver.conf.mainjar=$SERVER_HOME/$SERVER_NAME/conf:$SERVER_HOME/$SERVER_NAME/lib/*#g\" $SERVER_CONF_PATH" -SERVER_ENGINE_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis-engine.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#spark.config.dir.*#spark.config.dir=$SPARK_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_ENGINE_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##SparkEM install end - -##SparkEntrance install -PACKAGE_DIR=linkis/ujes/spark -SERVER_NAME=linkis-ujes-spark-entrance -SERVER_PORT=$SPARK_ENTRANCE_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.entrance.config.logPath.*#wds.linkis.entrance.config.logPath=$WORKSPACE_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.resultSet.store.path.*#wds.linkis.resultSet.store.path=$HDFS_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##SparkEntrance install end - - -##JDBCEntrance install -PACKAGE_DIR=linkis/ujes/jdbc -SERVER_NAME=linkis-ujes-jdbc-entrance -SERVER_IP=$JDBC_INSTALL_IP -SERVER_PORT=$JDBC_ENTRANCE_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.entrance.config.logPath.*#wds.linkis.entrance.config.logPath=$WORKSPACE_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.resultSet.store.path.*#wds.linkis.resultSet.store.path=$HDFS_USER_ROOT_PATH#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##JDBCEntrance install end - - -##ShellEM install -PACKAGE_DIR=linkis/ujes/shell -SERVER_NAME=linkis-ujes-shell-enginemanager -SERVER_IP=$SHELL_INSTALL_IP -SERVER_PORT=$SHELL_EM_PORT -SERVER_HOME=$LINKIS_INSTALL_HOME -###install dir -installPackage -emExtraInstallModule -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.enginemanager.sudo.script.*#wds.linkis.enginemanager.sudo.script=$SERVER_HOME/$SERVER_NAME/bin/rootScript.sh#g\" $SERVER_CONF_PATH" -SERVER_ENGINE_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis-engine.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_ENGINE_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_ENGINE_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" - -##SHELLEntrance install -PACKAGE_DIR=linkis/ujes/shell -SERVER_NAME=linkis-ujes-shell-entrance -SERVER_PORT=$SHELL_ENTRANCE_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#\#hadoop.config.dir.*#hadoop.config.dir=$HADOOP_CONF_DIR#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##SHELLEntrance install end - - -##Datasource Manager Server install -PACKAGE_DIR=linkis/datasource/linkis-dsm-server -SERVER_NAME=linkis-dsm-server -SERVER_PORT=$DSM_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.url.*#wds.linkis.server.mybatis.datasource.url=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=UTF-8#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.username.*#wds.linkis.server.mybatis.datasource.username=$MYSQL_USER#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.mybatis.datasource.password.*#wds.linkis.server.mybatis.datasource.password=$MYSQL_PASSWORD#g\" $SERVER_CONF_PATH" -executeCMD $SERVER_IP "sed -i ${txt} \"s#wds.linkis.server.dsm.admin.users.*#wds.linkis.server.dsm.admin.users=$deployUser#g\" $SERVER_CONF_PATH" -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##Datasource Manager Server install end - - - -##Metadata Manager Server install -PACKAGE_DIR=linkis/datasource/linkis-mdm-server -SERVER_NAME=linkis-mdm-server -SERVER_PORT=$MDM_PORT -###install dir -installPackage -###update linkis.properties -echo "$SERVER_NAME-step4:update linkis conf" -SERVER_CONF_PATH=$SERVER_HOME/$SERVER_NAME/conf/linkis.properties -replaceConf "wds.linkis.gateway.url" "http://$GATEWAY_INSTALL_IP:$GATEWAY_PORT" "$SERVER_CONF_PATH" -isSuccess "subsitution linkis.properties of $SERVER_NAME" -echo "<----------------$SERVER_NAME:end------------------->" -##Metadata Manager Server install end diff --git a/bin/start-all.sh b/bin/start-all.sh deleted file mode 100755 index 05f5046984..0000000000 --- a/bin/start-all.sh +++ /dev/null @@ -1,314 +0,0 @@ -#!/usr/bin/env bash -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - - -# Start all linkis applications -info="We will start all linkis applications, it will take some time, please wait" -echo ${info} - -#Actively load user env -source /etc/profile -source ~/.bash_profile - -shellDir=`dirname $0` -workDir=`cd ${shellDir}/..;pwd` - -CONF_DIR="${workDir}"/conf -export LINKIS_DSS_CONF_FILE=${LINKIS_DSS_CONF_FILE:-"${CONF_DIR}/config.sh"} -export DISTRIBUTION=${DISTRIBUTION:-"${CONF_DIR}/config.sh"} -#source $LINKIS_DSS_CONF_FILE -source ${DISTRIBUTION} - -source ${workDir}/bin/common.sh - - -local_host="`hostname --fqdn`" - -ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}'|awk 'NR==1') - -function isLocal(){ - if [ "$1" == "127.0.0.1" ];then - return 0 - elif [ $1 == "localhost" ]; then - return 0 - elif [ $1 == $local_host ]; then - return 0 - elif [ $1 == $ipaddr ]; then - return 0 - fi - return 1 -} - -function executeCMD(){ - isLocal $1 - flag=$? - echo "Is local "$flag - if [ $flag == "0" ];then - eval $2 - else - ssh -p $SSH_PORT $1 $2 - fi - -} - - -#if there is no LINKIS_INSTALL_HOME,we need to source config again -if [ -z ${LINKIS_INSTALL_HOME} ];then - echo "Info: LINKIS_INSTALL_HOME does not exist, we will source config" - if [ ! -f "${LINKIS_DSS_CONF_FILE}" ];then - echo "Error: can not find config file, start applications failed" - exit 1 - else - source ${LINKIS_DSS_CONF_FILE} - fi -fi -APP_PREFIX="linkis-" - -function startApp(){ -echo "<-------------------------------->" -echo "Begin to start $SERVER_NAME" -SERVER_PATH=${APP_PREFIX}${SERVER_NAME} - -SERVER_BIN=${LINKIS_INSTALL_HOME}/${SERVER_PATH}/bin -SERVER_LOCAL_START_CMD="dos2unix ${SERVER_BIN}/* > /dev/null 2>&1; dos2unix ${SERVER_BIN}/../conf/* > /dev/null 2>&1; sh ${SERVER_BIN}/start-${SERVER_NAME}.sh" -SERVER_REMOTE_START_CMD="source /etc/profile;source ~/.bash_profile;cd ${SERVER_BIN}; dos2unix ./* > /dev/null 2>&1; dos2unix ../conf/* > /dev/null 2>&1; sh start-${SERVER_NAME}.sh > /dev/null 2>&1" -if test -z "$SERVER_IP" -then - SERVER_IP=$local_host -fi - -if ! executeCMD $SERVER_IP "test -e $SERVER_BIN"; then - echo "$SERVER_NAME is not installed,the startup steps will be skipped" - return -fi - -isLocal $SERVER_IP -flag=$? -echo "Is local "$flag -if [ $flag == "0" ];then - eval $SERVER_LOCAL_START_CMD -else - ssh -p $SSH_PORT $SERVER_IP $SERVER_REMOTE_START_CMD -fi -isSuccess "End to start $SERVER_NAME" -echo "<-------------------------------->" -sleep 3 -} - - -#eureka -SERVER_NAME="eureka" -APP_PREFIX="" -SERVER_IP=$EUREKA_INSTALL_IP -startApp - - -APP_PREFIX="linkis-" -#gateway -SERVER_NAME="gateway" -SERVER_IP=$GATEWAY_INSTALL_IP -startApp - -#publicservice -SERVER_NAME="publicservice" -SERVER_IP=$PUBLICSERVICE_INSTALL_IP -startApp - - -#metadata -SERVER_NAME="metadata" -SERVER_IP=$METADATA_INSTALL_IP -startApp - -#bml -SERVER_NAME="bml" -SERVER_IP=$BML_INSTALL_IP -startApp - -#cs-server -SERVER_NAME="cs-server" -SERVER_IP=$CS_INSTALL_IP -startApp - -#datasource management -SERVER_NAME="dsm-server" -SERVER_IP=$DSM_INSTALL_IP -startApp - -#metadata management -SERVER_NAME="mdm-server" -SERVER_IP=$MDM_INSTALL_IP -startApp - -#resourcemanager -SERVER_NAME="resourcemanager" -SERVER_IP=$RESOURCEMANAGER_INSTALL_IP -startApp -echo "sleep 15 seconds to wait RM to be ready" -sleep 15 - -APP_PREFIX="linkis-ujes-" - -#python-entrance -SERVER_NAME="python-entrance" -SERVER_IP=$PYTHON_INSTALL_IP -startApp - -#python-enginemanager -SERVER_NAME="python-enginemanager" -SERVER_IP=$PYTHON_INSTALL_IP -startApp - -#shell-entrance -SERVER_NAME="shell-entrance" -SERVER_IP=$SHELL_INSTALL_IP -startApp - -#shell-enginemanager -SERVER_NAME="shell-enginemanager" -SERVER_IP=$SHELL_INSTALL_IP -startApp - -#spark-entrance -SERVER_NAME="spark-entrance" -SERVER_IP=$SPARK_INSTALL_IP -startApp - -#spark-enginemanager -SERVER_NAME="spark-enginemanager" -SERVER_IP=$SPARK_INSTALL_IP -startApp - -#hive-entrance -SERVER_NAME="hive-entrance" -SERVER_IP=$HIVE_INSTALL_IP -startApp - - -#hive-enginemanager -SERVER_NAME="hive-enginemanager" -SERVER_IP=$HIVE_INSTALL_IP -startApp - - -#JDBCEntrance -SERVER_NAME="jdbc-entrance" -SERVER_IP=$JDBC_INSTALL_IP -startApp - - - -echo "start-all shell script executed completely" - -echo "Start to check all dss microservice" - -function checkServer(){ -echo "<-------------------------------->" -echo "Begin to check $SERVER_NAME" -if test -z "$SERVER_IP" -then - SERVER_IP=$local_host -fi - -SERVER_BIN=${LINKIS_INSTALL_HOME}/$SERVER_NAME/bin - -if ! executeCMD $SERVER_IP "test -e $SERVER_BIN"; then - echo "$SERVER_NAME is not installed,the checkServer steps will be skipped" - return -fi - -sh $workDir/bin/checkServices.sh $SERVER_NAME $SERVER_IP $SERVER_PORT -isSuccess "start $SERVER_NAME " -echo "<-------------------------------->" -sleep 5 -} -SERVER_NAME="eureka" -SERVER_IP=$EUREKA_INSTALL_IP -SERVER_PORT=$EUREKA_PORT -checkServer - -APP_PREFIX="linkis-" -SERVER_NAME=$APP_PREFIX"gateway" -SERVER_IP=$GATEWAY_INSTALL_IP -SERVER_PORT=$GATEWAY_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"publicservice" -SERVER_IP=$PUBLICSERVICE_INSTALL_IP -SERVER_PORT=$PUBLICSERVICE_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"metadata" -SERVER_IP=$METADATA_INSTALL_IP -SERVER_PORT=$METADATA_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"resourcemanager" -SERVER_IP=$RESOURCEMANAGER_INSTALL_IP -SERVER_PORT=$RESOURCEMANAGER_PORT -checkServer - - -SERVER_NAME=$APP_PREFIX"bml" -SERVER_IP=$BML_INSTALL_IP -SERVER_PORT=$BML_PORT -checkServer - -#cs-server -SERVER_NAME="cs-server" -SERVER_IP=$CS_INSTALL_IP -checkServer - -APP_PREFIX="linkis-ujes-" -SERVER_NAME=$APP_PREFIX"python-entrance" -SERVER_IP=$PYTHON_INSTALL_IP -SERVER_PORT=$PYTHON_ENTRANCE_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"python-enginemanager" -SERVER_IP=$PYTHON_INSTALL_IP -SERVER_PORT=$PYTHON_EM_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"spark-entrance" -SERVER_IP=$SPARK_INSTALL_IP -SERVER_PORT=$SPARK_ENTRANCE_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"spark-enginemanager" -SERVER_IP=$SPARK_INSTALL_IP -SERVER_PORT=$SPARK_EM_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"hive-enginemanager" -SERVER_IP=$HIVE_INSTALL_IP -SERVER_PORT=$HIVE_EM_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"hive-entrance" -SERVER_IP=$HIVE_INSTALL_IP -SERVER_PORT=$HIVE_ENTRANCE_PORT -checkServer - -SERVER_NAME=$APP_PREFIX"jdbc-entrance" -SERVER_IP=$JDBC_INSTALL_IP -SERVER_PORT=$JDBC_ENTRANCE_PORT -checkServer - - -echo "Linkis started successfully" diff --git a/bin/stop-all.sh b/bin/stop-all.sh deleted file mode 100755 index 098a5772b7..0000000000 --- a/bin/stop-all.sh +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env bash -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - - -# Stop all linkis applications -info="We will stop all linkis applications, it will take some time, please wait" -echo ${info} - -#Actively load user env -source /etc/profile -source ~/.bash_profile - -workDir=`dirname "${BASH_SOURCE-$0}"` -workDir=`cd "$workDir"; pwd` - - -CONF_DIR="${workDir}"/../conf -export LINKIS_DSS_CONF_FILE=${LINKIS_DSS_CONF_FILE:-"${CONF_DIR}/config.sh"} -export DISTRIBUTION=${DISTRIBUTION:-"${CONF_DIR}/config.sh"} -source ${DISTRIBUTION} -function isSuccess(){ -if [ $? -ne 0 ]; then - echo "ERROR: " + $1 - exit 1 -else - echo "INFO:" + $1 -fi -} - - -local_host="`hostname --fqdn`" - -ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}'|awk 'NR==1') - -function isLocal(){ - if [ "$1" == "127.0.0.1" ];then - return 0 - elif [ $1 == "localhost" ]; then - return 0 - elif [ $1 == $local_host ]; then - return 0 - elif [ $1 == $ipaddr ]; then - return 0 - fi - return 1 -} - - -source ${workDir}/bin/common.sh - - -#if there is no LINKIS_INSTALL_HOME,we need to source config again -if [ -z ${LINKIS_INSTALL_HOME} ];then - echo "Warning: LINKIS_INSTALL_HOME does not exist, we will source config" - if [ ! -f "${LINKIS_DSS_CONF_FILE}" ];then - echo "Error: can not find config file, stop applications failed" - exit 1 - else - source ${LINKIS_DSS_CONF_FILE} - fi -fi -APP_PREFIX="linkis-" - -function stopApp(){ -echo "<-------------------------------->" -echo "Begin to stop $SERVER_NAME" -SERVER_PATH=${APP_PREFIX}${SERVER_NAME} -SERVER_BIN=${LINKIS_INSTALL_HOME}/${SERVER_PATH}/bin -SERVER_LOCAL_STOP_CMD="sh ${SERVER_BIN}/stop-${SERVER_NAME}.sh" -SERVER_REMOTE_STOP_CMD="source /etc/profile;source ~/.bash_profile;cd ${SERVER_BIN}; sh stop-${SERVER_NAME}.sh " -if test -z "$SERVER_IP" -then - SERVER_IP=$local_host -fi - -if ! executeCMD $SERVER_IP "test -e $SERVER_BIN"; then - echo "$SERVER_NAME is not installed,the stopApp steps will be skipped" - return -fi - -isLocal $SERVER_IP -flag=$? -echo "Is local "$flag -if [ $flag == "0" ];then - eval $SERVER_LOCAL_STOP_CMD -else - ssh -p $SSH_PORT $SERVER_IP $SERVER_REMOTE_STOP_CMD -fi -echo "<-------------------------------->" -sleep 3 -} - - -#eureka -SERVER_NAME="eureka" -APP_PREFIX="" -SERVER_IP=$EUREKA_INSTALL_IP -stopApp - - -APP_PREFIX="linkis-" -#gateway -SERVER_NAME="gateway" -SERVER_IP=$GATEWAY_INSTALL_IP -stopApp - -#publicservice -SERVER_NAME="publicservice" -SERVER_IP=$PUBLICSERVICE_INSTALL_IP -stopApp - -#bml -SERVER_NAME="bml" -SERVER_IP=$BML_INSTALL_IP -stopApp - - -#metadata -SERVER_NAME="metadata" -SERVER_IP=$METADATA_INSTALL_IP -stopApp - -#cs-server -SERVER_NAME="cs-server" -SERVER_IP=$CS_INSTALL_IP -stopApp - -#datasource management -SERVER_NAME="dsm-server" -SERVER_IP=$DSM_INSTALL_IP -stopApp - -#metadata management -SERVER_NAME="mdm-server" -SERVER_IP=$MDM_INSTALL_IP -stopApp - -APP_PREFIX="linkis-ujes-" - -#python-entrance -SERVER_NAME="python-entrance" -SERVER_IP=$PYTHON_INSTALL_IP -stopApp - -#python-enginemanager -SERVER_NAME="python-enginemanager" -SERVER_IP=$PYTHON_INSTALL_IP -stopApp - -#shell-entrance -SERVER_NAME="shell-entrance" -SERVER_IP=$SHELL_INSTALL_IP -stopApp - -#shell-enginemanager -SERVER_NAME="shell-enginemanager" -SERVER_IP=$SHELL_INSTALL_IP -stopApp - -#spark-entrance -SERVER_NAME="spark-entrance" -SERVER_IP=$SPARK_INSTALL_IP -stopApp - -#spark-enginemanager -SERVER_NAME="spark-enginemanager" -SERVER_IP=$SPARK_INSTALL_IP -stopApp - -#hive-entrance -SERVER_NAME="hive-entrance" -SERVER_IP=$HIVE_INSTALL_IP -stopApp - - -#hive-enginemanager -SERVER_NAME="hive-enginemanager" -SERVER_IP=$HIVE_INSTALL_IP -stopApp - -#cs-server -SERVER_NAME="cs-server" -SERVER_IP=$CS_INSTALL_IP -stopApp - - -#JDBCEntrance -SERVER_NAME="jdbc-entrance" -SERVER_IP=$JDBC_INSTALL_IP -stopApp - -SERVER_NAME="pipeline-entrance" -SERVER_IP=$PIPELINE_INSTALL_IP -stopApp - -SERVER_NAME="pipeline-enginemanager" -SERVER_IP=$PIPELINE_INSTALL_IP -stopApp - -SERVER_NAME="io-enginemanager" -SERVER_IP=$IO_INSTALL_IP -stopApp - - - -APP_PREFIX="linkis-" -#resourcemanager -SERVER_NAME="resourcemanager" -SERVER_IP=$RESOURCEMANAGER_INSTALL_IP -stopApp - -echo "stop-all shell script executed completely" diff --git a/bml/bml-engine-hook/pom.xml b/bml/bml-engine-hook/pom.xml deleted file mode 100644 index 0559429359..0000000000 --- a/bml/bml-engine-hook/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-bml-hook - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - com.webank.wedatasphere.linkis - linkis-bmlclient - - - org.apache.httpcomponents - httpclient - - - org.apache.httpcomponents - httpcore - - - org.apache.httpcomponents - httpcore - - - org.eclipse.jetty - jetty-servlet - - - org.eclipse.jetty - jetty-security - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-http - - - org.eclipse.jetty - jetty-util - - - org.eclipse.jetty - jetty-io - - - javax.servlet - javax.servlet-api - - - - - com.webank.wedatasphere.linkis - linkis-storage - provided - - - com.webank.wedatasphere.linkis - linkis-ujes-engine - provided - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - - - - \ No newline at end of file diff --git a/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/conf/BmlHookConf.scala b/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/conf/BmlHookConf.scala deleted file mode 100644 index 6ba4f2f9c8..0000000000 --- a/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/conf/BmlHookConf.scala +++ /dev/null @@ -1,12 +0,0 @@ -package com.webank.wedatasphere.linkis.bml.conf - -import com.webank.wedatasphere.linkis.bml.utils.BmlHookUtils -import com.webank.wedatasphere.linkis.common.conf.CommonVars - -/** - * created by cooperyang on 2019/9/23 - * Description: - */ -object BmlHookConf { - val WORK_DIR_STR = CommonVars("wds.linkis.bml.work.dir", BmlHookUtils.getCurrentWorkDir) -} diff --git a/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/hook/BmlEnginePreExecuteHook.scala b/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/hook/BmlEnginePreExecuteHook.scala deleted file mode 100644 index 398d857f76..0000000000 --- a/bml/bml-engine-hook/src/main/scala/com/webank/wedatasphere/linkis/bml/hook/BmlEnginePreExecuteHook.scala +++ /dev/null @@ -1,89 +0,0 @@ -package com.webank.wedatasphere.linkis.bml.hook - -import java.io.File -import java.util - -import com.webank.wedatasphere.linkis.bml.client.{BmlClient, BmlClientFactory} -import com.webank.wedatasphere.linkis.bml.conf.BmlHookConf -import com.webank.wedatasphere.linkis.bml.exception.BmlHookDownloadException -import com.webank.wedatasphere.linkis.bml.utils.BmlHookUtils -import com.webank.wedatasphere.linkis.common.exception.ErrorException -import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} -import com.webank.wedatasphere.linkis.engine.ResourceExecuteRequest -import com.webank.wedatasphere.linkis.engine.execute.EngineExecutorContext -import com.webank.wedatasphere.linkis.engine.extension.EnginePreExecuteHook -import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest -import org.apache.commons.lang.StringUtils - -import scala.collection.JavaConversions._ -/** - * created by cooperyang on 2019/9/23 - * Description: - */ -class BmlEnginePreExecuteHook extends EnginePreExecuteHook with Logging{ - override val hookName: String = "BmlEnginePreExecuteHook" - - val RESOURCES_STR = "resources" - - val RESOURCE_ID_STR = "resourceId" - - val VERSION_STR = "version" - - val FILE_NAME_STR = "fileName" - - val processUser:String = System.getProperty("user.name") - - val defaultUser:String = "hadoop" - - val bmlClient:BmlClient = if (StringUtils.isNotEmpty(processUser)) - BmlClientFactory.createBmlClient(processUser) else BmlClientFactory.createBmlClient(defaultUser) - - val seperator:String = File.separator - - val pathType:String = "file://" - - override def callPreExecuteHook(engineExecutorContext: EngineExecutorContext, executeRequest: ExecuteRequest, code: String): String = { - val workDir = BmlHookConf.WORK_DIR_STR.getValue - val jobId = engineExecutorContext.getJobId - var hookCode = code - executeRequest match { - case resourceExecuteRequest:ResourceExecuteRequest => val resources = resourceExecuteRequest.resources - if (null == resources) return hookCode - val resourcePaths = resources map { - case resource:util.Map[String, Object] => val fileName = resource.get(FILE_NAME_STR).toString - val resourceId = resource.get(RESOURCE_ID_STR).toString - val version = resource.get(VERSION_STR).toString - val fullPath = if (workDir.endsWith(seperator)) pathType + workDir + fileName else - pathType + workDir + seperator + fileName - val response = Utils.tryCatch{ - bmlClient.downloadResource(processUser, resourceId, version, fullPath, true) - }{ - case error:ErrorException => logger.error("download resource for {} failed", error) - throw error - case t:Throwable => logger.error(s"download resource for $jobId failed", t) - val e1 = BmlHookDownloadException(t.getMessage) - e1.initCause(t) - throw t - } - if (response.isSuccess){ - logger.info(s"for job $jobId resourceId $resourceId version $version download to path $fullPath ok") - fullPath - }else{ - logger.warn(s"for job $jobId resourceId $resourceId version $version download to path $fullPath Failed") - null - } - case _ => - logger.warn("job resource cannot download") - null - } - hookCode = if (StringUtils.isNotBlank(hookCode)) hookCode else executeRequest.code - hookCode = callResourcesDownloadedHook(resourcePaths.toArray, engineExecutorContext, executeRequest, hookCode) - case _ => - } - if (StringUtils.isNotBlank(hookCode)) hookCode else executeRequest.code - } - - def callResourcesDownloadedHook(resourcePaths: Array[String], engineExecutorContext: EngineExecutorContext, executeRequest: ExecuteRequest, code: String): String = { - code - } -} diff --git a/bml/bmlclient/pom.xml b/bml/bmlclient/pom.xml deleted file mode 100644 index ffe447048b..0000000000 --- a/bml/bmlclient/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-bmlclient - - - - 4.4 - - - - - com.webank.wedatasphere.linkis - linkis-bmlcommon - - - - com.webank.wedatasphere.linkis - linkis-storage - provided - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - com.webank.wedatasphere.linkis - linkis-gateway-httpclient-support - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - - - - - - - \ No newline at end of file diff --git a/bml/bmlclient/src/main/java/com/webank/wedatasphere/linkis/bml/client/BmlClient.java b/bml/bmlclient/src/main/java/com/webank/wedatasphere/linkis/bml/client/BmlClient.java deleted file mode 100644 index e8d5a55210..0000000000 --- a/bml/bmlclient/src/main/java/com/webank/wedatasphere/linkis/bml/client/BmlClient.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.client; - -import com.webank.wedatasphere.linkis.bml.protocol.*; - -import java.io.InputStream; - -/** - * created by cooperyang on 2019/5/15 - * Description: - */ -public interface BmlClient { - /** - * 传入resourceID bmlclient会resource的输入流,如果不传入version,默认返回最新的版本 - * @param resourceID resourceID - * @return InputStream - */ - public BmlDownloadResponse downloadResource(String user, String resourceID); - - public BmlDownloadResponse downloadResource(String user, String resourceId, String version); - - - public BmlDownloadResponse downloadResource(String user, String resourceId, String version, String path, boolean overwrite); - - - /** - * relateResource方法将targetFilePath路径的文件关联到resourceID下面 - * targetFilePath需要包括schema,如果不包含schema,默认是hdfs - * @param resourceID resourceID - * @param targetFilePath 指定文件目录 - * @return BmlRelateResult 包含resourceId和新的version - */ - public BmlRelateResponse relateResource(String resourceID, String targetFilePath); - - - /** - * 更新资源信息 - * @param resourceID 资源id - * @param filePath 目标文件路径 - * @return resourceId 新的版本信息 - */ - - public BmlUpdateResponse updateResource(String user, String resourceID, String filePath); - - public BmlUpdateResponse updateResource(String user, String resourceID, String filePath, InputStream inputStream); - - - - - /** - * 上传资源,用户指定输入流 - * @param user 用户名 - * @param filePath 上传的资源的路径 - * @param inputStream 上传资源的输入流 - * @return 包含resourceId和version - */ - public BmlUploadResponse uploadResource(String user, String filePath, InputStream inputStream); - - /** - * 上传文件,用户指定文件路径,客户端自动获取输入流 - * @param user 用户名 - * @param filePath 文件路径 - * @return 包含resourceId和version - */ - public BmlUploadResponse uploadResource(String user, String filePath); - - - - - - /** - * 获取resource的所有版本 - * @param user 用户名 - * @param resourceId 资源Id - * @return resourceId对应下的所有版本信息 - */ - public BmlResourceVersionsResponse getVersions(String user, String resourceId); - - - /** - * - */ - public BmlDeleteResponse deleteResource(String user, String resourceId, String version); - - public BmlDeleteResponse deleteResource(String user, String resourceId); - -} diff --git a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/client/impl/HttpBmlClient.scala b/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/client/impl/HttpBmlClient.scala deleted file mode 100644 index e7d63672a4..0000000000 --- a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/client/impl/HttpBmlClient.scala +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.client.impl - -import java.io.{File, IOException, InputStream} -import java.util - -import com.webank.wedatasphere.linkis.bml.client.AbstractBmlClient -import com.webank.wedatasphere.linkis.bml.common._ -import com.webank.wedatasphere.linkis.bml.conf.BmlConfiguration -import com.webank.wedatasphere.linkis.bml.http.HttpConf -import com.webank.wedatasphere.linkis.bml.protocol._ -import com.webank.wedatasphere.linkis.bml.request._ -import com.webank.wedatasphere.linkis.bml.response._ -import com.webank.wedatasphere.linkis.common.io.FsPath -import com.webank.wedatasphere.linkis.httpclient.authentication.AuthenticationStrategy -import com.webank.wedatasphere.linkis.httpclient.config.{ClientConfig, ClientConfigBuilder} -import com.webank.wedatasphere.linkis.httpclient.dws.DWSHttpClient -import com.webank.wedatasphere.linkis.httpclient.dws.authentication.{StaticAuthenticationStrategy, TokenAuthenticationStrategy} -import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfig -import com.webank.wedatasphere.linkis.storage.FSFactory -import org.apache.commons.io.IOUtils -import org.apache.commons.lang.StringUtils -import org.slf4j.{Logger, LoggerFactory} - -/** - * created by cooperyang on 2019/5/23 - * Description: - */ -class HttpBmlClient extends AbstractBmlClient{ - - private val logger:Logger = LoggerFactory.getLogger(classOf[HttpBmlClient]) - - val serverUrl:String = HttpConf.gatewayInstance - val maxConnection:Int = 10 - val readTimeout:Int = 10000 - val authenticationStrategy:AuthenticationStrategy = new TokenAuthenticationStrategy() - val clientConfig:ClientConfig = ClientConfigBuilder.newBuilder().addUJESServerUrl(serverUrl) - .connectionTimeout(30000).discoveryEnabled(false) - .loadbalancerEnabled(false).maxConnectionSize(maxConnection) - .retryEnabled(false).readTimeout(readTimeout) - .setAuthenticationStrategy(authenticationStrategy).setAuthTokenKey(BmlConfiguration.AUTH_TOKEN_KEY.getValue) - .setAuthTokenValue(BmlConfiguration.AUTH_TOKEN_VALUE.getValue).build() - val dwsClientConfig:DWSClientConfig = new DWSClientConfig(clientConfig) - dwsClientConfig.setDWSVersion(BmlConfiguration.DWS_VERSION.getValue) - val dwsClientName:String = "BML-Client" - val dwsClient:DWSHttpClient = new DWSHttpClient(dwsClientConfig, dwsClientName) - - val FIRST_VERSION:String = "v000001" - - - - override def downloadResource(user:String, resourceID: String): BmlDownloadResponse = { - downloadResource(user, resourceID, "") - } - - override def downloadResource(user: String, resourceId: String, version: String): BmlDownloadResponse = { - val bmlDownloadAction = BmlDownloadAction() - import scala.collection.JavaConversions._ - bmlDownloadAction.getParameters +="resourceId"->resourceId - // TODO: 不能放非空的参数 - if(version != null)bmlDownloadAction.getParameters +="version"->version - bmlDownloadAction.setUser(user) - val result = dwsClient.execute(bmlDownloadAction) - new BmlDownloadResponse(true,bmlDownloadAction.getInputStream,resourceId,version,null) - /* result match { - case downloadResult:BmlResourceDownloadResult => val isSuccess = if (downloadResult.getStatusCode == 0) true else false - if (isSuccess){ - downloadResult.setInputStream(bmlDownloadAction.getInputStream) - BmlDownloadResponse(isSuccess, downloadResult.inputStream, downloadResult.getResourceId, downloadResult.getVersion, "") - }else{ - logger.error(s"user ${user} download resource $resourceId version $version failed, status code is ${ downloadResult.getStatusCode}") - BmlDownloadResponse(isSuccess, null, null, null, null) - } - case r:BmlResult => logger.error(s"result type ${r.getResultType} not match BmlResourceDownloadResult") - throw POSTResultNotMatchException() - case _ => throw POSTResultNotMatchException() - }*/ - } - - /** - * 下载资源到指定的path中 - * @param user 用户名 - * @param resourceId 资源ID - * @param version 版本信息 - * @param path 指定的目录,前面要加schema share:// local:// 等 - * @param overwrite 是否是追加 - * @return 返回的inputStream已经被全部读完,所以返回一个null,另外的fullFileName是整个文件的名字 - */ - override def downloadResource(user: String, resourceId: String, version: String, path: String, overwrite:Boolean = false): BmlDownloadResponse = { - //1检查目录是否存在,包括path的schema - //2检查文件是否存在,如果文件存在,并且overwrite是false,则报错 - //3获取downloaded_file_name 拼成一个完整的filePath - //4获取inputStream,然后写入到filePath中 - val fsPath = new FsPath(path) - val fileSystem = FSFactory.getFsByProxyUser(fsPath, user) - fileSystem.init(new util.HashMap[String, String]()) -// if (fileSystem.exists(fsPath)){ -// logger.error(s"path $path not exists") -// throw IllegalPathException() -// } -// val getBasicAction = BmlGetBasicAction(resourceId) -// val getBasicResult = dwsClient.execute(getBasicAction) match{ -// case result:BmlGetBasicResult => result -// case _ => throw GetResultNotMatchException() -// } - -// val fileName:StringBuilder = new StringBuilder -// fileName.append(path).append(if (path.endsWith("/")) "" else "/") - -// if (getBasicResult != null && getBasicResult.getStatusCode == 0){ -// val downloadedFileName = getBasicResult.downloadedFileName -// if (StringUtils.isNotEmpty(downloadedFileName)){ -// fileName.append(downloadedFileName) -// }else{ -// throw BmlResponseErrorException("返回的downloadedFileName参数为空") -// } -// }else{ -// logger.error(s"获取 $resourceId 资源失败, BmlServer的返回码是 ${getBasicResult.getStatusCode}") -// throw BmlResponseErrorException("通过http方式获取") -// } - - val fullFileName = path - val downloadAction = BmlDownloadAction() // TODO: 这里暂时还没改 - import scala.collection.JavaConversions._ - downloadAction.getParameters += "resourceId" -> resourceId - // TODO: 不能放非空的参数 - if(version != null) downloadAction.getParameters += "version" -> version - downloadAction.setUser(user) - val downloadResult = dwsClient.execute(downloadAction) - val fullFilePath = new FsPath(fullFileName) - if (downloadResult != null){ - val inputStream = downloadAction.getInputStream - val outputStream = fileSystem.write(fullFilePath, overwrite) - try{ - IOUtils.copy(inputStream, outputStream) - }catch{ - case e:IOException => logger.error("inputStream和outputStream流copy失败", e) - val exception = BmlClientFailException("inputStream和outputStream流copy失败") - exception.initCause(e) - throw e - case t:Throwable => logger.error("流复制失败",t) - throw t - }finally{ - IOUtils.closeQuietly(inputStream) - IOUtils.closeQuietly(outputStream) - } - BmlDownloadResponse(true, null, resourceId, version, fullFileName) - }else{ - BmlDownloadResponse(false, null, null, null, null) - } - } - - /** - * 更新资源信息 - * - * @param resourceID 资源id - * @param filePath 目标文件路径 - * @return resourceId 新的版本信息 - */ - override def updateResource(user:String, resourceID: String, filePath: String): BmlUpdateResponse = { - val inputStream:InputStream = getInputStream(filePath) - updateResource(user, resourceID, filePath, inputStream) - } - - override def updateResource(user:String, resourceID: String, filePath: String, inputStream: InputStream): BmlUpdateResponse = { - val _inputStreams = new util.HashMap[String, InputStream]() - _inputStreams.put("file", inputStream) - val bmlUpdateAction = BmlUpdateAction(null, _inputStreams) - bmlUpdateAction.setUser(user) - bmlUpdateAction.inputStreamNames.put("file", pathToName(filePath)) - bmlUpdateAction.getParameters.put("resourceId",resourceID) - val result = dwsClient.execute(bmlUpdateAction) - result match{ - case updateResult:BmlUpdateResult => val isSuccess= if (updateResult.getStatus == 0) true else false - if (isSuccess){ - val resourceId = updateResult.getResourceId - val version = updateResult.getVersion - BmlUpdateResponse(isSuccess, resourceId, version) - }else{ - logger.error(s"user $user update resource failed, status code is ${updateResult.getStatusCode}") - BmlUpdateResponse(isSuccess, null, null) - } - case r:BmlResult => logger.error(s"result type ${r.getResultType} not match BmlResourceDownloadResult") - throw POSTResultNotMatchException() - case _ => throw POSTResultNotMatchException() - } - } - - /** - * relateResource方法将targetFilePath路径的文件关联到resourceID下面 - * targetFilePath需要包括schema,如果不包含schema,默认是hdfs - * - * @param resourceID resourceID - * @param targetFilePath 指定文件目录 - * @return BmlRelateResult 包含resourceId和新的version - */ - override def relateResource(resourceID: String, targetFilePath: String): BmlRelateResponse = { - null - } - - - - - /** - * 获取resourceid 对应资源的所有版本 - * @param user 用户名 - * @param resourceId 资源Id - * @return resourceId对应下的所有版本信息 - */ - override def getVersions(user: String, resourceId: String): BmlResourceVersionsResponse = { - val getVersionsAction = BmlGetVersionsAction(user, resourceId) - val result = dwsClient.execute(getVersionsAction) - result match{ - case _result:BmlResourceVersionResult => val isSuccess= if (_result.getStatus == 0) true else false - if (isSuccess){ - val resourceId = _result.getResourceId - val resourceVersions = _result.getResourceVersions - BmlResourceVersionsResponse(isSuccess,resourceId, resourceVersions) - }else{ - logger.error(s"user $user get versions failed, status code is ${_result.getStatusCode}") - BmlResourceVersionsResponse(isSuccess, null, null) - } - case r:BmlResult => logger.error(s"result type ${r.getResultType} not match BmlResourceDownloadResult") - throw POSTResultNotMatchException() - case _ => throw POSTResultNotMatchException() - } - } - - - - - /** - * 上传文件,用户指定文件路径,客户端自动获取输入流 - * @param user 用户名 - * @param filePath 文件路径 - * @return 包含resourceId和version - */ - override def uploadResource(user: String, filePath: String): BmlUploadResponse = { - val inputStream:InputStream = getInputStream(filePath) - uploadResource(user, filePath, inputStream) - } - - - private def pathToName(filePath:String):String = new File(filePath).getName - - - /** - * 上传资源 - * - * @param user 用户名 - * @param filePath 上传的资源的路径 - * @param inputStream 上传资源的输入流 - * @return - */ - override def uploadResource(user: String, filePath: String, inputStream: InputStream): BmlUploadResponse = { - val _inputStreams = new util.HashMap[String, InputStream]() - _inputStreams.put("file", inputStream) - val uploadAction = BmlUploadAction(null, _inputStreams) - uploadAction.inputStreamNames.put("file", pathToName(filePath)) - uploadAction.setUser(user) - val result = dwsClient.execute(uploadAction) - result match { - case bmlUploadResult:BmlUploadResult => val isSuccess = if(bmlUploadResult.getStatus == 0) true else false - if (isSuccess){ - val resourceId = bmlUploadResult.getResourceId - val version = bmlUploadResult.getVersion - BmlUploadResponse(isSuccess, resourceId,version) - }else{ - logger.error(s"user $user upload resource failed, status code is ${bmlUploadResult.getStatusCode}") - BmlUploadResponse(isSuccess, null, null) - } - case r:BmlResult => logger.error(s"result type ${r.getResultType} not match BmlResourceDownloadResult") - throw POSTResultNotMatchException() - case _ => throw POSTResultNotMatchException() - } - } - - - /** - * - */ - override def deleteResource(user: String, resourceId: String, version: String): BmlDeleteResponse = { - null - } - - override def deleteResource(user: String, resourceId: String): BmlDeleteResponse = { - val deleteAction = BmlDeleteAction(resourceId) - deleteAction.getParameters.put("resourceId", resourceId) - val result = dwsClient.execute(deleteAction) - result match { - case bmlDeleteResult: BmlDeleteResult => val isSuccess= if (bmlDeleteResult.getStatus == 0) true else false - if (isSuccess){ - BmlDeleteResponse(isSuccess) - }else{ - logger.error(s"user $user update resource failed, status code is ${bmlDeleteResult.getStatusCode}") - BmlDeleteResponse(isSuccess) - } - case r:BmlResult => logger.error(s"result type ${r.getResultType} not match BmlResourceDownloadResult") - throw POSTResultNotMatchException() - case _ => throw POSTResultNotMatchException() - } - } - - //todo 现在是为了通过编译 - private def getInputStream(str: String):InputStream = { - null - } - -} diff --git a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/http/HttpConf.scala b/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/http/HttpConf.scala deleted file mode 100644 index 4d335e3e79..0000000000 --- a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/http/HttpConf.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.http - -import com.webank.wedatasphere.linkis.bml.conf.BmlConfiguration -import com.webank.wedatasphere.linkis.common.conf.Configuration - -/** - * created by cooperyang on 2019/5/15 - * Description: - */ -object HttpConf { - - val gatewayInstance: String = Configuration.getGateWayURL() - val urlPrefix: String = if (BmlConfiguration.URL_PREFIX.getValue.endsWith("/")) { - BmlConfiguration.URL_PREFIX.getValue.substring(0, BmlConfiguration.URL_PREFIX.getValue.length - 1) - } else BmlConfiguration.URL_PREFIX.getValue - - val uploadURL:String = urlPrefix + "/" + BmlConfiguration.UPLOAD_URL.getValue - val downloadURL:String = urlPrefix + "/" + BmlConfiguration.DOWNLOAD_URL.getValue - val deleteURL:String = urlPrefix + "/" + BmlConfiguration.DELETE_URL - val updateVersionURL:String = urlPrefix + "/" + BmlConfiguration.UPDATE_VERSION_URL.getValue - val relateHdfsURL:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.RELATE_HDFS.getValue - val relateStorageURL:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.RELATE_STORAGE.getValue - val getResourcesUrl:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.GET_RESOURCES.getValue - val updateBasicUrl:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.UPDATE_BASIC_URL.getValue - val getVersionsUrl:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.GET_VERSIONS_URL.getValue - val getBasicUrl:String = gatewayInstance + urlPrefix + "/" + BmlConfiguration.GET_BASIC_URL.getValue - def main(args: Array[String]): Unit = { - println(uploadURL) - println(downloadURL) - println(updateVersionURL) - println(relateHdfsURL) - println(relateStorageURL) - println(getResourcesUrl) - println(updateBasicUrl) - } - - -} diff --git a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/request/BmlPOSTAction.scala b/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/request/BmlPOSTAction.scala deleted file mode 100644 index be915bea2c..0000000000 --- a/bml/bmlclient/src/main/scala/com/webank/wedatasphere/linkis/bml/request/BmlPOSTAction.scala +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.request - -import java.io.{File, InputStream} -import java.util - -import com.webank.wedatasphere.linkis.bml.http.HttpConf -import com.webank.wedatasphere.linkis.httpclient.request._ - -/** - * created by cooperyang on 2019/5/23 - * Description: - */ - -abstract class BmlPOSTAction extends POSTAction - -abstract class BmlGETAction extends GetAction - - -/** - * BmlUpload - * @param filePaths - * @param _inputStreams - */ -case class BmlUploadAction(filePaths:Array[String], - _inputStreams:util.Map[String,InputStream]) extends BmlPOSTAction with UploadAction{ - - private val streamNames = new util.HashMap[String,String] - - override val files: util.Map[String, String] = { - if (null == filePaths || filePaths.length == 0) new util.HashMap[String,String]() else{ - val map = new java.util.HashMap[String, String] - filePaths foreach { - filePath => val arr = filePath.split(File.separator) - val fileName = arr(arr.length - 1) - map.put("file", filePath) - } - map - } - } - - override def inputStreams: util.Map[String, InputStream] = _inputStreams - - override def inputStreamNames: util.Map[String, String] = streamNames - - // override def inputStreams: util.Map[String, InputStream] = { - // if (files.size() == 0) new util.HashMap[String, InputStream]() else{ - // val map = new util.HashMap[String, InputStream]() - // files foreach { - // case (fileName, filePath) => val fs = FSFactory.getFs(new FsPath(filePath)) - // fs.init(null) - // val inputStream = fs.read(new FsPath(filePath)) - // - // } - // } - // } - - private var _user:String = _ - - override def setUser(user: String): Unit = this._user = user - - override def getUser: String = this._user - - override def getRequestPayload: String = "" - - override def getURL: String = HttpConf.uploadURL -} - -case class BmlUpdateAction(filePaths:Array[String], - _inputStreams:util.Map[String,InputStream]) extends BmlPOSTAction with UploadAction{ - override def getURL: String = HttpConf.updateVersionURL - - override def getRequestPayload: String = "" - - private var _user:String = _ - - private val streamNames = new util.HashMap[String,String] - - override val files: util.Map[String, String] = { - if (null == filePaths || filePaths.length == 0) new util.HashMap[String,String]() else{ - val map = new java.util.HashMap[String, String] - filePaths foreach { - filePath => val arr = filePath.split(File.separator) - val fileName = arr(arr.length - 1) - map.put("file", filePath) - } - map - } - } - - override def setUser(user: String): Unit = this._user = user - - override def getUser: String = this._user - override def inputStreams: util.Map[String, InputStream] = _inputStreams - - override def inputStreamNames: util.Map[String, String] = streamNames -} - - -case class BmlDownloadAction() extends BmlGETAction with DownloadAction with UserAction{ - - private var inputStream:InputStream = _ - private var user:String = _ - - def getInputStream:InputStream = this.inputStream - - def setInputStream(inputStream: InputStream):Unit = this.inputStream = inputStream - - override def getURL: String = HttpConf.downloadURL - - override def write(inputStream: InputStream): Unit = this.inputStream = inputStream - - override def setUser(user: String): Unit = this.user = user - - override def getUser: String = this.user -} - - - - -case class BmlRelateAction(user:String, - resourceId:String, - inputStream: InputStream) extends BmlPOSTAction{ - override def getRequestPayload: String = "" - - override def getURL: String = HttpConf.updateVersionURL -} - - -case class BmlGetVersionsAction(user:String, - resourceId:String) extends BmlPOSTAction{ - override def getRequestPayload: String = "" - - override def getURL: String = HttpConf.getVersionsUrl -} - - -case class BmlUpdateBasicAction(properties:java.util.Map[String, String]) extends BmlPOSTAction{ - override def getRequestPayload: String = "" - - override def getURL: String = HttpConf.updateBasicUrl -} - - -case class BmlGetBasicAction(resourceId:String) extends BmlGETAction with UserAction { - - private var user:String = _ - - override def getURL: String = HttpConf.getBasicUrl - - override def setUser(user: String): Unit = this.user = user - - override def getUser: String = this.user -} - - - -case class BmlDeleteAction(resourceId:String) extends BmlPOSTAction { - override def getRequestPayload: String = "" - - override def getURL: String = HttpConf.deleteURL -} - - - diff --git a/bml/bmlcommon/pom.xml b/bml/bmlcommon/pom.xml deleted file mode 100644 index 5810ec7199..0000000000 --- a/bml/bmlcommon/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-bmlcommon - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - - - - - - - \ No newline at end of file diff --git a/bml/bmlcommon/src/main/java/com/webank/wedatasphere/linkis/bml/model/AbstractAuditable.java b/bml/bmlcommon/src/main/java/com/webank/wedatasphere/linkis/bml/model/AbstractAuditable.java deleted file mode 100644 index f362ccbc69..0000000000 --- a/bml/bmlcommon/src/main/java/com/webank/wedatasphere/linkis/bml/model/AbstractAuditable.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.model; - -import java.util.Date; - -/** - * created by cooperyang on 2019/5/14 - * Description: - */ -public abstract class AbstractAuditable { - private Date created; - private Date updated; - private String createdBy; - private String updatedBy; - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getUpdated() { - return updated; - } - - public void setUpdated(Date updated) { - this.updated = updated; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public String getUpdatedBy() { - return updatedBy; - } - - public void setUpdatedBy(String updatedBy) { - this.updatedBy = updatedBy; - } - - public void setInfoOnCreate(String user) { - Date current = new Date(); - this.setCreated(current); - this.setUpdated(current); - this.setCreatedBy(user); - this.setUpdatedBy(user); - } - - public void setInfoOnUpdate(String user) { - Date current = new Date(); - this.setUpdated(current); - this.setUpdatedBy(user); - } - -} diff --git a/bml/bmlserver/Dockerfile b/bml/bmlserver/Dockerfile deleted file mode 100644 index 19973e5c15..0000000000 --- a/bml/bmlserver/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-bml.zip /opt/linkis -RUN unzip linkis-bml.zip - -WORKDIR /opt/linkis/linkis-bml/bin -ENTRYPOINT ["/opt/linkis/linkis-bml/bin/startup.sh"] diff --git a/bml/bmlserver/bin/start-bml.sh b/bml/bmlserver/bin/start-bml.sh deleted file mode 100755 index 80cc775a4a..0000000000 --- a/bml/bmlserver/bin/start-bml.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-gc.log" -fi - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -nohup java $SERVER_JAVA_OPTS -cp ../module/lib/*:$HOME/conf:$HOME/lib/* $SERVER_CLASS 2>&1 > $SERVER_LOG_PATH/linkis.out & -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi \ No newline at end of file diff --git a/bml/bmlserver/bin/startup.sh b/bml/bmlserver/bin/startup.sh deleted file mode 100755 index 34b2e0dc1a..0000000000 --- a/bml/bmlserver/bin/startup.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-bml-gc.log" -fi - -if test -z "$START_PORT" -then - export START_PORT=14006 -fi - -export SERVER_PID=$HOME/bin/linkis.pid - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -cp -f /opt/linkis/conf/linkis.properties /opt/linkis/linkis-bml/conf - -nohup java $SERVER_JAVA_OPTS -Deurekaurl=$EUREKA_URL -Duser.timezone=Asia/Shanghai -cp $HOME/conf:$HOME/lib/* $SERVER_CLASS --server.port=$START_PORT 2>&1 > $SERVER_LOG_PATH/linkis-bml.log & - -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi - -tail -f /dev/null diff --git a/bml/bmlserver/bin/stop-bml.sh b/bml/bmlserver/bin/stop-bml.sh deleted file mode 100755 index f032887111..0000000000 --- a/bml/bmlserver/bin/stop-bml.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/bml/bmlserver/conf/application.yml b/bml/bmlserver/conf/application.yml deleted file mode 100644 index a1a3ec8925..0000000000 --- a/bml/bmlserver/conf/application.yml +++ /dev/null @@ -1,36 +0,0 @@ -server: - port: 8056 -spring: - application: - name: bml-server - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: test-user - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - -pagehelper: - helper-dialect: mysql - reasonable: true - support-methods-arguments: true - params: countSql - - -# register-with-eureka: false -# fetch-registry: false diff --git a/bml/bmlserver/conf/linkis.properties b/bml/bmlserver/conf/linkis.properties deleted file mode 100644 index 4135383f09..0000000000 --- a/bml/bmlserver/conf/linkis.properties +++ /dev/null @@ -1,13 +0,0 @@ -wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/bml/dao/impl/*.xml -wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.bml.dao -wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.bml.dao -wds.test.mode=true -wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.bml.restful - -#sit -wds.linkis.server.mybatis.datasource.url= -wds.linkis.server.mybatis.datasource.username= -wds.linkis.server.mybatis.datasource.password= -wds.linkis.server.version=v1 - -#hadoop.config.dir \ No newline at end of file diff --git a/bml/bmlserver/conf/log4j2.xml b/bml/bmlserver/conf/log4j2.xml deleted file mode 100644 index 3da04d9e2f..0000000000 --- a/bml/bmlserver/conf/log4j2.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/bml/bmlserver/pom.xml b/bml/bmlserver/pom.xml deleted file mode 100644 index 3799c53af1..0000000000 --- a/bml/bmlserver/pom.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-bmlserver - - - - com.webank.wedatasphere.linkis - linkis-mybatis - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-bmlcommon - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - ${project.version} - - - asm - org.ow2.asm - - - provided - - - com.webank.wedatasphere.linkis - linkis-storage - ${project.version} - provided - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-bml - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - - \ No newline at end of file diff --git a/bml/bmlserver/pom_k8s.xml b/bml/bmlserver/pom_k8s.xml deleted file mode 100644 index ec9e478559..0000000000 --- a/bml/bmlserver/pom_k8s.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-bmlserver - - - - com.webank.wedatasphere.linkis - linkis-mybatis - - - com.webank.wedatasphere.linkis - linkis-bmlcommon - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - asm - org.ow2.asm - - - tomcat - jasper-compiler - - - tomcat - jasper-runtime - - - - - com.webank.wedatasphere.linkis - linkis-storage - - - org.apache.httpcomponents - httpclient - - - tomcat - jasper-compiler - - - tomcat - jasper-runtime - - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-bml - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - - \ No newline at end of file diff --git a/bml/bmlserver/src/main/assembly/distribution.xml b/bml/bmlserver/src/main/assembly/distribution.xml deleted file mode 100644 index ff80357dc7..0000000000 --- a/bml/bmlserver/src/main/assembly/distribution.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - linkis-bml - - zip - - true - linkis-bml - - - - - - lib - true - true - false - true - true - - - - - - ${basedir}/conf - - * - - 0777 - conf - unix - - - ${basedir}/bin - - * - - 0777 - bin - unix - - - . - - */** - - logs - - - - - diff --git a/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/Entity/Resource.java b/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/Entity/Resource.java deleted file mode 100644 index 709c365dca..0000000000 --- a/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/Entity/Resource.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.Entity; - -import java.util.Date; -import java.util.Map; - -/** - * Created by cooperyang on 2019/5/16. - */ -public class Resource { - - private static final String MAX_VERSION = "maxVersion"; - private static final String IS_PRIVATE = "isPrivate"; - private static final String RESOURCE_HEADER = "resourceHeader"; - private static final String DOWNLOAD_FILE_NAME = "downloadedFileName"; - private static final String SYSTEM = "system"; - private static final String IS_EXPIRE = "isExpire"; - private static final String EXPIRE_TYPE = "expireType"; - private static final String EXPIRE_TIME = "expireTime"; - private static final String UPDATER = "updator"; - - - - - private int id; - - private boolean isPrivate; - - private String resourceHeader; - - private String downloadedFileName; - - private String sys; - - private Date createTime; - - private boolean isExpire; - - private String expireType; - - /** - * expireTime的形式是 yyyy-MM-dd - * 或 yyyy-MM-dd HH:mm:ss - */ - private String expireTime; - - private Date updateTime; - - private String updator; - - private int maxVersion; - - private String resourceId; - - private String user; - - private String system; - - private boolean enableFlag; - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getSystem() { - return system; - } - - public void setSystem(String system) { - this.system = system; - } - - public Resource() { - } - - public Resource(String resourceId, String user, String downloadedFileName){ - this.user = user; - this.resourceId = resourceId; - this.createTime = new Date(System.currentTimeMillis()); - this.setUpdateTime(new Date(System.currentTimeMillis())); - this.enableFlag = true; - this.downloadedFileName = downloadedFileName; - } - - public boolean isEnableFlag() { - return enableFlag; - } - - public void setEnableFlag(boolean enableFlag) { - this.enableFlag = enableFlag; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public boolean isPrivate() { - return isPrivate; - } - - public void setPrivate(boolean aPrivate) { - isPrivate = aPrivate; - } - - public String getResourceHeader() { - return resourceHeader; - } - - public void setResourceHeader(String resourceHeader) { - this.resourceHeader = resourceHeader; - } - - public String getDownloadedFileName() { - return downloadedFileName; - } - - public void setDownloadedFileName(String downloadedFileName) { - this.downloadedFileName = downloadedFileName; - } - - public String getSys() { - return sys; - } - - public void setSys(String sys) { - this.sys = sys; - } - - public Date getCreateTime() { - return createTime; - } - - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } - - public boolean isExpire() { - return isExpire; - } - - public void setExpire(boolean expire) { - isExpire = expire; - } - - public String getExpireType() { - return expireType; - } - - public void setExpireType(String expireType) { - this.expireType = expireType; - } - - public String getExpireTime() { - return expireTime; - } - - public void setExpireTime(String expireTime) { - this.expireTime = expireTime; - } - - public Date getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(Date updateTime) { - this.updateTime = updateTime; - } - - public String getUpdator() { - return updator; - } - - public void setUpdator(String updator) { - this.updator = updator; - } - - public int getMaxVersion() { - return maxVersion; - } - - public void setMaxVersion(int maxVersion) { - this.maxVersion = maxVersion; - } - - public static Resource createNewResource(String resourceId, String user, String downloadedFileName, Map properties){ - Resource resource = new Resource(resourceId, user, downloadedFileName); - if (properties.get(MAX_VERSION) == null){ - resource.setMaxVersion(10); - }else{ - resource.setMaxVersion(Integer.parseInt(properties.get(MAX_VERSION).toString())); - } - if (properties.get(IS_EXPIRE) == null){ - //默认是不过期的 - resource.setExpire(false); - }else{ - resource.setExpire(properties.get(IS_EXPIRE).toString().equalsIgnoreCase("true")); - } - if (properties.get(SYSTEM) == null){ - resource.setSystem("WTSS"); - }else{ - resource.setSystem(properties.get(SYSTEM).toString()); - } - if (properties.get(IS_PRIVATE) == null){ - resource.setPrivate(true); - }else{ - resource.setPrivate(properties.get(IS_PRIVATE).toString().equalsIgnoreCase("true")); - } - if (properties.get(RESOURCE_HEADER) == null){ - resource.setResourceHeader(null); - }else{ - resource.setResourceHeader((String)(properties.get(RESOURCE_HEADER))); - } - //如果资源是过期的,需要设置资源过期的类型和时间 - if (resource.isExpire()){ - if (properties.get(EXPIRE_TYPE) == null){ - resource.setExpireType("time"); - }else{ - resource.setExpireType((String)(properties.get(EXPIRE_TYPE))); - } - if (properties.get(EXPIRE_TIME) == null){ - //默认设置50天过期 - resource.setExpireTime("50d"); - }else{ - resource.setExpireTime((String)(properties.get(EXPIRE_TIME))); - } - } - return resource; - } - - - -} diff --git a/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/service/ResourceService.java b/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/service/ResourceService.java deleted file mode 100644 index bfed9c080d..0000000000 --- a/bml/bmlserver/src/main/java/com/webank/wedatasphere/linkis/bml/service/ResourceService.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.bml.service; - -import com.webank.wedatasphere.linkis.bml.Entity.Resource; -import com.webank.wedatasphere.linkis.bml.service.impl.ResourceServiceImpl; - -import org.glassfish.jersey.media.multipart.FormDataMultiPart; - -import java.util.List; -import java.util.Map; - -/** - * Created by cooperyang on 2019/5/17. - */ -public interface ResourceService { - - List getResources(Map paramMap); - - void deleteResource(String resourceId); - - void batchDeleteResources(List resourceIds); - - /** - * 用于上传文件的函数,上传文件的步骤 - * 1.根据用户名和resourceHeader信息为用户创建一个文件 - * 2.利用storage模块将二进制流存入到物料库 - * 3.二进制流的存储方式有两种,根据资源文件的大小选择合并或者是单独存储 - * 4.生成resourceID - * 4.更新resource 和 resource_version表 - * @param formDataMultiPart notnull - * @param user um_user - * @param properties Map - */ - List upload(FormDataMultiPart formDataMultiPart, String user, Map properties)throws Exception; - - boolean checkResourceId(String resourceId); - - - Resource getResource(String resourceId); - - - boolean checkAuthority(String user, String resourceId); - - boolean checkExpire(String resourceId, String version); - - void cleanExpiredResources(); -} diff --git a/conf/config.sh b/conf/config.sh deleted file mode 100755 index d6f7ad0ed1..0000000000 --- a/conf/config.sh +++ /dev/null @@ -1,135 +0,0 @@ -#!/bin/sh - -shellDir=`dirname $0` -workDir=`cd ${shellDir}/..;pwd` - -### -SSH_PORT=22 - -### deploy user -deployUser=hadoop - - -### The install home path of Linkis -LINKIS_INSTALL_HOME=$workDir #Must provided - - - -### Specifies the user workspace, which is used to store the user's script files and log files. -### Generally local directory -WORKSPACE_USER_ROOT_PATH=file:///tmp/linkis/ ##file:// required -### User's root hdfs path -HDFS_USER_ROOT_PATH=hdfs:///tmp/linkis ##hdfs:// required - -### Path to store job ResultSet:file or hdfs path -RESULT_SET_ROOT_PATH=hdfs:///tmp/linkis - -### Provide the DB information of Hive metadata database. -HIVE_META_URL= -HIVE_META_USER= -HIVE_META_PASSWORD= - -###HADOOP CONF DIR -HADOOP_CONF_DIR=/appcom/config/hadoop-config - -###HIVE CONF DIR -HIVE_CONF_DIR=/appcom/config/hive-config - -###SPARK CONF DIR -SPARK_CONF_DIR=/appcom/config/spark-config - -################### The install Configuration of all Micro-Services ##################### -# -# NOTICE: -# 1. If you just wanna try, the following micro-service configuration can be set without any settings. -# These services will be installed by default on this machine. -# 2. In order to get the most complete enterprise-level features, we strongly recommend that you install -# Linkis in a distributed manner and set the following microservice parameters -# - -### EUREKA install information -### You can access it in your browser at the address below:http://${EUREKA_INSTALL_IP}:${EUREKA_PORT} -#EUREKA_INSTALL_IP=127.0.0.1 # Microservices Service Registration Discovery Center -EUREKA_PORT=20303 - -### Gateway install information -#GATEWAY_INSTALL_IP=127.0.0.1 -GATEWAY_PORT=9001 - -### publicservice -#PUBLICSERVICE_INSTALL_IP=127.0.0.1 -PUBLICSERVICE_PORT=9102 - - -### Hive Metadata Query service, provide the metadata information of Hive databases. -#METADATA_INSTALL_IP=127.0.0.1 -METADATA_PORT=9103 - - -### ResourceManager -#RESOURCEMANAGER_INSTALL_IP=127.0.0.1 -RESOURCEMANAGER_PORT=9104 - - -### Spark -### This service is used to provide spark capability. -#SPARK_INSTALL_IP=127.0.0.1 -SPARK_EM_PORT=9105 -SPARK_ENTRANCE_PORT=9106 - - -### Hive -### This service is used to provide hive capability. -#HIVE_INSTALL_IP=127.0.0.1 -HIVE_EM_PORT=9107 -HIVE_ENTRANCE_PORT=9108 - - -### PYTHON -### This service is used to provide python capability. -#PYTHON_INSTALL_IP=127.0.0.1 -PYTHON_EM_PORT=9109 -PYTHON_ENTRANCE_PORT=9110 - - -### JDBC -### This service is used to provide jdbc capability. -#JDBC_INSTALL_IP=127.0.0.1 -JDBC_ENTRANCE_PORT=9111 - -### SHELL -### This service is used to provide shell capability. -#SHELL_INSTALL_IP=127.0.0.1 -SHELL_EM_PORT=9114 -SHELL_ENTRANCE_PORT=9115 - - - -### BML -### This service is used to provide BML capability. -#BML_INSTALL_IP=127.0.0.1 -BML_PORT=9113 - -### cs -#CS_INSTALL_IP=127.0.0.1 -CS_PORT=9116 - - -### datasource management server -#DSM_INSTALL_IP=127.0.0.1 -DSM_PORT=9117 - -### metadata management server -#MDM_INSTALL_IP=127.0.0.1 -MDM_PORT=9118 - -######################################################################################## - -## LDAP is for enterprise authorization, if you just want to have a try, ignore it. -#LDAP_URL=ldap://localhost:1389/ -#LDAP_BASEDN=dc=webank,dc=com - -## java application default jvm memory -export SERVER_HEAP_SIZE="512M" - -LINKIS_VERSION=0.11.0 diff --git a/conf/linkis-env.sh b/conf/linkis-env.sh new file mode 100644 index 0000000000..59319ac0d0 --- /dev/null +++ b/conf/linkis-env.sh @@ -0,0 +1,135 @@ +#!/bin/bash +# +# description: Starts and stops Server +# +# @name: linkis-demo + +# @created: 01.16.2021 +# +# Modified for Linkis 1.0.0 + +# SSH_PORT=22 + +### deploy user +deployUser=hadoop + +##Linkis_SERVER_VERSION +LINKIS_SERVER_VERSION=v1 + +### Specifies the user workspace, which is used to store the user's script files and log files. +### Generally local directory +WORKSPACE_USER_ROOT_PATH=file:///tmp/linkis/ ##file:// required +### User's root hdfs path +HDFS_USER_ROOT_PATH=hdfs:///tmp/linkis ##hdfs:// required + +### Path to store job ResultSet:file or hdfs path +RESULT_SET_ROOT_PATH=hdfs:///tmp/linkis ##hdfs:// required + +### Path to store started engines and engine logs, must be local +ENGINECONN_ROOT_PATH=/appcom/tmp ## file:// required + +ENTRANCE_CONFIG_LOG_PATH=hdfs:///tmp/linkis/ ##file:// required + +### Provide the DB information of Hive metadata database. +HIVE_META_URL= +HIVE_META_USER= +HIVE_META_PASSWORD= + +##YARN REST URL spark engine required +YARN_RESTFUL_URL=http://127.0.0.1:8088 + +###HADOOP CONF DIR +HADOOP_CONF_DIR=/appcom/config/hadoop-config + +###HIVE CONF DIR +HIVE_CONF_DIR=/appcom/config/hive-config + +###SPARK CONF DIR +SPARK_CONF_DIR=/appcom/config/spark-config + +## Engine version conf +#SPARK_VERSION +#SPARK_VERSION=2.4.3 +##HIVE_VERSION +#HIVE_VERSION=1.2.1 +#PYTHON_VERSION=python2 + +################### The install Configuration of all Micro-Services ##################### +# +# NOTICE: +# 1. If you just wanna try, the following micro-service configuration can be set without any settings. +# These services will be installed by default on this machine. +# 2. In order to get the most complete enterprise-level features, we strongly recommend that you install +# Linkis in a distributed manner and set the following microservice parameters +# + +### EUREKA install information +### You can access it in your browser at the address below:http://${EUREKA_INSTALL_IP}:${EUREKA_PORT} +#EUREKA_INSTALL_IP=127.0.0.1 # Microservices Service Registration Discovery Center +EUREKA_PORT=20303 +EUREKA_PREFER_IP=false + +### Gateway install information +#GATEWAY_INSTALL_IP=127.0.0.1 +GATEWAY_PORT=9001 + +### ApplicationManager +#MANAGER_INSTALL_IP=127.0.0.1 +MANAGER_PORT=9101 + +### EngineManager +#ENGINECONNMANAGER_INSTALL_IP=127.0.0.1 +ENGINECONNMANAGER_PORT=9102 + + + +### EnginePluginServer +#ENGINECONN_PLUGIN_SERVER_INSTALL_IP=127.0.0.1 +ENGINECONN_PLUGIN_SERVER_PORT=9103 + +### LinkisEntrance +#ENTRANCE_INSTALL_IP=127.0.0.1 +ENTRANCE_PORT=9104 + +### publicservice +#PUBLICSERVICE_INSTALL_IP=127.0.0.1 +PUBLICSERVICE_PORT=9105 + + +### Hive Metadata Query service, provide the metadata information of Hive databases. +#DATASOURCE_INSTALL_IP=127.0.0.1 +DATASOURCE_PORT=9106 + +### BML +### This service is used to provide BML capability. +#BML_INSTALL_IP=127.0.0.1 +BML_PORT=9107 + +### cs +#CS_INSTALL_IP=127.0.0.1 +CS_PORT=9108 + +######################################################################################## + +## LDAP is for enterprise authorization, if you just want to have a try, ignore it. +#LDAP_URL=ldap://localhost:1389/ +#LDAP_BASEDN=dc=webank,dc=com +#LDAP_USER_NAME_FORMAT=cn=%s@xxx.com,OU=xxx,DC=xxx,DC=com + +## java application default jvm memory +export SERVER_HEAP_SIZE="512M" + +if test -z "$EUREKA_INSTALL_IP" +then + export EUREKA_INSTALL_IP="`hostname --fqdn`" +fi +if [ "true" != "$EUREKA_PREFER_IP" ] +then + export EUREKA_HOSTNAME=$EUREKA_INSTALL_IP +fi +export EUREKA_URL=http://$EUREKA_INSTALL_IP:$EUREKA_PORT/eureka/ + +LINKIS_VERSION=1.0.0 + +# for install +LINKIS_PUBLIC_MODULE=lib/linkis-commons/public-module \ No newline at end of file diff --git a/conf/linkis.properties b/conf/linkis.properties new file mode 100644 index 0000000000..5654bafb0a --- /dev/null +++ b/conf/linkis.properties @@ -0,0 +1,51 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +## +#wds.linkis.test.mode=true +wds.linkis.server.version=v1 +##spring conf +wds.linkis.gateway.url=http://127.0.0.1:9001 +wds.linkis.eureka.defaultZone=http://127.0.0.1:20303/eureka/ +##mybatis +wds.linkis.server.mybatis.datasource.url= +wds.linkis.server.mybatis.datasource.username= +wds.linkis.server.mybatis.datasource.password= +##hive meta +hive.meta.url= +hive.meta.user= +hive.meta.password= +##LDAP +wds.linkis.ldap.proxy.url= +wds.linkis.ldap.proxy.baseDN= +wds.linkis.ldap.proxy.userNameFormat= + +wds.linkis.admin.user=hadoop +#hadoopconfig +#hadoop.config.dir=/appcom/config/hadoop-config +#hive.config.dir= +#spark.config.dir +##fileSystem +wds.linkis.filesystem.root.path=file:///tmp/linkis/ +wds.linkis.filesystem.hdfs.root.path=hdfs:///tmp/linkis/ +#engine plugin +wds.linkis.engineconn.root.dir=/appcom/tmp +wds.linkis.engineconn.home=/appcom/Install/LinkisInstall/lib/linkis-engineconn-plugins +wds.linkis.engineconn.plugin.loader.store.path=/appcom/Install/LinkisInstall/lib/linkis-engineconn-plugins +wds.linkis.public_module.path=/appcom/Install/LinkisInstall/lib/linkis-commons/public-module +##engine Version +#wds.linkis.spark.engine.version= +#wds.linkis.hive.engine.version= +#wds.linkis.python.engine.version= \ No newline at end of file diff --git a/contextservice/cs-cache/pom.xml b/contextservice/cs-cache/pom.xml deleted file mode 100644 index 1969444d9c..0000000000 --- a/contextservice/cs-cache/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-cache - - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - com.webank.wedatasphere.linkis - linkis-cs-persistence - - - - org.reflections - reflections - 0.9.10 - - - - com.webank.wedatasphere.linkis - linkis-module - provided - - - - junit - junit - RELEASE - test - - - com.webank.wedatasphere.linkis - linkis-cs-listener - compile - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-cache/src/main/java/com/webank/wedatasphere/linkis/cs/contextcache/cache/guava/ContextIDCacheLoader.java b/contextservice/cs-cache/src/main/java/com/webank/wedatasphere/linkis/cs/contextcache/cache/guava/ContextIDCacheLoader.java deleted file mode 100644 index d081e577f6..0000000000 --- a/contextservice/cs-cache/src/main/java/com/webank/wedatasphere/linkis/cs/contextcache/cache/guava/ContextIDCacheLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* -package com.webank.wedatasphere.linkis.cs.contextcache.cache.guava; - -import com.google.common.cache.CacheLoader; -import com.webank.wedatasphere.linkis.cs.contextcache.cache.csid.ContextIDValue; -import com.webank.wedatasphere.linkis.cs.contextcache.cache.csid.ContextIDValueGenerator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ContextIDCacheLoader extends CacheLoader { - - private static final Logger logger = LoggerFactory.getLogger(ContextIDCacheLoader.class); - - @Autowired - private ContextIDValueGenerator contextIDValueGenerator; - - @Override - public ContextIDValue load(String contextID) throws Exception { - logger.info("Start to load contextID:{}", contextID); - ContextIDValue contextIDValue = contextIDValueGenerator.createContextIDValue(contextID); - - logger.info("Finished to load contextID:{}", contextID); - return contextIDValue; - } -} -*/ diff --git a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/csid/TestContextID.java b/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/csid/TestContextID.java deleted file mode 100644 index a2344cd2b2..0000000000 --- a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/csid/TestContextID.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.contextcache.test.csid; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; - -/** - * @author peacewong - * @date 2020/2/13 20:41 - */ -public class TestContextID implements ContextID { - - String contextID; - - @Override - public String getContextId() { - return contextID; - } - - @Override - public void setContextId(String contextId) { - this.contextID = contextId; - } -} diff --git a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKey.java b/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKey.java deleted file mode 100644 index a52adcae00..0000000000 --- a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKey.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.contextcache.test.keyword; - -import com.webank.wedatasphere.linkis.cs.common.annotation.KeywordMethod; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextScope; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextType; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; - -/** - * @author peacewong - * @date 2020/2/13 16:32 - */ -public class TestContextKey implements ContextKey { - - private String key; - - private String keywords; - - @KeywordMethod - @Override - public String getKey() { - return this.key; - } - - @Override - public void setKey(String key) { - this.key = key; - } - - @Override - public ContextType getContextType() { - return ContextType.METADATA; - } - - @Override - public void setContextType(ContextType contextType) { - - } - - @Override - public ContextScope getContextScope() { - return ContextScope.PUBLIC; - } - - @Override - public void setContextScope(ContextScope contextScope) { - - } - - @KeywordMethod(splitter = ",") - @Override - public String getKeywords() { - return this.keywords; - } - - @Override - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - @Override - public int getType() { - return 0; - } - - @Override - public void setType(int type) { - - } -} diff --git a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKeyValue.java b/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKeyValue.java deleted file mode 100644 index f279ca74db..0000000000 --- a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextKeyValue.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.contextcache.test.keyword; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; - -/** - * @author peacewong - * @date 2020/2/13 16:46 - */ -public class TestContextKeyValue implements ContextKeyValue { - - private ContextKey contextKey; - - private ContextValue contextValue; - - @Override - public ContextKey getContextKey() { - return this.contextKey; - } - - @Override - public void setContextKey(ContextKey contextKey) { - this.contextKey = contextKey; - } - - @Override - public ContextValue getContextValue() { - return this.contextValue; - } - - @Override - public void setContextValue(ContextValue contextValue) { - this.contextValue = contextValue; - } -} diff --git a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextValue.java b/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextValue.java deleted file mode 100644 index 65e53dfefd..0000000000 --- a/contextservice/cs-cache/src/test/java/com/webank/wedatasphere/linkis/cs/contextcache/test/keyword/TestContextValue.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.contextcache.test.keyword; - -import com.webank.wedatasphere.linkis.cs.common.annotation.KeywordMethod; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ValueBean; - -/** - * @author peacewong - * @date 2020/2/13 16:44 - */ -public class TestContextValue implements ContextValue { - - private Object value; - - private String keywords; - - @KeywordMethod(splitter = "-") - @Override - public String getKeywords() { - return this.keywords; - } - - @Override - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - @KeywordMethod(regex = "hello") - @Override - public Object getValue() { - return this.value; - } - - @Override - public void setValue(Object value) { - this.value = value; - } -} diff --git a/contextservice/cs-cache/src/test/resources/linkis.properties b/contextservice/cs-cache/src/test/resources/linkis.properties deleted file mode 100644 index ce3f1ee22a..0000000000 --- a/contextservice/cs-cache/src/test/resources/linkis.properties +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -wds.linkis.test.mode=true - -wds.linkis.server.mybatis.datasource.url=jdbc:mysql://127.0.0.1:3306/ide_gz_bdap_sit_01?characterEncoding=UTF-8 -wds.linkis.server.mybatis.datasource.username= -wds.linkis.server.mybatis.datasource.password= - - -wds.linkis.log.clear=true -wds.linkis.server.version=v1 - -##restful -wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.cs.server.restful - -##mybatis -wds.linkis.server.mybatis.mapperLocations=classpath*:com\\webank\\wedatasphere\\linkis\\cs\\persistence\\dao\\impl\\*.xml - -wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.cs.persistence.entity - -wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.cs.persistence.dao diff --git a/contextservice/cs-cache/src/test/resources/log4j2.xml b/contextservice/cs-cache/src/test/resources/log4j2.xml deleted file mode 100644 index 2a9e19f810..0000000000 --- a/contextservice/cs-cache/src/test/resources/log4j2.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/contextservice/cs-client/pom.xml b/contextservice/cs-client/pom.xml deleted file mode 100644 index 820c8df603..0000000000 --- a/contextservice/cs-client/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-client - - - - com.webank.wedatasphere.linkis - linkis-common - - - - com.webank.wedatasphere.linkis - linkis-gateway-httpclient-support - - - com.webank.wedatasphere.linkis - linkis-storage - - - - - - com.webank.wedatasphere.linkis - linkis-httpclient - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - - - - - - com.webank.wedatasphere.linkis - linkis-cs-listener - - - - junit - junit - 4.12 - test - - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - - - \ No newline at end of file diff --git a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextIDListener.java b/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextIDListener.java deleted file mode 100644 index 84b99243fc..0000000000 --- a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextIDListener.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.listener; - -import com.webank.wedatasphere.linkis.common.listener.Event; -import com.webank.wedatasphere.linkis.cs.client.Context; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.listener.event.enumeration.OperateType; -import com.webank.wedatasphere.linkis.cs.listener.event.impl.DefaultContextIDEvent; - - -/** - * created by cooperyang on 2020/2/17 - * Description: 这个listener是用来监听contextID的,用户可以进行实现 - */ -public abstract class ContextIDListener implements ContextClientListener{ - - - private ContextID contextID; - - private Context context; - - - public ContextIDListener(){ - - } - - public ContextIDListener(ContextID contextID){ - this.contextID = contextID; - } - - public ContextID getContextID() { - return contextID; - } - - public void setContextID(ContextID contextID) { - this.contextID = contextID; - } - - - public Context getContext() { - return context; - } - - public void setContext(Context context) { - this.context = context; - } - - @Override - public void onContextCreated(Event event) { - - } - - @Override - public void onContextUpdated(Event event) { - - } - - public abstract void onContextRemoved(Event event); - - - @Override - public void onEvent(Event event) { - if (event instanceof DefaultContextIDEvent){ - DefaultContextIDEvent defaultContextKeyEvent = (DefaultContextIDEvent)event; - if (defaultContextKeyEvent.getContextID().equals(contextID)){ - switch(defaultContextKeyEvent.getOperateType()){ - case UPDATE : onContextUpdated(defaultContextKeyEvent); - break; - case CREATE: onContextCreated(defaultContextKeyEvent);break; - case REMOVE: onContextRemoved(defaultContextKeyEvent);break; - default: break; - } - } - } - } -} diff --git a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextKeyListener.java b/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextKeyListener.java deleted file mode 100644 index d6e57d9784..0000000000 --- a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/listener/ContextKeyListener.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.listener; - -import com.webank.wedatasphere.linkis.common.exception.ErrorException; -import com.webank.wedatasphere.linkis.common.listener.Event; -import com.webank.wedatasphere.linkis.cs.client.Context; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.listener.event.impl.DefaultContextKeyEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * created by cooperyang on 2020/2/18 - * Description:一个微服务对contextKey的监听器 - */ -public abstract class ContextKeyListener implements ContextClientListener{ - - private static final Logger LOGGER = LoggerFactory.getLogger(ContextKeyListener.class); - - private ContextKey contextKey; - - private Context context; - - public ContextKeyListener(){ - - } - - public ContextKeyListener(ContextKey contextKey){ - this.contextKey = contextKey; - } - - public ContextKey getContextKey() { - return contextKey; - } - - public void setContextKey(ContextKey contextKey) { - this.contextKey = contextKey; - } - - public Context getContext() { - return context; - } - - public void setContext(Context context) { - this.context = context; - } - - @Override - public void onContextUpdated(Event event) { - if (event instanceof DefaultContextKeyEvent){ - context.setLocal(((DefaultContextKeyEvent) event).getContextKeyValue()); - } - } - - @Override - public void onEvent(Event event) { - if (event instanceof DefaultContextKeyEvent){ - DefaultContextKeyEvent defaultContextKeyEvent = (DefaultContextKeyEvent)event; - if (defaultContextKeyEvent.getContextKeyValue().getContextKey().equals(contextKey)){ - switch(defaultContextKeyEvent.getOperateType()){ - case UPDATE:onContextUpdated(defaultContextKeyEvent);break; - case CREATE:onContextCreated(defaultContextKeyEvent);break; - default:break; - } - } - } - } -} diff --git a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/ResourceService.java b/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/ResourceService.java deleted file mode 100644 index 01b4c98288..0000000000 --- a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/ResourceService.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.service; - -import com.webank.wedatasphere.linkis.cs.common.entity.resource.BMLResource; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; - -import java.util.List; -import java.util.Map; - -/** - * @Author alexyang - * @Date 2020/3/9 - */ -public interface ResourceService { - - /** - * 通过ContextID和NodeName,获取上游的所有Resource数据 - * @param contextIDStr - * @param nodeName - * @return - */ - Map getAllUpstreamBMLResource(String contextIDStr, String nodeName) throws CSErrorException; - - List getUpstreamBMLResource(String contextIDStr, String nodeName) throws CSErrorException; -} diff --git a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/VariableService.java b/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/VariableService.java deleted file mode 100644 index 168b4f3377..0000000000 --- a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/service/VariableService.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.service; - -import com.webank.wedatasphere.linkis.cs.common.entity.object.LinkisVariable; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; - -import java.util.List; - -/** - * @author peacewong - * @date 2020/3/12 20:28 - */ -public interface VariableService { - - List getUpstreamVariables(String contextIDStr, String nodeName) throws CSErrorException; - - void putVariable(String contextIDStr, String contextKey, LinkisVariable linkisVariable) throws CSErrorException; -} diff --git a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/utils/ExceptionHelper.java b/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/utils/ExceptionHelper.java deleted file mode 100644 index 211469f8bb..0000000000 --- a/contextservice/cs-client/src/main/java/com/webank/wedatasphere/linkis/cs/client/utils/ExceptionHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.utils; - -import com.webank.wedatasphere.linkis.common.exception.ErrorException; - -/** - * created by cooperyang on 2020/2/19 - * Description: - */ -public class ExceptionHelper { - public static void throwErrorException(int errCode, String errMsg, Throwable t)throws ErrorException { - ErrorException errorException = new ErrorException(errCode, errMsg); - errorException.initCause(t); - throw errorException; - } -} diff --git a/contextservice/cs-client/src/main/scala/com/webank/wedatasphere/linkis/cs/client/utils/ContextClientUtils.scala b/contextservice/cs-client/src/main/scala/com/webank/wedatasphere/linkis/cs/client/utils/ContextClientUtils.scala deleted file mode 100644 index f0b895325d..0000000000 --- a/contextservice/cs-client/src/main/scala/com/webank/wedatasphere/linkis/cs/client/utils/ContextClientUtils.scala +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.client.utils - -import java.lang -import java.lang.reflect.Type - -import com.google.gson.{GsonBuilder, JsonElement, JsonPrimitive, JsonSerializationContext, JsonSerializer} - -/** - * created by cooperyang on 2020/2/23 - * Description: - */ -object ContextClientUtils { - implicit val gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls - .registerTypeAdapter(classOf[java.lang.Double], new JsonSerializer[java.lang.Double] { - override def serialize(t: lang.Double, `type`: Type, jsonSerializationContext: JsonSerializationContext): JsonElement = - if(t == t.longValue()) new JsonPrimitive(t.longValue()) else new JsonPrimitive(t) - }).create -} diff --git a/contextservice/cs-common/pom.xml b/contextservice/cs-common/pom.xml deleted file mode 100644 index ea1ff39312..0000000000 --- a/contextservice/cs-common/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-common - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - org.apache.commons - commons-text - 1.6 - - - org.reflections - reflections - 0.9.10 - - - - com.google.code.gson - gson - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Column.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Column.java deleted file mode 100644 index 902ef0c219..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Column.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.entity.metadata; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface Column { - - Integer getLength(); - - void setLength(Integer length); - - String getName(); - - void setName(String name); - - String getAlias(); - - void setAlias(String alias); - - String getType(); - - void setType(String type); - - String getComment(); - - void setComment(String comment); - - String getExpress(); - - void setExpress(String express); - - String getRule(); - - void setRule(String rule); - - Boolean getPrimary(); - - void setPrimary(Boolean primary); -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/DB.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/DB.java deleted file mode 100644 index 3e468f2147..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/DB.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.entity.metadata; - -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.DBType; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface DB { - - String getName(); - - void setName(String name); - - DBType getDbType(); - - void setDbType(DBType dbType); - - String getOwners(); - - void setOwners(String owners); - - String getComment(); - - void setComment(String comment); - - String[] getLables(); - - void setLables(String[] lables); - -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Partition.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Partition.java deleted file mode 100644 index 4790595f30..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/metadata/Partition.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.entity.metadata; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface Partition { - - Integer getLength(); - - void setLength(Integer length); - - String getName(); - - void setName(String name); - - String getAlias(); - - void setAlias(String alias); - - String getType(); - - void setType(String type); - - String getComment(); - - void setComment(String comment); - - String getExpress(); - - void setExpress(String express); - - String getRule(); - - void setRule(String rule); - - Boolean getPrimary(); - - void setPrimary(Boolean primary); -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/resource/Resource.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/resource/Resource.java deleted file mode 100644 index 4259d623a2..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/entity/resource/Resource.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.entity.resource; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ValueBean; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface Resource { -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/exception/ErrorCode.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/exception/ErrorCode.java deleted file mode 100644 index 3bd8513be1..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/exception/ErrorCode.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.exception; - -/** - * @Author alexyang - * @Date 2020/2/21 - */ -public class ErrorCode { - - public static final int INVALID_NULL_OBJECT = 70100; - - public static final int SERIALIZER_TO_JSON_ERROR = 70101; - - public static final int INVALID_NULL_STRING = 70102; - - public static final int INVALID_DESERIALIZE_STRING = 70103; - - public static final int INVALID_DESERIALIZE_OBJECT = 70104; - - public static final int DESERIALIZER_FROM_JSON_ERROR = 70105; - - public static final int METHOD_NOT_OVERRIDE = 70106; - - public static final int INVALID_HAID_ENCODE_PARAMS = 70107; - - public static final int INVALID_HAID_STRING = 70108; - - public static final int INVALID_CONTEXT_TYPE = 70109; - - public static final int GET_CONTEXT_VALUE_ERROR = 70110; - - public static final int SEARCH_CONTEXT_VALUE_ERROR = 70111; - - public static final int INVALID_CONTEXT_VALUE_TYPE = 70109; - - - public static final int DESERIALIZE_ERROR = 70112; - -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextIDListener.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextIDListener.java deleted file mode 100644 index 045ee18920..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextIDListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.listener; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface ContextIDListener { - - void onRemoved(ContextID contextID); - - void onReset(ContextID contextID); - - void onUPdated(ContextID contextID); -} diff --git a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextKeyListener.java b/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextKeyListener.java deleted file mode 100644 index c553cc8422..0000000000 --- a/contextservice/cs-common/src/main/java/com/webank/wedatasphere/linkis/cs/common/listener/ContextKeyListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.common.listener; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface ContextKeyListener { - - void onUpdated(ContextID contextID, ContextKeyValue contextKeyValue); - - void onRemoved(ContextID contextID, ContextKeyValue contextKeyValue); - - void onReset(ContextID contextID, ContextKeyValue contextKeyValue); - -} diff --git a/contextservice/cs-highavailable/pom.xml b/contextservice/cs-highavailable/pom.xml deleted file mode 100644 index de17876274..0000000000 --- a/contextservice/cs-highavailable/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-highavailable - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - provided - - - com.webank.wedatasphere.linkis - linkis-cs-persistence - provided - - - org.apache.commons - commons-math3 - 3.1.1 - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/conf/ContextHighAvailableConf.java b/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/conf/ContextHighAvailableConf.java deleted file mode 100644 index a56e62bf39..0000000000 --- a/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/conf/ContextHighAvailableConf.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.highavailable.conf; - -public class ContextHighAvailableConf { - - -} diff --git a/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/exception/ErrorCode.java b/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/exception/ErrorCode.java deleted file mode 100644 index 53d43bf3bb..0000000000 --- a/contextservice/cs-highavailable/src/main/java/com/webank/wedatasphere/linkis/cs/highavailable/exception/ErrorCode.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.highavailable.exception; - -/** - * @Author alexyang - * @Date 2020/2/18 - */ -public class ErrorCode { - - public static int INVALID_INSTANCE_ALIAS = 70010; - - public static int INVALID_HAID = 70011; - - public static int GENERATE_HAID_ERROR = 70012; - - public static int INVALID_CONTEXTID = 70013; - - public static int GENERATE_BACKUP_INSTANCE_ERROR = 70014; - - public static int INVALID_INSTANCE = 70015; - - public static int INVAID_HA_CONTEXTID = 70016; -} diff --git a/contextservice/cs-highavailable/src/test/resources/application.yml b/contextservice/cs-highavailable/src/test/resources/application.yml deleted file mode 100644 index d6b3e8fb9d..0000000000 --- a/contextservice/cs-highavailable/src/test/resources/application.yml +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -server: - port: 9010 -spring: - application: - name: CLOUD-CONTEXTSERVICE - -eureka: - client: - serviceUrl: - defaultZone: http://127.0.0.1:20303/eureka/ - registry-fetch-interval-seconds: 5 - instance: - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info diff --git a/contextservice/cs-highavailable/src/test/resources/log4j.properties b/contextservice/cs-highavailable/src/test/resources/log4j.properties deleted file mode 100644 index a7e6854c4d..0000000000 --- a/contextservice/cs-highavailable/src/test/resources/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -### set log levels ### - -log4j.rootCategory=INFO,console - -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=INFO -log4j.appender.console.layout=org.apache.log4j.PatternLayout -#log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n -log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) %p %c{1} - %m%n - - -log4j.appender.com.webank.bdp.ide.core=org.apache.log4j.DailyRollingFileAppender -log4j.appender.com.webank.bdp.ide.core.Threshold=INFO -log4j.additivity.com.webank.bdp.ide.core=false -log4j.appender.com.webank.bdp.ide.core.layout=org.apache.log4j.PatternLayout -log4j.appender.com.webank.bdp.ide.core.Append=true -log4j.appender.com.webank.bdp.ide.core.File=logs/linkis.log -log4j.appender.com.webank.bdp.ide.core.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n - -log4j.logger.org.springframework=INFO diff --git a/contextservice/cs-listener/pom.xml b/contextservice/cs-listener/pom.xml deleted file mode 100644 index 1c5413d008..0000000000 --- a/contextservice/cs-listener/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-listener - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - junit - junit - 4.12 - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-listener/src/main/java/com/webank/wedatasphere/linkis/cs/listener/callback/CallbackEngine.java b/contextservice/cs-listener/src/main/java/com/webank/wedatasphere/linkis/cs/listener/callback/CallbackEngine.java deleted file mode 100644 index 6bbaff3b9e..0000000000 --- a/contextservice/cs-listener/src/main/java/com/webank/wedatasphere/linkis/cs/listener/callback/CallbackEngine.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.callback; - -import com.webank.wedatasphere.linkis.cs.listener.callback.imp.ContextKeyValueBean; - -import java.util.ArrayList; -import java.util.Set; - -/** - * @Author: chaogefeng - * @Date: 2020/2/20 - */ -public interface CallbackEngine { - - ArrayList getListenerCallback(String source); - -} diff --git a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextID.java b/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextID.java deleted file mode 100644 index 3d81b457f3..0000000000 --- a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextID.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.test; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; - -/** - * @author peacewong - * @date 2020/2/13 20:41 - */ -public class TestContextID implements ContextID { - - String contextID; - - @Override - public String getContextId() { - return contextID; - } - - @Override - public void setContextId(String contextId) { - this.contextID = contextId; - } -} diff --git a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKey.java b/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKey.java deleted file mode 100644 index 6bd442ee6a..0000000000 --- a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKey.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.test; - -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextScope; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextType; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; - -/** - * @Author: chaogefeng - * @Date: 2020/2/22 - */ -public class TestContextKey implements ContextKey { - private String key; - private ContextType contextType; - @Override - public String getKey() { - return this.key; - } - - @Override - public void setKey(String key) { - this.key=key; - } - - @Override - public ContextType getContextType() { - return this.contextType; - } - - @Override - public void setContextType(ContextType contextType) { - this.contextType=contextType; - } - - @Override - public ContextScope getContextScope() { - return null; - } - - @Override - public void setContextScope(ContextScope contextScope) { - - } - - @Override - public String getKeywords() { - return null; - } - - @Override - public void setKeywords(String keywords) { - - } - - @Override - public int getType() { - return 0; - } - - @Override - public void setType(int type) { - - } -} diff --git a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKeyValue.java b/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKeyValue.java deleted file mode 100644 index df44a38e35..0000000000 --- a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextKeyValue.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.test; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; - -/** - * @author chaogefeng - * @date 2020/2/22 16:46 - */ -public class TestContextKeyValue implements ContextKeyValue { - - private ContextKey contextKey; - - private ContextValue contextValue; - - @Override - public ContextKey getContextKey() { - return this.contextKey; - } - - @Override - public void setContextKey(ContextKey contextKey) { - this.contextKey = contextKey; - } - - @Override - public ContextValue getContextValue() { - return this.contextValue; - } - - @Override - public void setContextValue(ContextValue contextValue) { - this.contextValue = contextValue; - } -} diff --git a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextValue.java b/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextValue.java deleted file mode 100644 index db01d5009f..0000000000 --- a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestContextValue.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.test; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ValueBean; - -/** - * @Author: chaogefeng - * @Date: 2020/2/22 - */ -public class TestContextValue implements ContextValue { - private Object value; - - private String keywords; - - - @Override - public String getKeywords() { - return null; - } - - @Override - public void setKeywords(String keywords) { - - } - - @Override - public Object getValue() { - return this.value; - } - - @Override - public void setValue(Object value) { - this.value=value; - } - - -} diff --git a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestListenerManager.java b/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestListenerManager.java deleted file mode 100644 index 37c174064d..0000000000 --- a/contextservice/cs-listener/src/test/java/com/webank/wedatasphere/linkis/cs/listener/test/TestListenerManager.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.listener.test; - -import com.webank.wedatasphere.linkis.common.listener.Event; -import com.webank.wedatasphere.linkis.cs.common.entity.listener.ListenerDomain; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.listener.ListenerBus.ContextAsyncListenerBus; -import com.webank.wedatasphere.linkis.cs.listener.callback.imp.ContextKeyValueBean; -import com.webank.wedatasphere.linkis.cs.listener.callback.imp.DefaultContextIDCallbackEngine; -import com.webank.wedatasphere.linkis.cs.listener.callback.imp.DefaultContextKeyCallbackEngine; -import com.webank.wedatasphere.linkis.cs.listener.event.enumeration.OperateType; -import com.webank.wedatasphere.linkis.cs.listener.event.impl.DefaultContextIDEvent; -import com.webank.wedatasphere.linkis.cs.listener.event.impl.DefaultContextKeyEvent; -import com.webank.wedatasphere.linkis.cs.listener.manager.ListenerManager; -import com.webank.wedatasphere.linkis.cs.listener.manager.imp.DefaultContextListenerManager; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** - * @Author: chaogefeng - * @Date: 2020/2/22 - */ -public class TestListenerManager { - @Test - public void testGetContextAsyncListenerBus() { - DefaultContextListenerManager defaultContextListenerManager = DefaultContextListenerManager.getInstance(); - - ContextAsyncListenerBus contextAsyncListenerBus = defaultContextListenerManager.getContextAsyncListenerBus(); - - DefaultContextIDCallbackEngine contextIDCallbackEngine = defaultContextListenerManager.getContextIDCallbackEngine(); - - DefaultContextKeyCallbackEngine contextKeyCallbackEngine = defaultContextListenerManager.getContextKeyCallbackEngine(); - //client1的contextID - TestContextID testContextID1 = new TestContextID(); - testContextID1.setContextId("18392881376"); - - //client2的contextID - TestContextID testContextID2 = new TestContextID(); - testContextID2.setContextId("13431335441"); - - List csKeys1 = new ArrayList<>(); - TestContextKey testContextKey1 = new TestContextKey(); - testContextKey1.setKey("key1"); - TestContextKey testContextKey2 = new TestContextKey(); - testContextKey2.setKey("key2"); - csKeys1.add(testContextKey1); - csKeys1.add(testContextKey2); - - List csKeys2 = new ArrayList<>(); - TestContextKey testContextKey3 = new TestContextKey(); - testContextKey3.setKey("key3"); - TestContextKey testContextKey4 = new TestContextKey(); - testContextKey4.setKey("key4"); - csKeys2.add(testContextKey3); - csKeys2.add(testContextKey4); - - - ListenerDomain ListenerDomain1; - - ListenerDomain ListenerDomain2; - - ListenerDomain ListenerDomain3; - - - - - DefaultContextKeyEvent defaultContextKeyEvent = new DefaultContextKeyEvent(); - defaultContextKeyEvent.setContextID(testContextID1); - defaultContextKeyEvent.setOperateType(OperateType.UPDATE); - TestContextKeyValue testContextKeyValue = new TestContextKeyValue(); - testContextKeyValue.setContextKey(testContextKey1); - TestContextValue testContextValue = new TestContextValue(); - testContextValue.setValue("chaogefeng"); - testContextKeyValue.setContextValue(testContextValue); - defaultContextKeyEvent.setContextKeyValue(testContextKeyValue); - contextAsyncListenerBus.doPostEvent(contextKeyCallbackEngine, defaultContextKeyEvent); - ArrayList clientSource2ListenerCallback = contextKeyCallbackEngine.getListenerCallback("127.0.0.1:8888"); - System.out.println("----------------------------------------------------------------------"); - for (ContextKeyValueBean contextKeyValueBean : clientSource2ListenerCallback) { - System.out.println("返回的bean里面对应的contexID: " + contextKeyValueBean.getCsID().getContextId()); - System.out.println("返回的bean里面对应的cskeys: " + contextKeyValueBean.getCsKey().getKey()); - if (contextKeyValueBean.getCsValue() != null) { - System.out.println("返回的bean里面对应的value: " + contextKeyValueBean.getCsValue().getValue()); - } - } - } - -} diff --git a/contextservice/cs-persistence/pom.xml b/contextservice/cs-persistence/pom.xml deleted file mode 100644 index b3a980dcdc..0000000000 --- a/contextservice/cs-persistence/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-persistence - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - com.webank.wedatasphere.linkis - linkis-mybatis - - - - com.webank.wedatasphere.linkis - linkis-module - provided - - - - org.apache.commons - commons-math3 - 3.1.1 - - - - junit - junit - 4.12 - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/java - - **/*.xml - - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/dao/ContextMapMapper.java b/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/dao/ContextMapMapper.java deleted file mode 100644 index 422b2ce445..0000000000 --- a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/dao/ContextMapMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.persistence.dao; - -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextScope; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextType; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.persistence.entity.PersistenceContextKeyValue; -import org.apache.ibatis.annotations.Param; - -import java.util.List; - -/** - * Created by patinousward on 2020/2/13. - */ -public interface ContextMapMapper { - void createMap(PersistenceContextKeyValue pKV); - - void updateMap(PersistenceContextKeyValue pKV); - - PersistenceContextKeyValue getContextMap(@Param("contextID") ContextID contextID, @Param("contextKey") ContextKey contextKey); - - List getAllContextMapByKey(@Param("contextID") ContextID contextID, @Param("key") String key); - - List getAllContextMapByContextID(@Param("contextID") ContextID contextID); - - List getAllContextMapByScope(@Param("contextID") ContextID contextID, @Param("contextScope") ContextScope contextScope); - - List getAllContextMapByType(@Param("contextID") ContextID contextID, @Param("contextType") ContextType contextType); - - void removeContextMap(@Param("contextID") ContextID contextID, @Param("contextKey") ContextKey contextKey); - - void removeAllContextMapByContextID(@Param("contextID") ContextID contextID); - - void removeAllContextMapByType(@Param("contextID") ContextID contextID, @Param("contextType") ContextType contextType); - - void removeAllContextMapByScope(@Param("contextID") ContextID contextID, @Param("contextScope") ContextScope contextScope); - - void removeByKeyPrefixAndContextType(@Param("contextID") ContextID contextID, @Param("contextType") ContextType contextType, @Param("keyPrefix") String keyPrefix); - - void removeByKeyPrefix(@Param("contextID") ContextID contextID, @Param("keyPrefix") String keyPrefix); -} diff --git a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/persistence/TransactionManager.java b/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/persistence/TransactionManager.java deleted file mode 100644 index 19fcafd906..0000000000 --- a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/persistence/TransactionManager.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.persistence.persistence; - -/** - * Created by patinousward on 2020/2/11. - */ -public interface TransactionManager { - - Object begin(); - - void rollback(Object object); - - void commit(Object object); - - void onTransaction(); - -} diff --git a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/util/PersistenceUtils.java b/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/util/PersistenceUtils.java deleted file mode 100644 index 8e29dc21ec..0000000000 --- a/contextservice/cs-persistence/src/main/java/com/webank/wedatasphere/linkis/cs/persistence/util/PersistenceUtils.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.persistence.util; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; -import com.webank.wedatasphere.linkis.cs.common.exception.CSWarnException; -import com.webank.wedatasphere.linkis.cs.common.serialize.helper.ContextSerializationHelper; -import com.webank.wedatasphere.linkis.cs.common.serialize.helper.SerializationHelper; -import com.webank.wedatasphere.linkis.cs.persistence.annotation.Ignore; -import com.webank.wedatasphere.linkis.cs.persistence.entity.ExtraFieldClass; -import com.webank.wedatasphere.linkis.cs.persistence.exception.ThrowingFunction; -import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper; -import org.apache.commons.math3.util.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * Created by patinousward on 2020/2/13. - */ -public class PersistenceUtils { - - private static ObjectMapper json = BDPJettyServerHelper.jacksonJson(); - - private static final Logger logger = LoggerFactory.getLogger(PersistenceUtils.class); - - private static String generateGetMethod(Field field) { - String fieldName = field.getName(); - return String.format("get%s%s", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1)); - } - - public static String generateSetMethod(String fieldName) { - return String.format("set%s%s", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1)); - } - - private static boolean canIgnore(Field field) { - return field.getAnnotation(Ignore.class) != null; - } - - private static List getIgnoreFieldName(Class> clazz) { - if (clazz.getAnnotation(Ignore.class) != null) { - return Arrays.stream(clazz.getDeclaredFields()).map(Field::getName).collect(Collectors.toList()); - } else { - return Arrays.stream(clazz.getDeclaredFields()) - .filter(PersistenceUtils::canIgnore).map(Field::getName).collect(Collectors.toList()); - } - } - - public static Pair transfer(T t, Class sClass) throws CSErrorException { - try { - ExtraFieldClass extraFieldClass = new ExtraFieldClass(); - S s = sClass.newInstance(); - BeanUtils.copyProperties(t, s); - Class> tClass = t.getClass(); - extraFieldClass.setClassName(tClass.getName()); - List canIgnore = getIgnoreFieldName(sClass); - for (Field field : tClass.getDeclaredFields()) { - if (!canIgnore.contains(field.getName())) { - Method method = tClass.getMethod(generateGetMethod(field)); - if (null != method.invoke(t)) { - //field.getType().getName() 无法拿到子类的类型 - Object invoke = method.invoke(t); - extraFieldClass.addFieldName(field.getName()); - if (invoke == null) { - extraFieldClass.addFieldType(field.getType().getName()); - } else { - extraFieldClass.addFieldType(invoke.getClass().getName()); - } - extraFieldClass.addFieldValue(invoke); - } - } - } - return new Pair<>(s, extraFieldClass); - } catch (Exception e) { - throw new CSErrorException(97000, "transfer bean failed:", e); - } - } - - public static T transfer(ExtraFieldClass extraFieldClass, S s) throws CSErrorException { - if (s == null) return null; - try { - Class> tClass = Class.forName(extraFieldClass.getClassName()); - T t = (T) tClass.newInstance(); - BeanUtils.copyProperties(s, t); - for (int i = 0; i < extraFieldClass.getFieldNames().size(); i++) { - Field field = tClass.getDeclaredField(extraFieldClass.getOneFieldName(i)); - field.setAccessible(true); - if (LONG_TYP.equals(extraFieldClass.getOneFieldType(i))) { - Long value = new Long(extraFieldClass.getOneFieldValue(i).toString()); - field.set(t, value); - } else if (Enum.class.isAssignableFrom(Class.forName(extraFieldClass.getOneFieldType(i)))) { - //反序列化支持枚举类 - Class> enumClass = Class.forName(extraFieldClass.getOneFieldType(i)); - Method valueOf = enumClass.getMethod("valueOf", String.class); - Object invoke = valueOf.invoke(null, extraFieldClass.getOneFieldValue(i)); - field.set(t, invoke); - } else if (!BeanUtils.isSimpleProperty(Class.forName(extraFieldClass.getOneFieldType(i)))) { - //非基本类型的话,使用jackson进行反序列化 // TODO: 2020/3/5 这里属性的序列化and反序列化最好修改为utils的序列化器 - Object o = json.convertValue(extraFieldClass.getOneFieldValue(i), Class.forName(extraFieldClass.getOneFieldType(i))); - field.set(t, o); - } else { - field.set(t, extraFieldClass.getOneFieldValue(i)); - } - } - return t; - } catch (Exception e) { - throw new CSErrorException(97000, "transfer bean failed:", e); - } - } - - public static Function map( - ThrowingFunction throwingFunction) { - return i -> { - try { - return throwingFunction.accept(i); - } catch (Exception e) { - throw new CSWarnException(97000, "execute failed,reason:", e); - } - }; - } - - private static final String LONG_TYP = "java.lang.Long"; - - // TODO: 2020/5/15 去掉重复的 - public static final SerializationHelper SERIALIZE = ContextSerializationHelper.getInstance(); - - public static String serialize(Object o) throws CSErrorException { - if (o instanceof String) { - return (String) o; - } - return SERIALIZE.serialize(o); - } - - public static T deserialize(String Str) throws CSErrorException { - return (T) SERIALIZE.deserialize(Str); - } - -} diff --git a/contextservice/cs-search/pom.xml b/contextservice/cs-search/pom.xml deleted file mode 100644 index a30d66c54b..0000000000 --- a/contextservice/cs-search/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-search - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - com.webank.wedatasphere.linkis - linkis-cs-cache - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - provided - - - - junit - junit - RELEASE - test - - - org.mockito - mockito-all - 2.0.2-beta - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/execution/matcher/NearestLogicContextSearchMatcher.java b/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/execution/matcher/NearestLogicContextSearchMatcher.java deleted file mode 100644 index 095ed1242d..0000000000 --- a/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/execution/matcher/NearestLogicContextSearchMatcher.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.execution.matcher; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.condition.impl.NearestCondition; -import com.webank.wedatasphere.linkis.cs.condition.impl.NotCondition; - -public class NearestLogicContextSearchMatcher extends UnaryLogicContextSearchMatcher{ - - public NearestLogicContextSearchMatcher(NearestCondition condition) { - super(condition); - } - - @Override - public Boolean match(ContextKeyValue contextKeyValue) { - return originalMatcher.match(contextKeyValue); - } -} diff --git a/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/optimize/dfs/Node.java b/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/optimize/dfs/Node.java deleted file mode 100644 index 85fb8ffffb..0000000000 --- a/contextservice/cs-search/src/main/java/com/webank/wedatasphere/linkis/cs/optimize/dfs/Node.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.optimize.dfs; - -public interface Node { - Double getCost(); - Double getPriority(); - Node getLeft(); - Node getRight(); - void shift(); - boolean visited(); - void visit(); -} diff --git a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/csid/TestContextID.java b/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/csid/TestContextID.java deleted file mode 100644 index 0fbdb6b11f..0000000000 --- a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/csid/TestContextID.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.csid; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; - -/** - * @author peacewong - * @date 2020/2/13 20:41 - */ -public class TestContextID implements ContextID { - - String contextID; - - @Override - public String getContextId() { - return contextID; - } - - @Override - public void setContextId(String contextId) { - this.contextID = contextId; - } -} diff --git a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKey.java b/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKey.java deleted file mode 100644 index 74bd9c6150..0000000000 --- a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKey.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.keyword; - -import com.webank.wedatasphere.linkis.cs.common.annotation.KeywordMethod; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextScope; -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextType; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; - -/** - * @author peacewong - * @date 2020/2/13 16:32 - */ -public class TestContextKey implements ContextKey { - - private String key; - - private String keywords; - - private ContextScope contextScope; - - private ContextType contextType; - - @KeywordMethod - @Override - public String getKey() { - return this.key; - } - - @Override - public void setKey(String key) { - this.key = key; - } - - @Override - public ContextType getContextType() { - return contextType; - } - - @Override - public void setContextType(ContextType contextType) { - this.contextType = contextType; - } - - @Override - public ContextScope getContextScope() { - return contextScope; - } - - @Override - public void setContextScope(ContextScope contextScope) { - this.contextScope = contextScope; - } - - @KeywordMethod(splitter = ",") - @Override - public String getKeywords() { - return this.keywords; - } - - @Override - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - - @Override - public int getType() { - return 0; - } - - @Override - public void setType(int type) { - - } -} diff --git a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKeyValue.java b/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKeyValue.java deleted file mode 100644 index 79d8a67091..0000000000 --- a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextKeyValue.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.keyword; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; - -/** - * @author peacewong - * @date 2020/2/13 16:46 - */ -public class TestContextKeyValue implements ContextKeyValue { - - private ContextKey contextKey; - - private ContextValue contextValue; - - @Override - public ContextKey getContextKey() { - return this.contextKey; - } - - @Override - public void setContextKey(ContextKey contextKey) { - this.contextKey = contextKey; - } - - @Override - public ContextValue getContextValue() { - return this.contextValue; - } - - @Override - public void setContextValue(ContextValue contextValue) { - this.contextValue = contextValue; - } -} diff --git a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextValue.java b/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextValue.java deleted file mode 100644 index 0a34ed4277..0000000000 --- a/contextservice/cs-search/src/test/java/com/webank/wedatasphere/linkis/cs/keyword/TestContextValue.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.webank.wedatasphere.linkis.cs.keyword; - -import com.webank.wedatasphere.linkis.cs.common.annotation.KeywordMethod; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ValueBean; - -/** - * @author peacewong - * @date 2020/2/13 16:44 - */ -public class TestContextValue implements ContextValue { - - private Object value; - - private String keywords; - - @KeywordMethod(splitter = "-") - @Override - public String getKeywords() { - return this.keywords; - } - - @Override - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - @KeywordMethod(regex = "hello") - @Override - public Object getValue() { - return this.value; - } - - @Override - public void setValue(Object value) { - this.value = value; - } -} diff --git a/contextservice/cs-server/Dockerfile b/contextservice/cs-server/Dockerfile deleted file mode 100644 index 9c136f496f..0000000000 --- a/contextservice/cs-server/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-cs-server.zip /opt/linkis -RUN unzip linkis-cs-server.zip - -WORKDIR /opt/linkis/linkis-cs-server/bin -ENTRYPOINT ["/opt/linkis/linkis-cs-server/bin/startup.sh"] diff --git a/contextservice/cs-server/bin/start-cs-server.sh b/contextservice/cs-server/bin/start-cs-server.sh deleted file mode 100755 index 6278ff3a6f..0000000000 --- a/contextservice/cs-server/bin/start-cs-server.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-gc.log" -fi - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -nohup java $SERVER_JAVA_OPTS -cp ../module/lib/*:$HOME/conf:$HOME/lib/* $SERVER_CLASS 2>&1 > $SERVER_LOG_PATH/linkis.out & -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi \ No newline at end of file diff --git a/contextservice/cs-server/bin/startup.sh b/contextservice/cs-server/bin/startup.sh deleted file mode 100755 index 7ed6a42bde..0000000000 --- a/contextservice/cs-server/bin/startup.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-cs-server-gc.log" -fi - -if test -z "$START_PORT" -then - export START_PORT=22008 -fi - -export SERVER_PID=$HOME/bin/linkis.pid - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -cp -f /opt/linkis/conf/linkis.properties /opt/linkis/linkis-cs-server/conf - -nohup java $SERVER_JAVA_OPTS -Deurekaurl=$EUREKA_URL -Duser.timezone=Asia/Shanghai -cp $HOME/conf:$HOME/lib/* $SERVER_CLASS --server.port=$START_PORT 2>&1 > $SERVER_LOG_PATH/linkis-cs-server.log & - -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi - -tail -f /dev/null diff --git a/contextservice/cs-server/bin/stop-cs-server.sh b/contextservice/cs-server/bin/stop-cs-server.sh deleted file mode 100755 index 9e84be4f12..0000000000 --- a/contextservice/cs-server/bin/stop-cs-server.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/bash -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/contextservice/cs-server/bin/stop.sh b/contextservice/cs-server/bin/stop.sh deleted file mode 100755 index 9e84be4f12..0000000000 --- a/contextservice/cs-server/bin/stop.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/bash -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/contextservice/cs-server/conf/application.yml b/contextservice/cs-server/conf/application.yml deleted file mode 100644 index 3cfdeaeb62..0000000000 --- a/contextservice/cs-server/conf/application.yml +++ /dev/null @@ -1,48 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -server: - port: 9042 -spring: - application: - name: cloud-contextservice - - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: test-user - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - -pagehelper: - helper-dialect: mysql - reasonable: true - support-methods-arguments: true - params: countSql \ No newline at end of file diff --git a/contextservice/cs-server/conf/linkis.properties b/contextservice/cs-server/conf/linkis.properties deleted file mode 100644 index 78e88064ab..0000000000 --- a/contextservice/cs-server/conf/linkis.properties +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright 2019 WeBank -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -wds.linkis.server.mybatis.datasource.url=jdbc:mysql://127.0.0.1:3306/dss_dev_center?characterEncoding=UTF-8 -wds.linkis.server.mybatis.datasource.username= -wds.linkis.server.mybatis.datasource.password= -wds.linkis.server.version=v1 -##restful -wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.cs.server.restful -##mybatis -wds.linkis.server.mybatis.mapperLocations=classpath*:com/webank/wedatasphere/linkis/cs/persistence/dao/impl/*.xml -wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.cs.persistence.entity -wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.cs.persistence.dao diff --git a/contextservice/cs-server/conf/log4j.properties b/contextservice/cs-server/conf/log4j.properties deleted file mode 100644 index de6691ad21..0000000000 --- a/contextservice/cs-server/conf/log4j.properties +++ /dev/null @@ -1,26 +0,0 @@ -# -# Copyright 2019 WeBank -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -log4j.rootCategory=INFO,console -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=INFO -log4j.appender.console.layout=org.apache.log4j.PatternLayout -#log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n -log4j.appender.console.layout.ConversionPattern=%d{ISO8601} %-5p (%t) %p %c{1} - %m%n -log4j.appender.com.webank.bdp.ide.core=org.apache.log4j.DailyRollingFileAppender -log4j.appender.com.webank.bdp.ide.core.Threshold=INFO -log4j.additivity.com.webank.bdp.ide.core=false -log4j.appender.com.webank.bdp.ide.core.layout=org.apache.log4j.PatternLayout -log4j.appender.com.webank.bdp.ide.core.Append=true -log4j.appender.com.webank.bdp.ide.core.File=logs/linkis.log -log4j.appender.com.webank.bdp.ide.core.layout.ConversionPattern=%d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n -log4j.logger.org.springframework=INFO \ No newline at end of file diff --git a/contextservice/cs-server/pom.xml b/contextservice/cs-server/pom.xml deleted file mode 100644 index 3679595cf6..0000000000 --- a/contextservice/cs-server/pom.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-server - - - - com.webank.wedatasphere.linkis - linkis-cs-common - ${project.version} - - - - com.webank.wedatasphere.linkis - linkis-cs-cache - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-listener - ${project.version} - - - - com.webank.wedatasphere.linkis - linkis-cs-persistence - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-highavailable - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-search - ${project.version} - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - ${project.version} - provided - - - - com.webank.wedatasphere.linkis - linkis-scheduler - ${project.version} - - - - junit - junit - 4.12 - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - scala-compile-first - process-resources - - add-source - compile - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-cs-server - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - - \ No newline at end of file diff --git a/contextservice/cs-server/pom_k8s.xml b/contextservice/cs-server/pom_k8s.xml deleted file mode 100644 index 65491d9391..0000000000 --- a/contextservice/cs-server/pom_k8s.xml +++ /dev/null @@ -1,204 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-server - - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - com.webank.wedatasphere.linkis - linkis-cs-cache - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-listener - - - - com.webank.wedatasphere.linkis - linkis-cs-persistence - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-highavailable - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cs-search - - - com.webank.wedatasphere.linkis - linkis-module - - - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - tomcat - jasper-compiler - - - tomcat - jasper-runtime - - - - - - com.webank.wedatasphere.linkis - linkis-scheduler - - - - junit - junit - 4.12 - test - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - scala-compile-first - process-resources - - add-source - compile - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-cs-server - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - - \ No newline at end of file diff --git a/contextservice/cs-server/src/main/assembly/distribution.xml b/contextservice/cs-server/src/main/assembly/distribution.xml deleted file mode 100644 index ac1d394d86..0000000000 --- a/contextservice/cs-server/src/main/assembly/distribution.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - linkis-cs-server - - zip - - true - linkis-cs-server - - - - - - lib - true - true - false - false - true - - - - - - - ${basedir}/conf - - * - - 0777 - conf - unix - - - ${basedir}/bin - - * - - 0777 - bin - unix - - - . - - */** - - logs - - - - - diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/enumeration/ServiceMethod.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/enumeration/ServiceMethod.java deleted file mode 100644 index fbc241a9a7..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/enumeration/ServiceMethod.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.enumeration; - -/** - * Created by patinousward on 2020/2/22. - */ -public enum ServiceMethod { - /** - * - */ - CREATE, GET, SEARCH, REMOVE, REMOVEALL, UPDATE, RESET, SET, BIND, HEARTBEAT -} diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextIDRestfulApi.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextIDRestfulApi.java deleted file mode 100644 index 2b33bcd660..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextIDRestfulApi.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.restful; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; -import com.webank.wedatasphere.linkis.cs.common.protocol.ContextHTTPConstant; -import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceMethod; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceType; -import com.webank.wedatasphere.linkis.cs.server.scheduler.CsScheduler; -import com.webank.wedatasphere.linkis.cs.server.scheduler.HttpAnswerJob; -import com.webank.wedatasphere.linkis.server.Message; -import org.codehaus.jackson.JsonNode; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; - -/** - * Created by patinousward on 2020/2/18. - */ -@Component -@Path("/contextservice") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class ContextIDRestfulApi implements CsRestfulParent { - - @Autowired - private CsScheduler csScheduler; - - @POST - @Path("createContextID") - public Response createContextID(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, ClassNotFoundException, IOException, CSErrorException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CREATE, contextID); - return Message.messageToResponse(generateResponse(answerJob, "contextId")); - } - - @GET - @Path("getContextID") - public Response getContextID(@Context HttpServletRequest req, @QueryParam("contextId") String id) throws InterruptedException, CSErrorException { - if (StringUtils.isEmpty(id)) { - throw new CSErrorException(97000, "contxtId cannot be empty"); - } - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, id); - Message message = generateResponse(answerJob, "contextID"); - return Message.messageToResponse(message); - } - - @POST - @Path("updateContextID") - public Response updateContextID(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - if (StringUtils.isEmpty(contextID.getContextId())) { - throw new CSErrorException(97000, "contxtId cannot be empty"); - } - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.UPDATE, contextID); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("resetContextID") - public Response resetContextID(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException { - if (!jsonNode.has(ContextHTTPConstant.CONTEXT_ID_STR)) { - throw new CSErrorException(97000, ContextHTTPConstant.CONTEXT_ID_STR + " cannot be empty"); - } - String id = jsonNode.get(ContextHTTPConstant.CONTEXT_ID_STR).getTextValue(); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, id); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - - @POST - @Path("removeContextID") - public Response removeContextID(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException { - String id = jsonNode.get("contextId").getTextValue(); - if (StringUtils.isEmpty(id)) { - throw new CSErrorException(97000, "contxtId cannot be empty"); - } - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, id); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @Override - public ServiceType getServiceType() { - return ServiceType.CONTEXT_ID; - } - - @Override - public CsScheduler getScheduler() { - return this.csScheduler; - } - -} diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextListenerRestfulApi.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextListenerRestfulApi.java deleted file mode 100644 index 5b9fa70edc..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextListenerRestfulApi.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.restful; - -import com.webank.wedatasphere.linkis.cs.common.entity.listener.CommonContextIDListenerDomain; -import com.webank.wedatasphere.linkis.cs.common.entity.listener.CommonContextKeyListenerDomain; -import com.webank.wedatasphere.linkis.cs.common.entity.listener.ContextIDListenerDomain; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceMethod; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceType; -import com.webank.wedatasphere.linkis.cs.server.scheduler.CsScheduler; -import com.webank.wedatasphere.linkis.cs.server.scheduler.HttpAnswerJob; -import com.webank.wedatasphere.linkis.server.Message; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.map.ObjectMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; - -/** - * Created by patinousward on 2020/2/18. - */ -@Component -@Path("/contextservice") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class ContextListenerRestfulApi implements CsRestfulParent { - - @Autowired - private CsScheduler csScheduler; - - private ObjectMapper objectMapper = new ObjectMapper(); - - @POST - @Path("onBindIDListener") - public Response onBindIDListener(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - String source = jsonNode.get("source").getTextValue(); - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextIDListenerDomain listener = new CommonContextIDListenerDomain(); - listener.setSource(source); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.BIND, contextID, listener); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("onBindKeyListener") - public Response onBindKeyListener(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - String source = jsonNode.get("source").getTextValue(); - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKey contextKey = getContextKeyFromJsonNode(jsonNode); - CommonContextKeyListenerDomain listener = new CommonContextKeyListenerDomain(); - listener.setSource(source); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.BIND, contextID, contextKey, listener); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("heartbeat") - public Response heartbeat(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, IOException, CSErrorException { - String source = jsonNode.get("source").getTextValue(); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.HEARTBEAT, source); - return Message.messageToResponse(generateResponse(answerJob, "ContextKeyValueBean")); - } - - @Override - public ServiceType getServiceType() { - return ServiceType.CONTEXT_LISTENER; - } - - @Override - public CsScheduler getScheduler() { - return this.csScheduler; - } -} diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextRestfulApi.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextRestfulApi.java deleted file mode 100644 index ea2e1cf8f6..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/ContextRestfulApi.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.restful; - -import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.ContextType; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; -import com.webank.wedatasphere.linkis.cs.common.protocol.ContextHTTPConstant; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceMethod; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceType; -import com.webank.wedatasphere.linkis.cs.server.scheduler.CsScheduler; -import com.webank.wedatasphere.linkis.cs.server.scheduler.HttpAnswerJob; -import com.webank.wedatasphere.linkis.server.Message; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.type.TypeReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.Map; - - -/** - * Created by patinousward on 2020/2/18. - */ -@Component -@Path("contextservice") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class ContextRestfulApi implements CsRestfulParent { - - private static final Logger LOGGER = LoggerFactory.getLogger(ContextRestfulApi.class); - - @Autowired - private CsScheduler csScheduler; - - private ObjectMapper objectMapper = new ObjectMapper(); - - @POST - @Path("getContextValue") - public Response getContextValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKey contextKey = getContextKeyFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID, contextKey); - Message message = generateResponse(answerJob, "contextValue"); - return Message.messageToResponse(message); - } - - - @POST - @Path("searchContextValue") - public Response searchContextValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - JsonNode condition = jsonNode.get("condition"); - Map conditionMap = objectMapper.convertValue(condition, new TypeReference>() { - }); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, contextID, conditionMap); - Message message = generateResponse(answerJob, "contextKeyValue"); - return Message.messageToResponse(message); - } - -/* @GET - @Path("searchContextValueByCondition") - public Response searchContextValueByCondition(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException { - Condition condition = null; - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, condition); - return generateResponse(answerJob,""); - }*/ - - - @POST - @Path("setValueByKey") - public Response setValueByKey(@Context HttpServletRequest req, JsonNode jsonNode) throws CSErrorException, IOException, ClassNotFoundException, InterruptedException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKey contextKey = getContextKeyFromJsonNode(jsonNode); - ContextValue contextValue = getContextValueFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SET, contextID, contextKey, contextValue); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("setValue") - public Response setValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKeyValue contextKeyValue = getContextKeyValueFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SET, contextID, contextKeyValue); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("resetValue") - public Response resetValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKey contextKey = getContextKeyFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, contextID, contextKey); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("removeValue") - public Response removeValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - ContextKey contextKey = getContextKeyFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, contextID, contextKey); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("removeAllValue") - public Response removeAllValue(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("removeAllValueByKeyPrefixAndContextType") - public Response removeAllValueByKeyPrefixAndContextType(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - String contextType = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_TYPE_STR).getTextValue(); - String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).getTextValue(); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID, ContextType.valueOf(contextType),keyPrefix); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @POST - @Path("removeAllValueByKeyPrefix") - public Response removeAllValueByKeyPrefix(@Context HttpServletRequest req, JsonNode jsonNode) throws InterruptedException, CSErrorException, IOException, ClassNotFoundException { - ContextID contextID = getContextIDFromJsonNode(jsonNode); - String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).getTextValue(); - HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID,keyPrefix); - return Message.messageToResponse(generateResponse(answerJob, "")); - } - - @Override - public ServiceType getServiceType() { - return ServiceType.CONTEXT; - } - - @Override - public CsScheduler getScheduler() { - return this.csScheduler; - } -} diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/CsRestfulParent.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/CsRestfulParent.java deleted file mode 100644 index f34c482584..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/restful/CsRestfulParent.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.restful; - -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextID; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKey; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextKeyValue; -import com.webank.wedatasphere.linkis.cs.common.entity.source.ContextValue; -import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceMethod; -import com.webank.wedatasphere.linkis.cs.server.enumeration.ServiceType; -import com.webank.wedatasphere.linkis.cs.server.protocol.HttpRequestProtocol; -import com.webank.wedatasphere.linkis.cs.server.protocol.HttpResponseProtocol; -import com.webank.wedatasphere.linkis.cs.server.protocol.RestResponseProtocol; -import com.webank.wedatasphere.linkis.cs.server.scheduler.CsScheduler; -import com.webank.wedatasphere.linkis.cs.server.scheduler.HttpAnswerJob; -import com.webank.wedatasphere.linkis.cs.server.scheduler.RestJobBuilder; -import com.webank.wedatasphere.linkis.cs.server.util.CsUtils; -import com.webank.wedatasphere.linkis.server.Message; -import com.webank.wedatasphere.linkis.server.security.SecurityFilter; -import org.codehaus.jackson.JsonNode; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by patinousward on 2020/2/22. - */ -public interface CsRestfulParent { - - default HttpAnswerJob submitRestJob(HttpServletRequest req, - ServiceMethod method, - Object... objects) throws InterruptedException { - // TODO: 2020/3/3 单例 - HttpAnswerJob job = (HttpAnswerJob) new RestJobBuilder().build(getServiceType()); - HttpRequestProtocol protocol = job.getRequestProtocol(); - protocol.setUsername(SecurityFilter.getLoginUsername(req)); - protocol.setServiceMethod(method); - protocol.setRequestObjects(objects); - getScheduler().sumbit(job); - return job; - } - - default Message generateResponse(HttpAnswerJob job, String responseKey) throws CSErrorException { - HttpResponseProtocol responseProtocol = job.getResponseProtocol(); - if (responseProtocol instanceof RestResponseProtocol) { - Message message = ((RestResponseProtocol) responseProtocol).get(); - if (message == null) { - return Message.error("job execute timeout"); - } - int status = ((RestResponseProtocol) responseProtocol).get().getStatus(); - if (status == 1) { - //failed - return ((RestResponseProtocol) responseProtocol).get(); - } else if (status == 0) { - Object data = job.getResponseProtocol().getResponseData(); - if (data == null) { - return Message.ok().data(responseKey, null); - } else if (data instanceof List && ((List) data).isEmpty()) { - return Message.ok().data(responseKey, new String[]{}); - } else if (data instanceof List) { - ArrayList strings = new ArrayList<>(); - for (Object d : (List) data) { - strings.add(CsUtils.serialize(d)); - } - return Message.ok().data(responseKey, strings); - } else { - String dataStr = CsUtils.serialize(data); - return Message.ok().data(responseKey, dataStr); - } - } else { - - } - } - return Message.ok(); - } - - ServiceType getServiceType(); - - CsScheduler getScheduler(); - - default ContextID getContextIDFromJsonNode(JsonNode jsonNode) throws CSErrorException, IOException, ClassNotFoundException { - return deserialize(jsonNode, "contextID"); - } - - default T deserialize(JsonNode jsonNode, String key) throws CSErrorException { - String str = jsonNode.get(key).getTextValue(); - return (T) CsUtils.SERIALIZE.deserialize(str); - } - - default ContextKey getContextKeyFromJsonNode(JsonNode jsonNode) throws CSErrorException, IOException, ClassNotFoundException { - return deserialize(jsonNode, "contextKey"); - } - - default ContextValue getContextValueFromJsonNode(JsonNode jsonNode) throws CSErrorException, IOException, ClassNotFoundException { - return deserialize(jsonNode, "contextValue"); - } - - default ContextKeyValue getContextKeyValueFromJsonNode(JsonNode jsonNode) throws CSErrorException, IOException, ClassNotFoundException { - return deserialize(jsonNode, "contextKeyValue"); - } - - - -} diff --git a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/scheduler/linkisImpl/CsExecutorManager.java b/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/scheduler/linkisImpl/CsExecutorManager.java deleted file mode 100644 index 08e55c9c5c..0000000000 --- a/contextservice/cs-server/src/main/java/com/webank/wedatasphere/linkis/cs/server/scheduler/linkisImpl/CsExecutorManager.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.cs.server.scheduler.linkisImpl; - -import com.webank.wedatasphere.linkis.scheduler.executer.Executor; -import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorManager; -import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener; -import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEvent; -import scala.Option; -import scala.Some; -import scala.concurrent.duration.Duration; - -/** - * Created by patinousward on 2020/2/18. - */ -public class CsExecutorManager extends ExecutorManager { - - @Override - public void setExecutorListener(ExecutorListener executorListener) { - - } - - @Override - public Executor createExecutor(SchedulerEvent event) { - return new CsExecutor(); - } - - @Override - public Option askExecutor(SchedulerEvent event) { - return new Some<>(createExecutor(event)); - } - - @Override - public Option askExecutor(SchedulerEvent event, Duration wait) { - return askExecutor(event); - } - - @Override - public Option getById(long id) { - return new Some<>(null); - } - - @Override - public Executor[] getByGroup(String groupName) { - return new Executor[0]; - } - - @Override - public void delete(Executor executor) { - - } - - @Override - public void shutdown() { - - } -} diff --git a/contextservice/cs-server/src/main/resources/application.yml b/contextservice/cs-server/src/main/resources/application.yml deleted file mode 100644 index 246846d777..0000000000 --- a/contextservice/cs-server/src/main/resources/application.yml +++ /dev/null @@ -1,38 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -server: - port: 9004 -spring: - application: - name: cloud-contextservice - - -eureka: - client: - serviceUrl: - defaultZone: http://127.0.0.1:20303/eureka/ - instance: - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml diff --git a/contextservice/cs-server/src/main/resources/linkis.properties b/contextservice/cs-server/src/main/resources/linkis.properties deleted file mode 100644 index 9abef042eb..0000000000 --- a/contextservice/cs-server/src/main/resources/linkis.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright 2019 WeBank -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -wds.linkis.test.mode=true - -wds.linkis.server.mybatis.datasource.url=jdbc:mysql://127.0.0.1:3306/ide_gz_bdap_sit_01?characterEncoding=UTF-8 -wds.linkis.server.mybatis.datasource.username= -wds.linkis.server.mybatis.datasource.password= - - -wds.linkis.log.clear=true -wds.linkis.server.version=v1 - -##restful -wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.cs.server.restful - -##mybatis -wds.linkis.server.mybatis.mapperLocations=classpath*:com\\webank\\wedatasphere\\linkis\\cs\\persistence\\dao\\impl\\*.xml - -wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.cs.persistence.entity - -wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.cs.persistence.dao diff --git a/contextservice/cs-server/src/main/resources/log4j.properties b/contextservice/cs-server/src/main/resources/log4j.properties deleted file mode 100644 index 0807e60877..0000000000 --- a/contextservice/cs-server/src/main/resources/log4j.properties +++ /dev/null @@ -1,37 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# - -### set log levels ### - -log4j.rootCategory=INFO,console - -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=INFO -log4j.appender.console.layout=org.apache.log4j.PatternLayout -#log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n -log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) %p %c{1} - %m%n - - -log4j.appender.com.webank.bdp.ide.core=org.apache.log4j.DailyRollingFileAppender -log4j.appender.com.webank.bdp.ide.core.Threshold=INFO -log4j.additivity.com.webank.bdp.ide.core=false -log4j.appender.com.webank.bdp.ide.core.layout=org.apache.log4j.PatternLayout -log4j.appender.com.webank.bdp.ide.core.Append=true -log4j.appender.com.webank.bdp.ide.core.File=logs/linkis.log -log4j.appender.com.webank.bdp.ide.core.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n - -log4j.logger.org.springframework=INFO diff --git a/contextservice/cs-server/src/main/resources/log4j2.xml b/contextservice/cs-server/src/main/resources/log4j2.xml deleted file mode 100644 index 3923cd9f39..0000000000 --- a/contextservice/cs-server/src/main/resources/log4j2.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/contextservice/cs-ujes-client/pom.xml b/contextservice/cs-ujes-client/pom.xml deleted file mode 100644 index fd8b60ecd4..0000000000 --- a/contextservice/cs-ujes-client/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cs-ujes-client - - - - com.webank.wedatasphere.linkis - linkis-cs-client - - - com.webank.wedatasphere.linkis - linkis-storage - provided - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - - - \ No newline at end of file diff --git a/core/cloudModule/pom.xml b/core/cloudModule/pom.xml deleted file mode 100644 index be71d09e22..0000000000 --- a/core/cloudModule/pom.xml +++ /dev/null @@ -1,553 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-module - - - - com.webank.wedatasphere.linkis - linkis-common - - - json4s-jackson_2.11 - org.json4s - - - jackson-core - com.fasterxml.jackson.core - - - - - - org.springframework.boot - spring-boot - ${spring.boot.version} - - - org.apache.logging.log4j - log4j-api - - - org.apache.logging.log4j - log4j-core - - - - - org.springframework.cloud - spring-cloud-starter-eureka - ${spring.eureka.version} - - - jsr311-api - javax.ws.rs - - - jackson-annotations - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - jackson-databind - com.fasterxml.jackson.core - - - httpclient - org.apache.httpcomponents - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - org.springframework.cloud - spring-cloud-starter-netflix-archaius - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - guava - com.google.guava - - - org.springframework.boot - spring-boot-autoconfigure - - - org.springframework.boot - spring-boot - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - 2.0.0.RELEASE - - - jsr311-api - javax.ws.rs - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-annotations - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - - - - org.springframework.boot - spring-boot-starter-jetty - ${spring.boot.version} - - - asm - org.ow2.asm - - - javax.annotation-api - javax.annotation - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - hibernate-validator - org.hibernate.validator - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-datatype-jdk8 - com.fasterxml.jackson.datatype - - - jackson-datatype-jsr310 - com.fasterxml.jackson.datatype - - - jackson-module-parameter-names - com.fasterxml.jackson.module - - - ${spring.boot.version} - - - - org.springframework.boot - spring-boot-starter - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-actuator - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-datatype-jsr310 - com.fasterxml.jackson.datatype - - - - - - org.springframework.cloud - spring-cloud-starter-config - 2.0.0.RELEASE - - - org.springframework.boot - spring-boot-starter-logging - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-annotations - com.fasterxml.jackson.core - - - spring-cloud-commons - org.springframework.cloud - - - org.springframework.cloud - spring-cloud-context - - - - - - org.springframework.boot - spring-boot-starter-aop - - - org.springframework.boot - spring-boot-starter-logging - - - ${spring.boot.version} - - - - mysql - mysql-connector-java - 5.1.49 - - - - org.glassfish.jersey.bundles - jaxrs-ri - 2.21 - - - jersey-container-servlet-core - org.glassfish.jersey.containers - - - jersey-container-servlet - org.glassfish.jersey.containers - - - javax.annotation-api - javax.annotation - - - - - cglib - cglib - 2.2.2 - - - commons-dbcp - commons-dbcp - 1.4 - - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-webapp - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-server - ${jetty.version} - - - - org.glassfish.jersey.ext - jersey-spring3 - ${jersey.servlet.version} - - - org.springframework - spring - - - org.springframework - spring-core - - - org.springframework - spring-web - - - org.springframework - spring-beans - - - org.springframework - spring-context - - - jersey-server - org.glassfish.jersey.core - - - - - - - com.sun.jersey - jersey-server - 1.19.1 - - - jsr311-api - javax.ws.rs - - - - - com.sun.jersey - jersey-servlet - 1.19.1 - - - org.glassfish.jersey.containers - jersey-container-servlet - ${jersey.servlet.version} - - - jersey-common - org.glassfish.jersey.core - - - jersey-server - org.glassfish.jersey.core - - - - - org.glassfish.jersey.containers - jersey-container-servlet-core - ${jersey.servlet.version} - - - javax.ws.rs-api - javax.ws.rs - - - jersey-common - org.glassfish.jersey.core - - - jersey-server - org.glassfish.jersey.core - - - - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - - - jackson-annotations - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - jackson-databind - com.fasterxml.jackson.core - - - jersey-common - org.glassfish.jersey.core - - - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey.version} - - - jersey-common - org.glassfish.jersey.core - - - - - org.glassfish.jersey.ext - jersey-entity-filtering - ${jersey.version} - - - com.sun.jersey - jersey-json - - - jsr311-api - javax.ws.rs - - - 1.19 - - - - com.fasterxml.jackson.core - jackson-databind - ${fasterxml.jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${fasterxml.jackson.version} - - - - org.reflections - reflections - 0.9.10 - - - - com.google.code.gson - gson - - - io.netty - netty-all - ${netty.version} - - - io.netty - netty-transport-native-epoll - ${netty.version} - - - org.json4s - json4s-jackson_${scala.binary.version} - ${json4s.version} - - - org.scala-lang - scala-library - - - jackson-databind - com.fasterxml.jackson.core - - - json4s-core_2.11 - org.json4s - - - - - org.springframework.cloud - spring-cloud-starter-openfeign - 2.0.0.RELEASE - - - guava - com.google.guava - - - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - diff --git a/core/cloudModule/src/main/assembly/distribution.xml b/core/cloudModule/src/main/assembly/distribution.xml deleted file mode 100644 index 865b4a9a34..0000000000 --- a/core/cloudModule/src/main/assembly/distribution.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - module - - zip - - true - module - - - - - - lib - true - true - false - true - true - - io.netty:netty-buffer* - io.netty:netty-codec* - io.netty:netty-common* - io.netty:netty-handler* - io.netty:netty-transport* - - - - - - diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala b/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala deleted file mode 100644 index 5f00528cd5..0000000000 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis - -import java.util - -import javax.servlet.http.HttpServletRequest -import com.webank.wedatasphere.linkis.common.exception.{ErrorException, ExceptionManager, FatalException, WarnException} -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.server.exception.{BDPServerErrorException, NonLoginException} -import com.webank.wedatasphere.linkis.server.security.SecurityFilter -import org.apache.commons.lang.StringUtils -import org.apache.commons.lang.exception.ExceptionUtils -import org.slf4j.Logger - -import scala.collection.{JavaConversions, mutable} - -/** - * Created by enjoyyin on 2018/5/2. - */ -package object server { - - val EXCEPTION_MSG = "errorMsg" - type JMap[K, V] = java.util.HashMap[K, V] - - implicit def getUser(req: HttpServletRequest): String = SecurityFilter.getLoginUsername(req) - - def validateFailed(message: String): Message = Message(status = 2).setMessage(message) - def validate[T](json: util.Map[String, T], keys: String*): Unit = { - keys.foreach(k => if(!json.contains(k) || json.get(k) == null || StringUtils.isEmpty(json.get(k).toString)) - throw new BDPServerErrorException(11001, s"Verification failed, $k cannot be empty!(验证失败,$k 不能为空!)")) - } - def error(message: String): Message = Message.error(message) - implicit def ok(msg: String): Message = Message.ok(msg) - implicit def error(t: Throwable): Message = Message.error(t) - implicit def error(e: (String, Throwable)): Message = Message.error(e) - implicit def error(msg: String, t: Throwable): Message = Message.error(msg -> t) - // def tryCatch[T](tryOp: => T)(catchOp: Throwable => T): T = Utils.tryCatch(tryOp)(catchOp) -// def tryCatch(tryOp: => Message)(catchOp: Throwable => Message): Message = Utils.tryCatch(tryOp){ -// case nonLogin: NonLoginException => Message.noLogin(msg = nonLogin.getMessage) -// case t => catchOp(t) -// } - def catchMsg(tryOp: => Message)(msg: String)(implicit log: Logger): Message = Utils.tryCatch(tryOp){ - case fatal: FatalException => - log.error("Fatal Error, system exit...", fatal) - System.exit(fatal.getErrCode) - Message.error("Fatal Error, system exit...") - case nonLogin: NonLoginException => - val message = Message.noLogin(nonLogin.getMessage) - message.data(EXCEPTION_MSG, nonLogin.toMap) - message - case error: ErrorException => - val cause = error.getCause - val errorMsg = cause match { - case t: ErrorException => s"error code(错误码): ${t.getErrCode}, error message(错误信息): ${t.getDesc}." - case _ => s"error code(错误码): ${error.getErrCode}, error message(错误信息): ${error.getDesc}." - } - log.error(errorMsg, error) - val message = Message.error(errorMsg) - message.data(EXCEPTION_MSG, error.toMap) - message - case warn: WarnException => - val warnMsg = s"Warning code(警告码): ${warn.getErrCode}, Warning message(警告信息): ${warn.getDesc}." - log.warn(warnMsg, warn) - val message = Message.warn(warnMsg) - message.data(EXCEPTION_MSG, warn.toMap) - message - case t => - log.error(msg, t) - val errorMsg = ExceptionUtils.getRootCauseMessage(t) - val message = if(StringUtils.isNotEmpty(errorMsg) && "operation failed(操作失败)" != msg) error(msg + "!the reason(原因):" + errorMsg) - else if(StringUtils.isNotEmpty(errorMsg)) error(errorMsg) else error(msg) - message.data(EXCEPTION_MSG, ExceptionManager.unknownException(message.getMessage)) - } - def catchIt(tryOp: => Message)(implicit log: Logger): Message = catchMsg(tryOp)("operation failed(操作失败)s") - implicit def toScalaBuffer[T](list: util.List[T]): mutable.Buffer[T] = JavaConversions.asScalaBuffer(list) - implicit def toScalaMap[K, V](map: util.Map[K, V]): mutable.Map[K, V] = JavaConversions.mapAsScalaMap(map) - implicit def toJavaList[T](list: mutable.Buffer[T]): util.List[T] = { - val arrayList = new util.ArrayList[T] - list.foreach(arrayList.add) - arrayList - } - implicit def toJavaMap[K, V](map: mutable.Map[K, V]): JMap[K, V] = { - val hashMap = new util.HashMap[K, V]() - map.foreach(m => hashMap.put(m._1, m._2)) - hashMap - } - implicit def toJavaMap[K, V](map: Map[K, V]): JMap[K, V] = { - val hashMap = new util.HashMap[K, V]() - map.foreach(m => hashMap.put(m._1, m._2)) - hashMap - } - implicit def asString(mapWithKey: (util.Map[String, Object], String)): String = mapWithKey._1.get(mapWithKey._2).asInstanceOf[String] - implicit def getString(mapWithKey: (util.Map[String, String], String)): String = mapWithKey._1.get(mapWithKey._2) - implicit def asInt(map: util.Map[String, Object], key: String): Int = map.get(key).asInstanceOf[Int] - implicit def asBoolean(mapWithKey: (util.Map[String, Object], String)): Boolean = mapWithKey._1.get(mapWithKey._2).asInstanceOf[Boolean] - -} diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala b/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala deleted file mode 100644 index 1d01cd60d9..0000000000 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.server.security - -import java.text.DateFormat -import java.util.{Date, Locale} - -import com.webank.wedatasphere.linkis.common.conf.{CommonVars, Configuration} -import com.webank.wedatasphere.linkis.common.utils.{Logging, RSAUtils, Utils} -import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration -import com.webank.wedatasphere.linkis.server.exception.{IllegalUserTicketException, LoginExpireException, NonLoginException} -import com.webank.wedatasphere.linkis.server.security.SSOUtils.sslEnable -import com.webank.wedatasphere.linkis.server.{Message, _} -import javax.servlet._ -import javax.servlet.http.{Cookie, HttpServletRequest, HttpServletResponse} -import org.apache.commons.lang.StringUtils - -/** - * Created by enjoyyin on 2018/1/9. - */ -class SecurityFilter extends Filter with Logging { - private val refererValidate = ServerConfiguration.BDP_SERVER_SECURITY_REFERER_VALIDATE.getValue - private val localAddress = ServerConfiguration.BDP_SERVER_ADDRESS.getValue - protected val testUser = ServerConfiguration.BDP_TEST_USER.getValue - - override def init(filterConfig: FilterConfig): Unit = {} - - private def filterResponse(message: Message)(implicit response: HttpServletResponse): Unit = { - response.setHeader("Content-Type", "application/json;charset=UTF-8") - response.setStatus(Message.messageToHttpStatus(message)) - response.getOutputStream.print(message) - response.getOutputStream.flush() - } - - def doFilter(request: HttpServletRequest)(implicit response: HttpServletResponse): Boolean = { - addAccessHeaders(response) - if(refererValidate) { - //Security certification support, referer limited(安全认证支持,referer限定) - val referer = request.getHeader("Referer") - if(StringUtils.isNotEmpty(referer) && !referer.trim.contains(localAddress)) { - filterResponse(validateFailed("不允许的跨站请求!")) - return false - } - //Security certification support, solving verb tampering(安全认证支持,解决动词篡改) - request.getMethod.toUpperCase match { - case "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "TRACE" | "CONNECT" | "OPTIONS" => - case _ => - filterResponse(validateFailed("Do not use HTTP verbs to tamper with!(不可使用HTTP动词篡改!)")) - return false - } - } - - if(request.getRequestURI == ServerConfiguration.BDP_SERVER_SECURITY_SSL_URI.getValue) { - val message = Message.ok("Get success!(获取成功!)").data("enable", SSOUtils.sslEnable) - if(SSOUtils.sslEnable) message.data("publicKey", RSAUtils.getDefaultPublicKey()) - filterResponse(message) - false - } else if(request.getRequestURI == ServerConfiguration.BDP_SERVER_RESTFUL_LOGIN_URI.getValue) { - true - } else { - val userName = Utils.tryCatch(SecurityFilter.getLoginUser(request)){ - case n: NonLoginException => - if(Configuration.IS_TEST_MODE.getValue) None else { - filterResponse(Message.noLogin(n.getMessage) << request.getRequestURI) - return false - } - case t: Throwable => - SecurityFilter.warn("", t) - throw t - } - if(userName.isDefined) { - true - } else if(Configuration.IS_TEST_MODE.getValue) { - SecurityFilter.info("test mode! login for uri: " + request.getRequestURI) - SecurityFilter.setLoginUser(response, testUser) - true - } else { - filterResponse(Message.noLogin("You are not logged in, please login first!(您尚未登录,请先登录!)") << request.getRequestURI) - false - } - } - } - - override def doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain): Unit = { - val request = servletRequest.asInstanceOf[HttpServletRequest] - implicit val response = servletResponse.asInstanceOf[HttpServletResponse] - if(doFilter(request)) filterChain.doFilter(servletRequest, servletResponse) - if(SecurityFilter.isRequestIgnoreTimeout(request)) SecurityFilter.removeIgnoreTimeoutSignal(response) - } - - protected def addAccessHeaders(response: HttpServletResponse) { - response.setHeader("Access-Control-Allow-Origin", "*") - response.setHeader("Access-Control-Allow-Credentials", "true") - response.setHeader("Access-Control-Allow-Headers", "authorization,Content-Type") - response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, HEAD, DELETE") - val fullDateFormatEN = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, new Locale("EN", "en")) - response.setHeader("Date", fullDateFormatEN.format(new Date)) - } - - override def destroy(): Unit = {} -} - -object SecurityFilter extends Logging { - private[linkis] val OTHER_SYSTEM_IGNORE_UM_USER = "dataworkcloud_rpc_user" - private[linkis] val ALLOW_ACCESS_WITHOUT_TIMEOUT = "dataworkcloud_inner_request" - def getLoginUserThrowsExceptionWhenTimeout(req: HttpServletRequest): Option[String] = Option(req.getCookies).flatMap(cs => SSOUtils.getLoginUser(cs)) - .orElse(SSOUtils.getLoginUserIgnoreTimeout(key => Option(req.getHeader(key))).filter(_ == OTHER_SYSTEM_IGNORE_UM_USER)) - def getLoginUser(req: HttpServletRequest): Option[String] = Utils.tryCatch(getLoginUserThrowsExceptionWhenTimeout(req)) { - case _: LoginExpireException => - SSOUtils.getLoginUserIgnoreTimeout(key => Option(req.getCookies).flatMap(_.find(_.getName == key).map(_.getValue))).filter(user => user != OTHER_SYSTEM_IGNORE_UM_USER && - isRequestIgnoreTimeout(req)) - case t => throw t - } - def isRequestIgnoreTimeout(req: HttpServletRequest): Boolean = Option(req.getCookies).exists(_.exists(c => c.getName == ALLOW_ACCESS_WITHOUT_TIMEOUT && c.getValue == "true")) - def addIgnoreTimeoutSignal(response: HttpServletResponse): Unit = response.addCookie(ignoreTimeoutSignal()) - def ignoreTimeoutSignal(): Cookie = { - val cookie = new Cookie(ALLOW_ACCESS_WITHOUT_TIMEOUT, "true") - cookie.setMaxAge(-1) - cookie.setPath("/") - if(sslEnable) cookie.setSecure(true) - cookie - } - def removeIgnoreTimeoutSignal(response: HttpServletResponse): Unit = { - val cookie = new Cookie(ALLOW_ACCESS_WITHOUT_TIMEOUT, "false") - cookie.setMaxAge(0) - cookie.setPath("/") - if(sslEnable) cookie.setSecure(true) - response.addCookie(cookie) - } - def getLoginUsername(req: HttpServletRequest): String = getLoginUser(req).getOrElse(throw new IllegalUserTicketException( s"Illegal user token information(非法的用户token信息).")) - def setLoginUser(resp: HttpServletResponse, username: String): Unit = SSOUtils.setLoginUser(c => resp.addCookie(c), username) - def removeLoginUser(req: HttpServletRequest, resp: HttpServletResponse): Unit = { - SSOUtils.removeLoginUser(req.getCookies) - SSOUtils.removeLoginUserByAddCookie(s => resp.addCookie(s)) - } -} \ No newline at end of file diff --git a/core/cloudMybatis/pom.xml b/core/cloudMybatis/pom.xml deleted file mode 100644 index c4dade413b..0000000000 --- a/core/cloudMybatis/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - jar - - linkis-mybatis - - - - com.webank.wedatasphere.linkis - linkis-module - provided - - - org.mybatis.spring.boot - mybatis-spring-boot-starter - 1.3.2 - - - spring-boot-starter - org.springframework.boot - - - spring-boot-autoconfigure - org.springframework.boot - - - spring-beans - org.springframework - - - - - com.github.pagehelper - pagehelper - 5.1.4 - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/core/cloudProtocol/pom.xml b/core/cloudProtocol/pom.xml deleted file mode 100644 index 95b8587870..0000000000 --- a/core/cloudProtocol/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-protocol - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java deleted file mode 100644 index f0c719e689..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -public class CacheNotFound implements ResponseReadCache { -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java deleted file mode 100644 index 7f36f7d3b5..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -public class CacheTaskResult implements ResponseReadCache { - - private String resultLocation; - - public CacheTaskResult(String resultLocation) { - this.resultLocation = resultLocation; - } - - public String getResultLocation() { - return resultLocation; - } -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java deleted file mode 100644 index 41cdca6ec2..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -public class FailedToDeleteCache { - private String errorMessage; - - public FailedToDeleteCache(String errorMessage) { - this.errorMessage = errorMessage; - } - - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java deleted file mode 100644 index 317eed73ce..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; - -public class RequestDeleteCache implements QueryProtocol { - - private String executionCode; - private String engineType; - private String user; - - public RequestDeleteCache(String executionCode, String engineType, String user) { - this.executionCode = executionCode; - this.engineType = engineType; - this.user = user; - } - - public String getExecutionCode() { - return executionCode; - } - - public String getEngineType() { - return engineType; - } - - public String getUser() { - return user; - } -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java deleted file mode 100644 index 49ed99e2e2..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; - -public class RequestReadCache implements QueryProtocol { - private String executionCode; - private String engineType; - private String user; - private Long readCacheBefore; - - public RequestReadCache(String executionCode, String engineType, String user, Long readCacheBefore) { - this.executionCode = executionCode; - this.engineType = engineType; - this.user = user; - this.readCacheBefore = readCacheBefore; - } - - public String getExecutionCode() { - return executionCode; - } - - public String getEngineType() { - return engineType; - } - - public String getUser() { - return user; - } - - public Long getReadCacheBefore() { - return readCacheBefore; - } -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java deleted file mode 100644 index e9c0e3a9e3..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; - -public interface ResponseDeleteCache extends QueryProtocol { -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java deleted file mode 100644 index dbcc84a50e..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; - -public interface ResponseReadCache extends QueryProtocol { -} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java b/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java deleted file mode 100644 index b16098faad..0000000000 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.webank.wedatasphere.linkis.protocol.query.cache; - -public class SuccessDeletedCache { -} diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/RequestQueryGlobalConfig.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/RequestQueryGlobalConfig.scala deleted file mode 100644 index 18592fdfdf..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/RequestQueryGlobalConfig.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.config - -import com.webank.wedatasphere.linkis.protocol.{CacheableProtocol, RetryableProtocol} - -/** - * Created by enjoyyin on 2018/10/16. - */ -trait ConfigProtocol - -case class RequestQueryGlobalConfig(userName:String) extends CacheableProtocol with RetryableProtocol with ConfigProtocol - -case class RequestQueryAppConfig(userName:String,creator:String,appName:String) extends CacheableProtocol with RetryableProtocol with ConfigProtocol - -case class RequestQueryAppConfigWithGlobal(userName:String,creator:String,appName:String,isMerge:Boolean) extends CacheableProtocol with RetryableProtocol with ConfigProtocol diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala deleted file mode 100644 index e3aeb3e353..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.engine - -import com.webank.wedatasphere.linkis.protocol.RetryableProtocol - -/** - * - * Request status information from an engine(向某一个engine请求状态信息) - * Created by enjoyyin on 2018/9/27. - */ -case class RequestEngineStatus(messageType: Int) extends RetryableProtocol -object RequestEngineStatus { - val Status_Only = 1 - val Status_Overload = 2 - val Status_Concurrent = 3 - val Status_Overload_Concurrent = 4 - val Status_BasicInfo = 5 - val ALL = 6 -} \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestNewEngine.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestNewEngine.scala deleted file mode 100644 index d8f354c2ed..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestNewEngine.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.engine - -import java.util - -import com.webank.wedatasphere.linkis.protocol.RetryableProtocol - -/** - * Created by enjoyyin on 2018/9/18. - */ -trait RequestEngine extends RetryableProtocol { - val creator: String - val user: String - val properties: util.Map[String, String] //Other parameter information(其他参数信息) -} -object RequestEngine { - private val header = "_req_" - val REQUEST_ENTRANCE_INSTANCE = header + "entrance_instance" -// val ENGINE_MAX_FREE_TIME = header + "engine_max_free_time" -// val ENGINE_MAX_EXECUTE_NUM = header + "engine_max_execute_num" - // val ENGINE_USER = header + "engine_user" - val ENGINE_INIT_SPECIAL_CODE = header + "engine_init_code" - def isRequestEngineProperties(key: String) = key.startsWith(header) -} -trait TimeoutRequestEngine { - val timeout: Long -} -case class RequestNewEngine(creator: String, user: String, properties: util.Map[String, String]) extends RequestEngine -case class TimeoutRequestNewEngine(timeout: Long, user: String, creator: String, properties: util.Map[String, String]) extends RequestEngine with TimeoutRequestEngine -case class RequestKillEngine(instance: String, killApplicationName: String, killInstance: String) \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestTask.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestTask.scala deleted file mode 100644 index 6411d6ac3b..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestTask.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.engine - -import java.util - -import com.webank.wedatasphere.linkis.protocol.RetryableProtocol - -/** - * Created by enjoyyin on 2018/9/14. - */ -trait RequestTask { - def getCode: String - def setCode(code: String): Unit - def getLock: String - def setLock(lock: String): Unit - def getProperties: util.Map[String, Object] - def setProperties(properties: util.Map[String, Object]) - def data(key: String, value: Object): Unit -} -object RequestTask { - private val header = "#rt_" - val RESULT_SET_STORE_PATH = header + "rs_store_path" -} -class RequestTaskExecute extends RequestTask { - private var code: String = _ - private var lock: String = _ - private var properties: util.Map[String, Object] = new util.HashMap[String, Object] - override def getCode: String = code - - override def setCode(code: String): Unit = this.code = code - - override def getLock: String = lock - - override def setLock(lock: String): Unit = this.lock = lock - - override def getProperties: util.Map[String, Object] = properties - - override def setProperties(properties: util.Map[String, Object]): Unit = this.properties = properties - - override def data(key: String, value: Object): Unit = { - if(properties == null) properties = new util.HashMap[String, Object] - properties.put(key, value) - } -} -case class RequestTaskPause(execId: String) -case class RequestTaskResume(execId: String) -case class RequestTaskKill(execId: String) -//Instance pass the corresponding instance information, used to print the log, to facilitate troubleshooting -//instance传递对应的实例信息,用于打印日志,方便排查问题 -case class RequestEngineLock(instance: String, timeout: Long) -case class RequestEngineUnlock(instance: String, lock: String) - -/** - * The status of requesting job execution, mainly used for: - * 1. If the engine has not sent information to the entity for a long time, the enumeration periodically requests status information - * 2. If the entance of the request engine is hanged, the newly taken entity first requests the status of the job from the engine, the engine maintains the new sender information, - * and then sends log information to the sender. - * 请求Job执行的状态,主要用于: - * 1. 如果engine很久没有给entrance发送信息,entrance定时请求一次状态信息 - * 2. 如果请求engine的entrance挂掉了,新接手的entrance第一次向engine请求Job的状态,engine维系新的sender信息,后续向该sender发送日志信息 - */ -case class RequestTaskStatus(execId: String) \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseNewEngine.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseNewEngine.scala deleted file mode 100644 index 167f50c53c..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseNewEngine.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.engine - -import com.webank.wedatasphere.linkis.protocol.{BroadcastProtocol, RetryableProtocol} - -/** - * Created by enjoyyin on 2018/9/18. - */ -trait ResponseEngine extends RetryableProtocol { - val port: Int - val status: Int - val initErrorMsg: String -} - -/** - * engine send to engineManager - * @param pid - */ -case class ResponseEnginePid(port: Int, pid: String) extends RetryableProtocol -/** - * engine send to engineManager - * @param host - */ -case class ResponseEngineHost(port: Int, host: String) extends RetryableProtocol -/** - * engine send to engineManager - * @param port - * @param status - * @param initErrorMsg - */ -case class ResponseEngineStatusCallback(override val port: Int, - override val status: Int, - override val initErrorMsg: String) extends ResponseEngine - -/** - * engineManager send to entrance - * @param instance - * @param responseEngineStatus - */ - case class ResponseNewEngineStatus(instance: String, responseEngineStatus: ResponseEngineStatusCallback) extends RetryableProtocol - -/** - * engineManager send to entrance - * @param applicationName - * @param instance - */ -case class ResponseNewEngine(applicationName: String, instance: String) extends RetryableProtocol - -case class BroadcastNewEngine(responseNewEngine: ResponseNewEngine, responseEngineStatus: ResponseEngineStatus) - extends BroadcastProtocol \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseTaskExecute.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseTaskExecute.scala deleted file mode 100644 index 66d7d97b07..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/ResponseTaskExecute.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.engine - -import java.util - -import com.webank.wedatasphere.linkis.protocol.{BroadcastProtocol, IRServiceGroupProtocol, RetryableProtocol, UserWithCreator} - -/** - * Created by enjoyyin on 2018/9/14. - */ -case class ResponseTaskExecute(execId: String) -case class JobProgressInfo(id: String, totalTasks: Int, runningTasks: Int, failedTasks: Int, succeedTasks: Int) -case class ResponseTaskProgress(execId: String, progress: Float, progressInfo: Array[JobProgressInfo])( - implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol with IRServiceGroupProtocol -case class ResponseEngineLock(lock: String) -case class EngineConcurrentInfo(runningTasks: Int, pendingTasks: Int, succeedTasks: Int, failedTasks: Int) -case class EngineOverloadInfo(maxMemory: Long, usedMemory: Long, systemCPUUsed: Float) -case class ResponseEngineStatusChanged(instance: String, fromState: Int, toState: Int, - overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo) - extends BroadcastProtocol -case class ResponseEngineInfo(createEntranceInstance: String, creator: String, user: String, properties: util.Map[String, String]) -case class ResponseEngineStatus(instance: String, state: Int, overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo, - engineInfo: ResponseEngineInfo) -case class ResponseTaskLog(execId: String, log: String)( - implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol with IRServiceGroupProtocol - -case class ResponseTaskError(execId: String, errorMsg: String)( - implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol with IRServiceGroupProtocol - -case class ResponseTaskStatus(execId: String, state: Int)( - implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol with IRServiceGroupProtocol - -case class ResponseTaskResultSet(execId: String, output: String, alias: String)( - implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol with IRServiceGroupProtocol - -case class ResponseTaskResultSize(execId: String, resultSize: Int)(implicit override val userWithCreator: UserWithCreator) extends RetryableProtocol - with IRServiceGroupProtocol \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala b/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala deleted file mode 100644 index 7e333c1c63..0000000000 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.protocol.utils - -import javafx.beans.binding.LongExpression - -/** - * created by enjoyyin on 2018/11/8 - * Description: - */ -object ZuulEntranceUtils { - - - - def parseExecID(longExecID:String):Array[String] = { - //Add creator to execID while old code is compatible(添加creator到execID,同时老代码兼容) - if(isNumberic(longExecID.substring(0, 6))){ - val creatorLength = Integer.parseInt(longExecID.substring(0,2)) - val executeLength = Integer.parseInt(longExecID.substring(2,4)) - val instanceLength = Integer.parseInt(longExecID.substring(4,6)) - val creator = longExecID.substring(6, 6 + creatorLength) - val executeApplicationName = longExecID.substring(6 + creatorLength, 6 + creatorLength + executeLength) - val instance = longExecID.substring(6 + creatorLength + executeLength, 6 + creatorLength + executeLength + instanceLength) - val shortExecID = longExecID.substring(6 + creatorLength + executeLength + instanceLength, longExecID.length) - return Array(creator, executeApplicationName, instance, shortExecID) - } - val executeLength = Integer.parseInt(longExecID.substring(0,2)) - val instanceLength = Integer.parseInt(longExecID.substring(2,4)) - val executeApplicationName:String = longExecID.substring(4, 4 + executeLength) - val instance:String = longExecID.substring(4 + executeLength, 4 + executeLength + instanceLength) - val shortExecID:String = longExecID.substring(4 + executeLength + instanceLength, longExecID.length) - Array[String](executeApplicationName, instance, shortExecID) - } - - - private def isNumberic(s:String):Boolean = { - s.toCharArray foreach { - c => if (c < 48 || c >57) return false - } - true - } - - /** - * - * @param shortExecID ExecID generated by the scheduler, such as IDE_neiljianliu_0(scheduler生成的ExecID, 如 IDE_neiljianliu_0) - * @param executeApplicationName {dd}{dd}${executeApplicationName}${instance}${shortExecID} - * @return - */ - @Deprecated - def generateExecID(shortExecID:String, executeApplicationName:String, instance:String):String = { - val executeLength = getLengthStr(executeApplicationName) - val instanceLength = getLengthStr(instance) - if (shortExecID.split("_").length == 3){ - //Backward compatible(向下兼容) - val creator = shortExecID.split("_")(0) - val creatorLength = getLengthStr(creator) - return creatorLength + executeLength + instanceLength + creator + executeApplicationName + instance + shortExecID - } - executeLength + instanceLength + executeApplicationName + instance + shortExecID - } - - - def generateExecID(shortExecID:String, executeApplicationName:String, instance:String, creator:String):String = { - val creatorLength = getLengthStr(creator) - val executeLength = getLengthStr(executeApplicationName) - val instanceLength = getLengthStr(instance) - creatorLength + executeLength + instanceLength + creator + executeApplicationName + instance + shortExecID - } - - - - - private def getLengthStr(string:String):String = { - val length = string.length - if (length >= 10) String.valueOf(length) else "0" + String.valueOf(length) - } - - def main(args: Array[String]): Unit = { - - } - -} diff --git a/core/cloudRPC/pom.xml b/core/cloudRPC/pom.xml deleted file mode 100644 index 8a9a9c3d72..0000000000 --- a/core/cloudRPC/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-cloudRPC - - - - com.webank.wedatasphere.linkis - linkis-protocol - - - com.webank.wedatasphere.linkis - linkis-module - - - org.springframework.cloud - spring-cloud-starter-feign - ${spring.eureka.version} - - - netty-codec - io.netty - - - netty-transport - io.netty - - - jersey-client - com.sun.jersey - - - jersey-apache-client4 - com.sun.jersey.contribs - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - jackson-annotations - com.fasterxml.jackson.core - - - httpclient - org.apache.httpcomponents - - - spring-cloud-commons - org.springframework.cloud - - - HdrHistogram - org.hdrhistogram - - - jsr305 - com.google.code.findbugs - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - - - org.json4s - json4s-jackson_${scala.binary.version} - 3.5.3 - - - jackson-databind - com.fasterxml.jackson.core - - - - - org.springframework.cloud - spring-cloud-starter-openfeign - 2.0.0.RELEASE - - - jackson-databind - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - jackson-annotations - com.fasterxml.jackson.core - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/core/common/pom.xml b/core/common/pom.xml deleted file mode 100644 index f44e1562e1..0000000000 --- a/core/common/pom.xml +++ /dev/null @@ -1,204 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-common - jar - - - - - - org.scala-lang - scala-library - - - org.scala-lang - scala-compiler - - - org.scala-lang - scala-reflect - - - org.scala-lang - scalap - - - commons-lang - commons-lang - - - commons-io - commons-io - 2.4 - - - commons-collections - commons-collections - - - com.google.guava - guava - - - - com.fasterxml.jackson.core - jackson-databind - ${fasterxml.jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${fasterxml.jackson.version} - - - com.fasterxml.jackson.module - jackson-module-scala_${scala.binary.version} - ${fasterxml.jackson.version} - - - com.google.guava - guava - - - org.scala-lang - scala-library - - - org.scala-lang - scala-reflect - - - paranamer - com.thoughtworks.paranamer - - - - - - com.fasterxml.jackson.module - jackson-module-parameter-names - ${fasterxml.jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${fasterxml.jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - ${fasterxml.jackson.version} - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - commons-net - commons-net - 3.1 - - - - commons-codec - commons-codec - 1.10 - - - com.google.code.gson - gson - - - org.json4s - json4s-jackson_2.11 - - - - - org.json4s - json4s-core_${scala.binary.version} - 3.2.11 - - - org.json4s - json4s-jackson_${scala.binary.version} - 3.2.11 - - - jackson-databind - com.fasterxml.jackson.core - - - - - org.json4s - json4s-ast_2.11 - 3.2.11 - - - org.apache.httpcomponents - httpclient - 4.5.4 - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/resources - - - ${project.artifactId}-${project.version} - - - - \ No newline at end of file diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/TestMain.java b/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/TestMain.java deleted file mode 100644 index abd1f65017..0000000000 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/TestMain.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.common.io; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.net.*; - -/** - * Created by enjoyyin on 2018/10/24. - */ -public class TestMain { - public static void main(String[] args) throws FileNotFoundException, URISyntaxException, MalformedURLException, UnknownHostException { - FsPath fsPath = new FsPath("hdfs:///test"); - System.out.print(fsPath.getPath()); - } -} diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala b/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala deleted file mode 100644 index 41c10f7536..0000000000 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.common.conf - -import java.io._ -import java.util.Properties -import com.webank.wedatasphere.linkis.common.utils.Logging -import org.apache.commons.io.IOUtils -import org.apache.commons.lang.StringUtils -import scala.collection.JavaConversions._ - -/** - * Created by enjoyyin on 2018/1/9. - */ -private[conf] object BDPConfiguration extends Logging { - - val DEFAULT_PROPERTY_FILE_NAME = "linkis.properties" - val CHARSET_NAME = "utf-8" - - private val config = new Properties - private val sysProps = sys.props - private val extractConfig = new Properties - - private val env = sys.env - - val propertyFile = sysProps.getOrElse("wds.linkis.configuration", DEFAULT_PROPERTY_FILE_NAME) - private val configFileURL = getClass.getClassLoader.getResource(propertyFile) - if (configFileURL != null && new File(configFileURL.getPath).exists) initConfig(config, configFileURL.getPath) - else warn(s"******************************** Notice: The dataworkcloud configuration file $propertyFile is not exists! ***************************") - - private def initConfig(config: Properties, filePath: String) { - var inputStream: InputStream = null - var inputStreamReader: InputStreamReader = null - try { - inputStream = new FileInputStream(filePath) - inputStreamReader = new InputStreamReader(inputStream, CHARSET_NAME) - config.load(inputStreamReader) - } catch { case e: IOException => - error("Can't load " + propertyFile, e) - } finally { - IOUtils.closeQuietly(inputStream) - IOUtils.closeQuietly(inputStreamReader) - } - } - - def getOption(key: String): Option[String] = { - if(extractConfig.containsKey(key)) - return Some(extractConfig.getProperty(key)) - val value = config.getProperty(key) - if(StringUtils.isNotEmpty(value)) { - return Some(value) - } - val propsValue = sysProps.get(key).orElse(sys.props.get(key)) - if(propsValue.isDefined){ - return propsValue - } - env.get(key) - } - - def properties = { - val props = new Properties - props.putAll(sysProps) - props.putAll(config) - props.putAll(extractConfig) - props.putAll(env) - props - } - - def getOption[T](commonVars: CommonVars[T]): Option[T] = if(commonVars.value != null) Option(commonVars.value) - else { - val value = BDPConfiguration.getOption(commonVars.key) - if (value.isEmpty) Option(commonVars.defaultValue) - else formatValue(commonVars.defaultValue, value) - } - - private[common] def formatValue[T](defaultValue: T, value: Option[String]): Option[T] = { - if(value.isEmpty || value.exists(StringUtils.isEmpty)) return Option(defaultValue) - val formattedValue = defaultValue match { - case _: String => value - case _: Byte => value.map(_.toByte) - case _: Short => value.map(_.toShort) - case _: Char => value.map(_.toCharArray.apply(0)) - case _: Int => value.map(_.toInt) - case _: Long => value.map(_.toLong) - case _: Float => value.map(_.toFloat) - case _: Double => value.map(_.toDouble) - case _: Boolean => value.map(_.toBoolean) - case _: TimeType => value.map(new TimeType(_)) - case _: ByteType => value.map(new ByteType(_)) - case null => value - } - formattedValue.asInstanceOf[Option[T]] - } - - def set(key: String, value: String) = extractConfig.setProperty(key, value) - - def setIfNotExists(key: String, value: String) = if(!config.containsKey(key)) set(key, value) - - def getBoolean(key: String, default: Boolean):Boolean = getOption(key).map(_.toBoolean).getOrElse(default) - def getBoolean(commonVars: CommonVars[Boolean]): Option[Boolean] = getOption(commonVars) - - def get(key: String, default: String): String = getOption(key).getOrElse(default) - def get(commonVars: CommonVars[String]): Option[String] = getOption(commonVars) - - def get(key: String): String = getOption(key).getOrElse(throw new NoSuchElementException(key)) - - def getInt(key: String, default: Int):Int = getOption(key).map(_.toInt).getOrElse(default) - def getInt(commonVars: CommonVars[Int]): Option[Int] = getOption(commonVars) - - def contains(key: String): Boolean = getOption(key).isDefined - -} diff --git a/core/hadoop-common/pom.xml b/core/hadoop-common/pom.xml deleted file mode 100644 index 62a0c87e45..0000000000 --- a/core/hadoop-common/pom.xml +++ /dev/null @@ -1,243 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-hadoop-common - jar - - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - - org.apache.hadoop - hadoop-common - ${hadoop.version} - - - log4j - log4j - - - org.mortbay.jetty - jetty - - - org.mortbay.jetty - jetty-util - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - com.sun.jersey - jersey-json - - - jsr311-api - javax.ws.rs - - - net.java.dev.jets3t - jets3t - - - com.jcraft - jsch - - - com.google.code.findbugs - jsr305 - - - xmlenc - xmlenc - - - net.java.dev.jets3t - jets3t - - - org.apache.avro - avro - - - org.apache.hadoop - hadoop-auth - - - com.jcraft - jsch - - - com.google.code.findbugs - jsr305 - - - servlet-api - javax.servlet - - - org.slf4j - slf4j-log4j12 - - - com.sun.jersey - * - - - org.codehaus.jackson - * - - - commons-codec - commons-codec - - - commons-logging - commons-logging - - - netty - io.netty - - - curator-client - org.apache.curator - - - - - org.apache.hadoop - hadoop-hdfs - ${hadoop.version} - - - io.netty - netty - - - servlet-api - javax.servlet - - - com.google.guava - guava - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - org.slf4j - slf4j-log4j12 - - - com.sun.jersey - * - - - org.codehaus.jackson - * - - - commons-logging - commons-logging - - - netty - io.netty - - - commons-codec - commons-codec - - - - - org.apache.hadoop - hadoop-auth - ${hadoop.version} - - - org.slf4j - slf4j-log4j12 - - - org.apache.httpcomponents - httpclient - - - org.apache.httpcomponents - * - - - commons-codec - commons-codec - - - zookeeper - org.apache.zookeeper - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/core/httpclient/pom.xml b/core/httpclient/pom.xml deleted file mode 100644 index 12765893cf..0000000000 --- a/core/httpclient/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - linkis-httpclient - - - - com.webank.wedatasphere.linkis - linkis-common - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - org.apache.httpcomponents - httpmime - ${httpmime.version} - - - - org.json4s - json4s-jackson_${scala.binary.version} - ${json4s.version} - - - org.scala-lang - scala-library - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-core - - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala b/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala deleted file mode 100644 index e610b6379f..0000000000 --- a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright 2019 WeBank - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.httpclient - -import java.util -import java.util.concurrent.TimeUnit - -import com.webank.wedatasphere.linkis.common.conf.Configuration -import com.webank.wedatasphere.linkis.common.io.{Fs, FsPath} -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.httpclient.authentication.{AbstractAuthenticationStrategy, AuthenticationAction, HttpAuthentication} -import com.webank.wedatasphere.linkis.httpclient.config.ClientConfig -import com.webank.wedatasphere.linkis.httpclient.discovery.{AbstractDiscovery, Discovery, HeartbeatAction} -import com.webank.wedatasphere.linkis.httpclient.exception.{HttpClientResultException, HttpMessageParseException} -import com.webank.wedatasphere.linkis.httpclient.loadbalancer.{AbstractLoadBalancer, DefaultLoadbalancerStrategy, LoadBalancer} -import com.webank.wedatasphere.linkis.httpclient.request._ -import com.webank.wedatasphere.linkis.httpclient.response._ -import org.apache.commons.io.IOUtils -import org.apache.commons.lang.StringUtils -import org.apache.http.client.entity.UrlEncodedFormEntity -import org.apache.http.client.methods.{CloseableHttpResponse, HttpGet, HttpPost} -import org.apache.http.client.utils.URIBuilder -import org.apache.http.entity.mime.MultipartEntityBuilder -import org.apache.http.entity.{ContentType, StringEntity} -import org.apache.http.impl.client.HttpClients -import org.apache.http.message.BasicNameValuePair -import org.apache.http.util.EntityUtils -import org.apache.http.{HttpException, HttpResponse, _} -import org.json4s.jackson.Serialization.read -import org.json4s.{DefaultFormats, Formats} - -import scala.collection.Iterable -import scala.collection.JavaConversions._ -import scala.concurrent.duration.Duration -import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService} - - -/** - * Created by enjoyyin on 2019/5/20. - */ -abstract class AbstractHttpClient(clientConfig: ClientConfig, clientName: String) extends Client { - - protected implicit val formats: Formats = DefaultFormats - protected implicit val executors: ExecutionContext = Utils.newCachedExecutionContext(clientConfig.getMaxConnection, clientName, false) - protected val httpTimeout: Duration = if (clientConfig.getReadTimeout > 0) Duration(clientConfig.getReadTimeout, TimeUnit.MILLISECONDS) - else Duration.Inf - - protected val httpClient = HttpClients.createDefault() - - if (clientConfig.getAuthenticationStrategy != null) clientConfig.getAuthenticationStrategy match { - case auth: AbstractAuthenticationStrategy => auth.setClient(this) - case _ => - } - protected val (discovery, loadBalancer): (Option[Discovery], Option[LoadBalancer]) = - if (this.clientConfig.isDiscoveryEnabled) { - val discovery = Some(createDiscovery()) - discovery.foreach { - case d: AbstractDiscovery => - d.setServerUrl(clientConfig.getServerUrl) - d.setClient(this) - d.setSchedule(clientConfig.getDiscoveryPeriod, clientConfig.getDiscoveryTimeUnit) - case d => d.setServerUrl(clientConfig.getServerUrl) - } - //如果discovery没有启用,那么启用loadBalancer是没有意义的 - val loadBalancer = if (clientConfig.isLoadbalancerEnabled && this.clientConfig.getLoadbalancerStrategy != null) - Some(this.clientConfig.getLoadbalancerStrategy.createLoadBalancer()) - else if (clientConfig.isLoadbalancerEnabled) Some(DefaultLoadbalancerStrategy.createLoadBalancer()) - else None - loadBalancer match { - case Some(lb: AbstractLoadBalancer) => - discovery.foreach(_.addDiscoveryListener(lb)) - case _ => - } - (discovery, loadBalancer) - } else (None, None) - - discovery.foreach(_.start()) - - protected def createDiscovery(): Discovery - - override def execute(requestAction: Action): Result = execute(requestAction, -1) - - override def execute(requestAction: Action, waitTime: Long): Result = { - if(!requestAction.isInstanceOf[HttpAction]) - throw new UnsupportedOperationException("only HttpAction supported, but the fact is " + requestAction.getClass) - val action = prepareAction(requestAction.asInstanceOf[HttpAction]) - val response: CloseableHttpResponse = executeHttpAction(action) - responseToResult(response, action) - } - - override def execute(requestAction: Action, resultListener: ResultListener): Unit = { - if (!requestAction.isInstanceOf[HttpAction]) { - throw new UnsupportedOperationException("only HttpAction supported, but the fact is " + requestAction.getClass) - } - val action = prepareAction(requestAction.asInstanceOf[HttpAction]) - val response: CloseableHttpResponse = executeHttpAction(action) - //response.onSuccess{case r => resultListener.onSuccess(responseToResult(r, action))} - //response.onFailure{case t => resultListener.onFailure(t)} - } - - protected def getRequestUrl(suffixUrl: String, requestBody: String): String = { - val urlPrefix = loadBalancer.map(_.chooseServerUrl(requestBody)).getOrElse(clientConfig.getServerUrl) - connectUrl(urlPrefix, suffixUrl) - } - - protected def connectUrl(prefix: String, suffix: String): String = { - val prefixEnd = prefix.endsWith("/") - val suffixStart = suffix.startsWith("/") - if(prefixEnd && suffixStart) prefix.substring(0, prefix.length - 1) + suffix - else if(!prefixEnd && !suffixStart) prefix + "/" + suffix - else prefix + suffix - } - - protected def prepareAction(requestAction: HttpAction): HttpAction = requestAction - - protected def executeHttpAction(requestAction: HttpAction): CloseableHttpResponse = { - var realURL = "" - requestAction match { - case serverUrlAction: ServerUrlAction => - realURL = connectUrl(serverUrlAction.serverUrl, requestAction.getURL) - case _ => - realURL = getRequestUrl(requestAction.getURL, requestAction.getRequestBody) - } - - if (clientConfig.getAuthenticationStrategy != null) clientConfig.getAuthenticationStrategy.login(requestAction, realURL.replaceAll(requestAction.getURL, "")) match { - case authAction: HttpAuthentication => - val cookies = authAction.authToCookies - if (cookies != null && cookies.nonEmpty) cookies.foreach(requestAction.addCookie) - val headers = authAction.authToHeaders - if (headers != null && !headers.isEmpty()) { - headers.foreach { case (k, v) => requestAction.addHeader(k.toString(), v.toString()) } - } - case _ => - } - - var response: CloseableHttpResponse = null - requestAction match { - case upload: UploadAction => - val httpPost = new HttpPost(realURL) - val builder = MultipartEntityBuilder.create() - if(upload.inputStreams != null) - upload.inputStreams.foreach { case (k, v) => - builder.addBinaryBody(k, v, ContentType.create("multipart/form-data"), k) - } - upload match { - case get: GetAction => get.getParameters. - retain((k, v) => v != null && k != null). - foreach { case (k, v) => builder.addTextBody(k.toString, v.toString) } - case _ => - } - upload match { - case get: GetAction => get.getHeaders. - retain((k, v) => v != null && k != null). - foreach { case (k, v) => httpPost.addHeader(k.toString, v.toString) } - case _ => - } - val httpEntity = builder.build() - httpPost.setEntity(httpEntity) - response = httpClient.execute(httpPost) - case post: POSTAction => - val httpPost = new HttpPost(realURL) - if (post.getParameters.nonEmpty || post.getFormParams.nonEmpty) { - val nvps = new util.ArrayList[NameValuePair] - if (post.getParameters.nonEmpty) { - post.getParameters.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } - } - if (post.getFormParams.nonEmpty) { - post.getFormParams.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } - } - httpPost.setEntity(new UrlEncodedFormEntity(nvps)) - } - - if (StringUtils.isNotBlank(post.getRequestPayload)) { - val stringEntity = new StringEntity(post.getRequestPayload, "UTF-8") - stringEntity.setContentEncoding(Configuration.BDP_ENCODING.getValue) - stringEntity.setContentType("application/json") - httpPost.setEntity(stringEntity) - } - - if (requestAction.getHeaders.nonEmpty) { - requestAction.getHeaders.foreach { case (k, v) => httpPost.addHeader(k.toString(), v.toString()) } - } - response = httpClient.execute(httpPost) - case get: GetAction => - val builder = new URIBuilder(realURL) - if (!get.getParameters.isEmpty) { - get.getParameters.foreach { case (k, v) => builder.addParameter(k.toString(), v.toString()) } - } - val httpGet = new HttpGet(builder.build()) - if (requestAction.getHeaders.nonEmpty) { - requestAction.getHeaders.foreach { case (k, v) => httpGet.addHeader(k.toString(), v.toString()) } - } - response = httpClient.execute(httpGet); - case _ => - val httpost = new HttpPost(realURL) - val stringEntity = new StringEntity(requestAction.getRequestBody, "UTF-8") - stringEntity.setContentEncoding(Configuration.BDP_ENCODING.getValue) - stringEntity.setContentType("application/json") - httpost.setEntity(stringEntity) - if (requestAction.getHeaders.nonEmpty) { - requestAction.getHeaders.foreach { case (k, v) => httpost.addHeader(k.toString(), v.toString()) } - } - response = httpClient.execute(httpost) - } - response - } - - protected def getFsByUser(user: String, path: FsPath): Fs - - protected def responseToResult(response: HttpResponse, requestAction: Action): Result = { - var entity = response.getEntity - val result = requestAction match { - case download: DownloadAction => - val statusCode = response.getStatusLine.getStatusCode - if (statusCode != 200) { - var responseBody: String = null - if (entity != null) { - responseBody = EntityUtils.toString(entity, "UTF-8") - } - throw new HttpClientResultException(s"request failed! ResponseBody is $responseBody.") - } - download.write(entity.getContent) - Result() - case heartbeat: HeartbeatAction => - discovery.map { - case d: AbstractDiscovery => d.getHeartbeatResult(response, heartbeat) - }.getOrElse(throw new HttpMessageParseException("Discovery is not enable, HeartbeatAction is not needed!")) - case auth: AuthenticationAction => - clientConfig.getAuthenticationStrategy match { - case a: AbstractAuthenticationStrategy => a.getAuthenticationResult(response, auth) - case _ => throw new HttpMessageParseException("AuthenticationStrategy is not enable, login is not needed!") - } - case httpAction: HttpAction => - var responseBody: String = null - if (entity != null) { - responseBody = EntityUtils.toString(entity, "UTF-8") - } - httpResponseToResult(response, httpAction, responseBody) - .getOrElse(throw new HttpMessageParseException("cannot parse message: " + responseBody)) - } - result match { - case userAction: UserAction => requestAction match { - case _userAction: UserAction => userAction.setUser(_userAction.getUser) - case _ => - } - case _ => - } - result - } - - protected def httpResponseToResult(response: HttpResponse, requestAction: HttpAction, responseBody: String): Option[Result] - - protected def deserializeResponseBody(response: HttpResponse): Iterable[_] = { - var entity = response.getEntity - var responseBody: String = null - if (entity != null) { - responseBody = EntityUtils.toString(entity, "UTF-8") - } - if (responseBody.startsWith("{") && responseBody.endsWith("}")) - read[Map[String, Object]](responseBody) - else if (responseBody.startsWith("[") && responseBody.endsWith("}")) - read[List[Map[String, Object]]](responseBody) - else if (StringUtils.isEmpty(responseBody)) Map.empty[String, Object] - else if (responseBody.length > 200) throw new HttpException(responseBody.substring(0, 200)) - else throw new HttpException(responseBody) - } - - override def close(): Unit = { - discovery.foreach { - case d: AbstractDiscovery => IOUtils.closeQuietly(d) - case _ => - } - httpClient.close() - executors.asInstanceOf[ExecutionContextExecutorService].shutdown() - } -} \ No newline at end of file diff --git a/core/scheduler/pom.xml b/core/scheduler/pom.xml deleted file mode 100644 index 8caf8941a7..0000000000 --- a/core/scheduler/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - 4.0.0 - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - linkis-scheduler - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - com.webank.wedatasphere.linkis - linkis-protocol - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - - - product - - 0.0.5 - - - - \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala b/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala deleted file mode 100644 index 34c7c71a24..0000000000 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.scheduler.executer - -/** - * Created by enjoyyin on 2018/8/31. - */ -trait ExecuteResponse -trait CompletedExecuteResponse extends ExecuteResponse -case class SuccessExecuteResponse() extends CompletedExecuteResponse -trait OutputExecuteResponse extends ExecuteResponse { - def getOutput: String -} -case class AliasOutputExecuteResponse(alias: String, output: String) extends OutputExecuteResponse { - override def getOutput: String = output -} -case class ErrorExecuteResponse(message: String, t: Throwable) extends CompletedExecuteResponse -case class IncompleteExecuteResponse(message: String) extends ExecuteResponse -trait AsynReturnExecuteResponse extends ExecuteResponse { - def notify(rs: ExecuteResponse => Unit): Unit -} \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala b/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala deleted file mode 100644 index e33f45b4de..0000000000 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.scheduler.executer - -import java.io.Closeable - -import com.webank.wedatasphere.linkis.protocol.engine.EngineState -import com.webank.wedatasphere.linkis.protocol.engine.EngineState.EngineState - -/** - * Created by enjoyyin on 2018/8/31. - */ -trait Executor extends Closeable { - def getId: Long - def execute(executeRequest: ExecuteRequest): ExecuteResponse - def state: ExecutorState.ExecutorState - - def getExecutorInfo: ExecutorInfo -} -object ExecutorState { - type ExecutorState = EngineState - val Starting = EngineState.Starting - val Idle = EngineState.Idle - val Busy = EngineState.Busy - val ShuttingDown = EngineState.ShuttingDown - val Error = EngineState.Error - val Dead = EngineState.Dead - val Success = EngineState.Success - - def apply(x: Int): ExecutorState = EngineState(x) - def isCompleted(state: ExecutorState) = EngineState.isCompleted(state.asInstanceOf[EngineState]) - def isAvailable(state: ExecutorState) = EngineState.isAvailable(state.asInstanceOf[EngineState]) -} \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala b/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala deleted file mode 100644 index 3c4722431c..0000000000 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.scheduler.executer - -import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener -import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEvent} - -import scala.concurrent.duration.Duration - -/** - * Created by enjoyyin on 2018/9/1. - */ -abstract class ExecutorManager { - - def setExecutorListener(executorListener: ExecutorListener): Unit - - protected def createExecutor(event: SchedulerEvent): Executor - - def askExecutor(event: SchedulerEvent): Option[Executor] - - def askExecutor(event: SchedulerEvent, wait: Duration): Option[Executor] - - def getById(id: Long): Option[Executor] - - def getByGroup(groupName: String): Array[Executor] - - protected def delete(executor: Executor): Unit - - def shutdown(): Unit - -} \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala b/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala deleted file mode 100644 index db9d4bfade..0000000000 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue - -/** - * Created by enjoyyin on 2018/9/7. - */ - -import java.util.concurrent.{ExecutorService, Future} - -import com.webank.wedatasphere.linkis.common.exception.{ErrorException, WarnException} -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.scheduler.SchedulerContext -import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException -import com.webank.wedatasphere.linkis.scheduler.executer.Executor -import com.webank.wedatasphere.linkis.scheduler.future.{BDPFuture, BDPFutureTask} -import com.webank.wedatasphere.linkis.scheduler.queue._ - -import scala.collection.mutable.ArrayBuffer -import scala.concurrent.TimeoutException - -class FIFOUserConsumer(schedulerContext: SchedulerContext, - executeService: ExecutorService, private var group: Group) extends Consumer(schedulerContext, executeService) { - private var fifoGroup = group.asInstanceOf[FIFOGroup] - private var queue: ConsumeQueue = _ - private val maxRunningJobsNum = fifoGroup.getMaxRunningJobs - private val runningJobs = new Array[Job](maxRunningJobsNum) - private var future: Future[_] = _ - - def this(schedulerContext: SchedulerContext,executeService: ExecutorService) = { - this(schedulerContext,executeService, null) - } - - def start(): Unit = future = executeService.submit(this) - - override def setConsumeQueue(consumeQueue: ConsumeQueue) = { - queue = consumeQueue - } - - override def getConsumeQueue = queue - - override def getGroup = fifoGroup - - override def setGroup(group: Group) = { - this.fifoGroup = group.asInstanceOf[FIFOGroup] - } - - override def getRunningEvents = getEvents(_.isRunning) - - private def getEvents(op: SchedulerEvent => Boolean): Array[SchedulerEvent] = { - val result = ArrayBuffer[SchedulerEvent]() - runningJobs.filter(_ != null).filter(x => op(x)).foreach(result += _) - result.toArray - } - - override def run() = { - Thread.currentThread().setName(s"${toString}Thread") - info(s"$toString thread started!") - while (!terminate) { - Utils.tryAndError(loop()) - Utils.tryAndError(Thread.sleep(10)) - } - info(s"$toString thread stopped!") - } - - protected def askExecutorGap(): Unit = {} - - protected def loop(): Unit = { - val completedNums = runningJobs.filter(e => e == null || e.isCompleted) - if (completedNums.length < 1) { - Utils.tryQuietly(Thread.sleep(1000)) //TODO can also be optimized to optimize by implementing JobListener(TODO 还可以优化,通过实现JobListener进行优化) - return - } - var isRetryJob = false - var event: Option[SchedulerEvent] = None - def getWaitForRetryEvent: Option[SchedulerEvent] = { - val waitForRetryJobs = runningJobs.filter(job => job != null && job.isJobCanRetry) - waitForRetryJobs.find{job => - isRetryJob = Utils.tryCatch(job.turnToRetry()){ t => - job.onFailure("Job state flipped to Scheduled failed in Retry(Retry时,job状态翻转为Scheduled失败)!", t) - false - } - isRetryJob - } - } - while(event.isEmpty) { - val takeEvent = if(getRunningEvents.isEmpty) Option(queue.take()) else queue.take(3000) - event = if(takeEvent.exists(e => Utils.tryCatch(e.turnToScheduled()) {t => - takeEvent.get.asInstanceOf[Job].onFailure("Job state flipped to Scheduled failed(Job状态翻转为Scheduled失败)!", t) - false - })) takeEvent else getWaitForRetryEvent - } - event.foreach { case job: Job => - Utils.tryCatch { - val (totalDuration, askDuration) = (fifoGroup.getMaxAskExecutorDuration, fifoGroup.getAskExecutorInterval) - var executor: Option[Executor] = None - job.consumerFuture = new BDPFutureTask(this.future) - Utils.waitUntil(() => { - executor = Utils.tryCatch(schedulerContext.getOrCreateExecutorManager.askExecutor(job, askDuration)) { - case warn: WarnException => - job.getLogListener.foreach(_.onLogUpdate(job, warn.getDesc)) - None - case e:ErrorException => - job.getLogListener.foreach(_.onLogUpdate(job, e.getDesc)) - throw e - case error: Throwable => - throw error - } - Utils.tryQuietly(askExecutorGap()) - executor.isDefined - }, totalDuration) - job.consumerFuture = null - executor.foreach { executor => - job.setExecutor(executor) - job.future = executeService.submit(job) - job.getJobDaemon.foreach(jobDaemon => jobDaemon.future = executeService.submit(jobDaemon)) - if(!isRetryJob) putToRunningJobs(job) - } - }{ - case _: TimeoutException => - warn(s"Ask executor for Job $job timeout!") - job.onFailure("The request engine times out and the cluster cannot provide enough resources(请求引擎超时,集群不能提供足够的资源).", - new SchedulerErrorException(11055, "Insufficient resources, requesting available engine timeout(资源不足,请求可用引擎超时)!")) - case error: Throwable => - job.onFailure("Request engine failed, possibly due to insufficient resources or background process error(请求引擎失败,可能是由于资源不足或后台进程错误)!", error) - if(job.isWaitForRetry) { - warn(s"Ask executor for Job $job failed, wait for the next retry!", error) - if(!isRetryJob) putToRunningJobs(job) - } else warn(s"Ask executor for Job $job failed!", error) - } - } - } - - private def putToRunningJobs(job: Job): Unit = { - val index = runningJobs.indexWhere(f => f == null || f.isCompleted) - runningJobs(index) = job - } - - override def shutdown() = { - future.cancel(true) - super.shutdown() - } -} diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala b/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala deleted file mode 100644 index 2c61f6e9e4..0000000000 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue - -import java.util.concurrent.ExecutorService - -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.scheduler.listener.ConsumerListener -import com.webank.wedatasphere.linkis.scheduler.queue._ -import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer - -import scala.collection.mutable - -/** - * Created by enjoyyin on 2018/9/11. - */ -class ParallelConsumerManager(maxParallelismUsers: Int)extends ConsumerManager{ - - private val UJES_CONTEXT_CONSTRUCTOR_LOCK = new Object() - private var consumerListener: Option[ConsumerListener] = None - - private var executorService: ExecutorService = _ - - private val consumerGroupMap = new mutable.HashMap[String, FIFOUserConsumer]() - - override def setConsumerListener(consumerListener: ConsumerListener) = { - this.consumerListener = Some(consumerListener) - } - - override def getOrCreateExecutorService = if(executorService != null) executorService - else UJES_CONTEXT_CONSTRUCTOR_LOCK.synchronized { - if (executorService == null) { - executorService = Utils.newCachedThreadPool(5 * maxParallelismUsers + 1, "Engine-Scheduler-ThreadPool-", true) - } - executorService - } - - override def getOrCreateConsumer(groupName: String) = if(consumerGroupMap.contains(groupName)) consumerGroupMap(groupName) - else UJES_CONTEXT_CONSTRUCTOR_LOCK.synchronized { - consumerGroupMap.getOrElse(groupName, { - val newConsumer = createConsumer(groupName) - val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) - newConsumer.setGroup(group) - newConsumer.setConsumeQueue(new LoopArrayQueue(group)) - consumerGroupMap.put(groupName, newConsumer) - consumerListener.foreach(_.onConsumerCreated(newConsumer)) - newConsumer.start() - newConsumer - }) - } - - override protected def createConsumer(groupName: String) = { - val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) - new FIFOUserConsumer(getSchedulerContext, getOrCreateExecutorService, group) - } - - override def destroyConsumer(groupName: String) = - consumerGroupMap.get(groupName).foreach { tmpConsumer => - tmpConsumer.shutdown() - consumerGroupMap.remove(groupName) - consumerListener.foreach(_.onConsumerDestroyed(tmpConsumer)) - } - - override def shutdown() = { - consumerGroupMap.iterator.foreach(x => x._2.shutdown()) - } - - override def listConsumers() = consumerGroupMap.values.toArray -} diff --git a/datasource/datasourcemanager/common/pom.xml b/datasource/datasourcemanager/common/pom.xml deleted file mode 100644 index 340baeb4c1..0000000000 --- a/datasource/datasourcemanager/common/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - - linkis-datasourcemanager-common - - - - UTF-8 - 1.0.12 - - - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/resources - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/datasourcemanager/common/src/main/java/com/webank/wedatasphere/linkis/datasourcemanager/common/util/json/Json.java b/datasource/datasourcemanager/common/src/main/java/com/webank/wedatasphere/linkis/datasourcemanager/common/util/json/Json.java deleted file mode 100644 index 9becb83223..0000000000 --- a/datasource/datasourcemanager/common/src/main/java/com/webank/wedatasphere/linkis/datasourcemanager/common/util/json/Json.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2019 WeBank - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.datasourcemanager.common.util.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.*; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; - -/** - * @author kirkzhou - * Json utils - * 2018/9/3 - */ -public class Json { - private static final String PREFIX = "["; - private static final String SUFFIX = "]"; - private static final Logger logger = LoggerFactory.getLogger(Json.class); - - private static ObjectMapper mapper; - - static{ - mapper = new ObjectMapper(); - mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); - mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); - mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); - //empty beans allowed - mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - //ignore unknown properties - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - //cancel to scape non ascii - mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false); - } - private Json(){} - - @SuppressWarnings("unchecked") - public static T fromJson(String json, Class> clazz, Class>... parameters){ - if(StringUtils.isNotBlank(json)){ - try{ - if(parameters.length > 0){ - return (T)mapper.readValue(json, mapper.getTypeFactory().constructParametricType(clazz, parameters)); - } - if(json.startsWith(PREFIX) - && json.endsWith(SUFFIX)){ - JavaType javaType = mapper.getTypeFactory() - .constructParametricType(ArrayList.class, clazz); - return mapper.readValue(json, javaType); - } - return (T)mapper.readValue(json, clazz); - } catch (Exception e) { - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - } - return null; - } - - public static T fromJson(InputStream stream, Class> clazz, Class>... parameters){ - StringBuilder builder = new StringBuilder(); - String jsonStr = null; - try{ - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); - while((jsonStr = reader.readLine()) != null){ - builder.append(jsonStr); - } - reader.close(); - }catch(Exception e){ - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - return fromJson(builder.toString(), clazz, parameters); - } - - public static String toJson(Object obj, Class> model){ - ObjectWriter writer = mapper.writer(); - if(null != obj){ - try{ - if(null != model){ - writer = writer.withView(model); - } - return writer.writeValueAsString(obj); - } catch (JsonProcessingException e) { - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - } - return null; - } - -} diff --git a/datasource/datasourcemanager/server/Dockerfile b/datasource/datasourcemanager/server/Dockerfile deleted file mode 100644 index edda49ab94..0000000000 --- a/datasource/datasourcemanager/server/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-dsm-server.zip /opt/linkis -RUN unzip linkis-dsm-server.zip - -WORKDIR /opt/linkis/linkis-dsm-server/bin -ENTRYPOINT ["/opt/linkis/linkis-dsm-server/bin/startup.sh"] diff --git a/datasource/datasourcemanager/server/conf/application.yml b/datasource/datasourcemanager/server/conf/application.yml deleted file mode 100644 index 8e9cb3ae6f..0000000000 --- a/datasource/datasourcemanager/server/conf/application.yml +++ /dev/null @@ -1,30 +0,0 @@ -server: - port: 8196 -spring: - application: - name: dsm-server - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - - diff --git a/datasource/datasourcemanager/server/pom.xml b/datasource/datasourcemanager/server/pom.xml deleted file mode 100644 index efdf6ed8fc..0000000000 --- a/datasource/datasourcemanager/server/pom.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - - linkis-datasourcemanager-server - - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - hk2-api - org.glassfish.hk2 - - - jersey-common - org.glassfish.jersey.core - - - provided - - - - com.webank.wedatasphere.linkis - linkis-datasourcemanager-common - - - asm - org.ow2.asm - - - - - - org.glassfish.jersey.ext - jersey-bean-validation - ${jersey.version} - - - javax.ws.rs-api - javax.ws.rs - - - hk2-locator - org.glassfish.hk2 - - - hk2-api - org.glassfish.hk2 - - - - - - com.webank.wedatasphere.linkis - linkis-bmlclient - - - - com.webank.wedatasphere.linkis - linkis-mybatis - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - provided - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - hk2-api - org.glassfish.hk2 - 2.4.0-b34 - - - org.json4s - json4s-jackson_2.11 - ${json4s.version} - - - org.json4s - json4s-core_2.11 - ${json4s.version} - - - org.json4s - json4s-ast_2.11 - ${json4s.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-dsm-server - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/datasourcemanager/server/pom_k8s.xml b/datasource/datasourcemanager/server/pom_k8s.xml deleted file mode 100644 index 2eefaa0a44..0000000000 --- a/datasource/datasourcemanager/server/pom_k8s.xml +++ /dev/null @@ -1,209 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - - linkis-datasourcemanager-server - - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - hk2-api - org.glassfish.hk2 - - - jersey-common - org.glassfish.jersey.core - - - - - - com.webank.wedatasphere.linkis - linkis-datasourcemanager-common - - - asm - org.ow2.asm - - - - - - org.glassfish.jersey.ext - jersey-bean-validation - ${jersey.version} - - - javax.ws.rs-api - javax.ws.rs - - - hk2-locator - org.glassfish.hk2 - - - hk2-api - org.glassfish.hk2 - - - - - - com.webank.wedatasphere.linkis - linkis-bmlclient - - - - com.webank.wedatasphere.linkis - linkis-mybatis - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - hk2-api - org.glassfish.hk2 - 2.4.0-b34 - - - org.json4s - json4s-jackson_2.11 - ${json4s.version} - - - org.json4s - json4s-core_2.11 - ${json4s.version} - - - org.json4s - json4s-ast_2.11 - ${json4s.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-dsm-server - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - - - - - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/common/pom.xml b/datasource/metadatamanager/common/pom.xml deleted file mode 100644 index c3b9381419..0000000000 --- a/datasource/metadatamanager/common/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - - linkis-metadatamanager-common - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-common - - - asm - org.ow2.asm - - - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - src/main/resources - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/common/src/main/java/com/webank/wedatasphere/linkis/metadatamanager/common/Json.java b/datasource/metadatamanager/common/src/main/java/com/webank/wedatasphere/linkis/metadatamanager/common/Json.java deleted file mode 100644 index 203c4a1409..0000000000 --- a/datasource/metadatamanager/common/src/main/java/com/webank/wedatasphere/linkis/metadatamanager/common/Json.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2019 WeBank - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.metadatamanager.common; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.*; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; - -/** - * Json utils - * Created by jackyxxie on 2018/9/3. - */ -public class Json { - private static final String PREFIX = "["; - private static final String SUFFIX = "]"; - private static final Logger logger = LoggerFactory.getLogger(Json.class); - - private static ObjectMapper mapper; - - static{ - mapper = new ObjectMapper(); - mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); - mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); - mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); - mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); - //empty beans allowed - mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - //ignore unknown properties - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - //cancel to scape non ascii - mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false); - } - private Json(){} - - @SuppressWarnings("unchecked") - public static T fromJson(String json, Class> clazz, Class>... parameters){ - if(StringUtils.isNotBlank(json)){ - try{ - if(parameters.length > 0){ - return (T)mapper.readValue(json, mapper.getTypeFactory().constructParametricType(clazz, parameters)); - } - if(json.startsWith(PREFIX) - && json.endsWith(SUFFIX)){ - JavaType javaType = mapper.getTypeFactory() - .constructParametricType(ArrayList.class, clazz); - return mapper.readValue(json, javaType); - } - return (T)mapper.readValue(json, clazz); - } catch (Exception e) { - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - } - return null; - } - - public static T fromJson(InputStream stream, Class> clazz, Class>... parameters){ - StringBuilder builder = new StringBuilder(); - String jsonStr = null; - try{ - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); - while((jsonStr = reader.readLine()) != null){ - builder.append(jsonStr); - } - reader.close(); - }catch(Exception e){ - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - return fromJson(builder.toString(), clazz, parameters); - } - - public static String toJson(Object obj, Class> model){ - ObjectWriter writer = mapper.writer(); - if(null != obj){ - try{ - if(null != model){ - writer = writer.withView(model); - } - return writer.writeValueAsString(obj); - } catch (JsonProcessingException e) { - logger.info(e.getLocalizedMessage()); - throw new RuntimeException(e); - } - } - return null; - } - -} diff --git a/datasource/metadatamanager/server/Dockerfile b/datasource/metadatamanager/server/Dockerfile deleted file mode 100644 index 6e7ebcbb45..0000000000 --- a/datasource/metadatamanager/server/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-mdm-server.zip /opt/linkis -RUN unzip linkis-mdm-server.zip - -WORKDIR /opt/linkis/linkis-mdm-server/bin -ENTRYPOINT ["/opt/linkis/linkis-mdm-server/bin/startup.sh"] diff --git a/datasource/metadatamanager/server/conf/application.yml b/datasource/metadatamanager/server/conf/application.yml deleted file mode 100644 index c74a09c008..0000000000 --- a/datasource/metadatamanager/server/conf/application.yml +++ /dev/null @@ -1,35 +0,0 @@ -server: - port: 8296 -spring: - application: - name: mdm-server - - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - -pagehelper: - helper-dialect: mysql - reasonable: true - support-methods-arguments: true - params: countSql - diff --git a/datasource/metadatamanager/server/pom.xml b/datasource/metadatamanager/server/pom.xml deleted file mode 100644 index 1aaa0b765c..0000000000 --- a/datasource/metadatamanager/server/pom.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - linkis-metadatamanager-server - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - provided - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - - com.webank.wedatasphere.linkis - linkis-datasourcemanager-common - - - asm - org.ow2.asm - - - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - provided - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-server - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/server/pom_k8s.xml b/datasource/metadatamanager/server/pom_k8s.xml deleted file mode 100644 index 69f3f675f8..0000000000 --- a/datasource/metadatamanager/server/pom_k8s.xml +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../pom.xml - - 4.0.0 - linkis-metadatamanager-server - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - - com.webank.wedatasphere.linkis - linkis-datasourcemanager-common - - - asm - org.ow2.asm - - - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-server - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/elasticsearch/Dockerfile b/datasource/metadatamanager/service/elasticsearch/Dockerfile deleted file mode 100644 index 4736fd79a5..0000000000 --- a/datasource/metadatamanager/service/elasticsearch/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-mdm-service-es.zip /opt/linkis -RUN unzip linkis-mdm-service-es.zip - -WORKDIR /opt/linkis/linkis-mdm-service-es/bin -ENTRYPOINT ["/opt/linkis/linkis-mdm-service-es/bin/startup.sh"] diff --git a/datasource/metadatamanager/service/elasticsearch/conf/application.yml b/datasource/metadatamanager/service/elasticsearch/conf/application.yml deleted file mode 100644 index 474819da67..0000000000 --- a/datasource/metadatamanager/service/elasticsearch/conf/application.yml +++ /dev/null @@ -1,28 +0,0 @@ -server: - port: 8295 -spring: - application: - name: mdm-service-elasticsearch - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - diff --git a/datasource/metadatamanager/service/elasticsearch/pom.xml b/datasource/metadatamanager/service/elasticsearch/pom.xml deleted file mode 100644 index d710bf810e..0000000000 --- a/datasource/metadatamanager/service/elasticsearch/pom.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - - linkis-metadatamanager-service-es - - UTF-8 - 6.7.1 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - - - org.elasticsearch.client - elasticsearch-rest-client - ${es.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-es - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/elasticsearch/pom_k8s.xml b/datasource/metadatamanager/service/elasticsearch/pom_k8s.xml deleted file mode 100644 index 540fd2db48..0000000000 --- a/datasource/metadatamanager/service/elasticsearch/pom_k8s.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - - linkis-metadatamanager-service-es - - UTF-8 - 6.7.1 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - - - org.elasticsearch.client - elasticsearch-rest-client - ${es.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-es - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/hive/Dockerfile b/datasource/metadatamanager/service/hive/Dockerfile deleted file mode 100644 index 1f6244a87e..0000000000 --- a/datasource/metadatamanager/service/hive/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-mdm-service-hive.zip /opt/linkis -RUN unzip linkis-mdm-service-hive.zip - -WORKDIR /opt/linkis/linkis-mdm-service-hive/bin -ENTRYPOINT ["/opt/linkis/linkis-mdm-service-hive/bin/startup.sh"] diff --git a/datasource/metadatamanager/service/hive/conf/application.yml b/datasource/metadatamanager/service/hive/conf/application.yml deleted file mode 100644 index 08f79c0e02..0000000000 --- a/datasource/metadatamanager/service/hive/conf/application.yml +++ /dev/null @@ -1,28 +0,0 @@ -server: - port: 8293 -spring: - application: - name: mdm-service-hive - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - diff --git a/datasource/metadatamanager/service/hive/pom.xml b/datasource/metadatamanager/service/hive/pom.xml deleted file mode 100644 index 3c842514d0..0000000000 --- a/datasource/metadatamanager/service/hive/pom.xml +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - linkis-metadatamanager-service-hive - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - - org.apache.hadoop - hadoop-client - ${hadoop.version} - - - org.slf4j - slf4j-log4j12 - - - servlet-api - javax.servlet - - - guava - com.google.guava - - - - - org.apache.hive - hive-exec - ${hive.version} - - - slf4j-log4j12 - org.slf4j - - - org.apache.ivy - ivy - - - guava - com.google.guava - - - commons-lang3 - org.apache.commons - - - - - - com.webank.wedatasphere.linkis - linkis-bmlclient - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-hive - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/hive/pom_k8s.xml b/datasource/metadatamanager/service/hive/pom_k8s.xml deleted file mode 100644 index cb3df71680..0000000000 --- a/datasource/metadatamanager/service/hive/pom_k8s.xml +++ /dev/null @@ -1,174 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - linkis-metadatamanager-service-hive - - - UTF-8 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - - org.apache.hadoop - hadoop-client - ${hadoop.version} - - - org.slf4j - slf4j-log4j12 - - - servlet-api - javax.servlet - - - guava - com.google.guava - - - - - org.apache.hive - hive-exec - ${hive.version} - - - slf4j-log4j12 - org.slf4j - - - org.apache.ivy - ivy - - - guava - com.google.guava - - - commons-lang3 - org.apache.commons - - - - - - com.webank.wedatasphere.linkis - linkis-bmlclient - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-hive - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/mysql/Dockerfile b/datasource/metadatamanager/service/mysql/Dockerfile deleted file mode 100644 index 269399c5bc..0000000000 --- a/datasource/metadatamanager/service/mysql/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-mdm-service-mysql.zip /opt/linkis -RUN unzip linkis-mdm-service-mysql.zip - -WORKDIR /opt/linkis/linkis-mdm-service-mysql/bin -ENTRYPOINT ["/opt/linkis/linkis-mdm-service-mysql/bin/startup.sh"] diff --git a/datasource/metadatamanager/service/mysql/conf/application.yml b/datasource/metadatamanager/service/mysql/conf/application.yml deleted file mode 100644 index 072b1b5af1..0000000000 --- a/datasource/metadatamanager/service/mysql/conf/application.yml +++ /dev/null @@ -1,28 +0,0 @@ -server: - port: 8294 -spring: - application: - name: mdm-service-mysql - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info -logging: - config: classpath:log4j2.xml - - diff --git a/datasource/metadatamanager/service/mysql/conf/log4j2.xml b/datasource/metadatamanager/service/mysql/conf/log4j2.xml deleted file mode 100644 index 1c68190669..0000000000 --- a/datasource/metadatamanager/service/mysql/conf/log4j2.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/datasource/metadatamanager/service/mysql/pom.xml b/datasource/metadatamanager/service/mysql/pom.xml deleted file mode 100644 index cbe8df0df3..0000000000 --- a/datasource/metadatamanager/service/mysql/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - - linkis-metadatamanager-service-mysql - - - UTF-8 - 5.1.34 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - mysql - mysql-connector-java - - - - - mysql - mysql-connector-java - ${mysql.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-mysql - false - false - - src/main/assembly/distribution.xml - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/datasource/metadatamanager/service/mysql/pom_k8s.xml b/datasource/metadatamanager/service/mysql/pom_k8s.xml deleted file mode 100644 index e93710bfe1..0000000000 --- a/datasource/metadatamanager/service/mysql/pom_k8s.xml +++ /dev/null @@ -1,143 +0,0 @@ - - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../../../pom.xml - - 4.0.0 - - linkis-metadatamanager-service-mysql - - - UTF-8 - 5.1.34 - - - - - com.webank.wedatasphere.linkis - linkis-metadatamanager-common - - - com.webank.wedatasphere.linkis - linkis-module - - - asm - org.ow2.asm - - - mysql - mysql-connector-java - - - - - mysql - mysql-connector-java - ${mysql.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - linkis-mdm-service-mysql - false - false - - src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - ${project.artifactId}-${project.version} - - diff --git a/db/linkis_ddl.sql b/db/linkis_ddl.sql index 620c7e2ff5..c271459973 100644 --- a/db/linkis_ddl.sql +++ b/db/linkis_ddl.sql @@ -1,171 +1,45 @@ SET FOREIGN_KEY_CHECKS=0; --- ---------------------------- --- Table structure for linkis_develop_application --- ---------------------------- -DROP TABLE IF EXISTS `linkis_develop_application`; -CREATE TABLE `linkis_develop_application` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(200) DEFAULT NULL, - `source` varchar(50) DEFAULT NULL COMMENT 'Source of the development application', - `version` varchar(50) DEFAULT NULL, - `description` text, - `user_id` bigint(20) DEFAULT NULL, - `is_published` bit(1) DEFAULT NULL, - `create_time` datetime DEFAULT NULL, - `update_time` datetime DEFAULT NULL, - `org_id` bigint(20) DEFAULT NULL COMMENT 'Organization ID', - `visibility` bit(1) DEFAULT NULL, - `is_transfer` bit(1) DEFAULT NULL COMMENT 'Reserved word', - `initial_org_id` bigint(20) DEFAULT NULL, - `json_path` varchar(255) DEFAULT NULL COMMENT 'Path of the jason file which is used for data development in the front-end. ', - `isAsh` bit(1) DEFAULT NULL COMMENT 'If it is active', - `pic` varchar(255) DEFAULT NULL, - `star_num` int(11) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_project_list --- ---------------------------- -DROP TABLE IF EXISTS `linkis_project_list`; -CREATE TABLE `linkis_project_list` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(200) DEFAULT NULL COMMENT 'Project service name which needs to be initialized', - `is_project_need_init` bit(1) DEFAULT NULL, - `url` varchar(255) DEFAULT NULL COMMENT 'URL used to initialize a project', - `is_user_need_init` bit(1) DEFAULT NULL, - `is_project_inited` bit(1) DEFAULT NULL, - `json` text COMMENT 'Data provided by project to the front-end would be jsonized after initialization.', - `level` tinyint(255) DEFAULT NULL COMMENT 'Marks the importance of the project. When encounter initialization failure, if a user tried to log in, the project would report an error if its level is greater than 4, otherwise, grey the corresponding function button', - `user_init_url` varchar(255) DEFAULT NULL COMMENT 'URL used to initialize a user', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_project_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_project_user`; -CREATE TABLE `linkis_project_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `project_id` bigint(20) DEFAULT NULL, - `json` varchar(255) DEFAULT NULL COMMENT 'Data returned by initializing a user would be jsonized', - `user_id` bigint(20) DEFAULT NULL, - `is_init_success` bit(1) DEFAULT NULL, - `is_new_feature` bit(1) DEFAULT NULL COMMENT 'If this project is a new function to the user', - PRIMARY KEY (`id`), - UNIQUE KEY `project_id` (`project_id`,`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_user`; -CREATE TABLE `linkis_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `email` varchar(255) DEFAULT NULL, - `username` varchar(255) NOT NULL, - `password` varchar(255) DEFAULT NULL, - `admin` tinyint(1) DEFAULT NULL COMMENT 'If it is an administrator', - `active` tinyint(1) DEFAULT NULL COMMENT 'If it is active', - `name` varchar(255) DEFAULT NULL COMMENT 'User name', - `description` varchar(255) DEFAULT NULL, - `department` varchar(255) DEFAULT NULL, - `avatar` varchar(255) DEFAULT NULL COMMENT 'Path of the avator', - `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `create_by` bigint(20) DEFAULT '0', - `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `update_by` bigint(20) DEFAULT '0', - `is_first_login` bit(1) DEFAULT NULL COMMENT 'If it is the first time to log in', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -SET FOREIGN_KEY_CHECKS=0; - - --- ---------------------------- --- Table structure for linkis_application --- ---------------------------- -DROP TABLE IF EXISTS `linkis_application`; -CREATE TABLE `linkis_application` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(50) DEFAULT NULL COMMENT 'Can be one of the following: execute_application_name(in table linkis_task), request_application_name(i.e. creator), general configuration', - `chinese_name` varchar(50) DEFAULT NULL, - `description` varchar(200) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key_tree --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key_tree`; -CREATE TABLE `linkis_config_key_tree` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `key_id` bigint(20) DEFAULT NULL, - `tree_id` bigint(20) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `key_id` (`key_id`), - KEY `tree_id` (`tree_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key_user`; -CREATE TABLE `linkis_config_key_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Same as id in tale linkis_application, except that it cannot be the id of creator', - `key_id` bigint(20) DEFAULT NULL, - `user_name` varchar(50) DEFAULT NULL, - `value` varchar(200) DEFAULT NULL COMMENT 'Value of the key', - PRIMARY KEY (`id`), - UNIQUE KEY `application_id_2` (`application_id`,`key_id`,`user_name`), - KEY `key_id` (`key_id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key`; -CREATE TABLE `linkis_config_key` ( +DROP TABLE IF EXISTS `linkis_configuration_config_key`; +CREATE TABLE `linkis_configuration_config_key`( `id` bigint(20) NOT NULL AUTO_INCREMENT, `key` varchar(50) DEFAULT NULL COMMENT 'Set key, e.g. spark.executor.instances', `description` varchar(200) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Correlate with id in table linkis_application', + `engine_conn_type` varchar(50) DEFAULT NULL COMMENT 'engine type,such as spark,hive etc', `default_value` varchar(200) DEFAULT NULL COMMENT 'Adopted when user does not set key', `validate_type` varchar(50) DEFAULT NULL COMMENT 'Validate type, one of the following: None, NumInterval, FloatInterval, Include, Regex, OPF, Custom Rules', - `validate_range` varchar(100) DEFAULT NULL COMMENT 'Validate range', + `validate_range` varchar(50) DEFAULT NULL COMMENT 'Validate range', `is_hidden` tinyint(1) DEFAULT NULL COMMENT 'Whether it is hidden from user. If set to 1(true), then user cannot modify, however, it could still be used in back-end', `is_advanced` tinyint(1) DEFAULT NULL COMMENT 'Whether it is an advanced parameter. If set to 1(true), parameters would be displayed only when user choose to do so', `level` tinyint(1) DEFAULT NULL COMMENT 'Basis for displaying sorting in the front-end. Higher the level is, higher the rank the parameter gets', - `unit` varchar(64) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + `treeName` varchar(20) DEFAULT NULL COMMENT 'Reserved field, representing the subdirectory of engineType', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_config_tree --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_tree`; -CREATE TABLE `linkis_config_tree` ( +DROP TABLE IF EXISTS `linkis_configuration_config_value`; +CREATE TABLE linkis_configuration_config_value( `id` bigint(20) NOT NULL AUTO_INCREMENT, - `parent_id` bigint(20) DEFAULT NULL COMMENT 'Parent ID', - `name` varchar(50) DEFAULT NULL COMMENT 'Application name or category name under general configuration', - `description` varchar(200) DEFAULT NULL, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Same as id(in table linkis_application), except that it cannot be the id of creator', + `configkey_id` bigint(20), + `config_value` varchar(50), + `config_label_id`int(20), PRIMARY KEY (`id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -SET FOREIGN_KEY_CHECKS=0; + UNIQUE INDEX(`configkey_id`, `config_label_id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_configuration_category`; +CREATE TABLE `linkis_configuration_category` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) NOT NULL, + `level` int(20) NOT NULL, + `description` varchar(200), + `tag` varchar(200), + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE INDEX(`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Table structure for linkis_task @@ -176,6 +50,7 @@ CREATE TABLE `linkis_task` ( `instance` varchar(50) DEFAULT NULL COMMENT 'An instance of Entrance, consists of IP address of the entrance server and port', `exec_id` varchar(50) DEFAULT NULL COMMENT 'execution ID, consists of jobID(generated by scheduler), executeApplicationName , creator and instance', `um_user` varchar(50) DEFAULT NULL COMMENT 'User name', + `submit_user` varchar(50) DEFAULT NULL COMMENT 'submitUser name', `execution_code` text COMMENT 'Run script. When exceeding 6000 lines, script would be stored in HDFS and its file path would be stored in database', `progress` float DEFAULT NULL COMMENT 'Script execution progress, between zero and one', `log_path` varchar(200) DEFAULT NULL COMMENT 'File path of the log files', @@ -191,63 +66,15 @@ CREATE TABLE `linkis_task` ( `script_path` varchar(200) DEFAULT NULL COMMENT 'Path of the script in workspace', `params` text COMMENT 'Configuration item of the parameters', `engine_instance` varchar(50) DEFAULT NULL COMMENT 'An instance of engine, consists of IP address of the engine server and port', + `task_resource` varchar(1024) DEFAULT NULL, `engine_start_time` time DEFAULT NULL, + `label_json` varchar(200) DEFAULT NULL COMMENT 'label json', PRIMARY KEY (`id`), KEY `created_time` (`created_time`), KEY `um_user` (`um_user`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -DROP TABLE IF EXISTS `linkis_em_resource_meta_data`; -CREATE TABLE `linkis_em_resource_meta_data` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `em_application_name` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `em_instance` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `total_resource` varchar(2000) COLLATE utf8_bin DEFAULT NULL, - `protected_resource` varchar(2000) COLLATE utf8_bin DEFAULT NULL, - `resource_policy` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `used_resource` varchar(2000) COLLATE utf8_bin DEFAULT NULL, - `left_resource` varchar(2000) COLLATE utf8_bin DEFAULT NULL, - `locked_resource` varchar(2000) COLLATE utf8_bin DEFAULT NULL, - `register_time` bigint(20) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; - -DROP TABLE IF EXISTS `linkis_resource_lock`; -CREATE TABLE `linkis_resource_lock` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `user` varchar(50) COLLATE utf8_bin DEFAULT NULL, - `em_application_name` varchar(50) COLLATE utf8_bin DEFAULT NULL, - `em_instance` varchar(50) COLLATE utf8_bin DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `lock_unique` (`user`,`em_application_name`,`em_instance`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; - -DROP TABLE IF EXISTS `linkis_user_resource_meta_data`; -CREATE TABLE `linkis_user_resource_meta_data` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `user` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `ticket_id` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `creator` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `em_application_name` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `em_instance` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `engine_application_name` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `engine_instance` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `user_locked_resource` varchar(5000) COLLATE utf8_bin DEFAULT NULL, - `user_used_resource` varchar(5000) COLLATE utf8_bin DEFAULT NULL, - `resource_type` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `locked_time` bigint(20) DEFAULT NULL, - `used_time` bigint(20) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; - -DROP TABLE IF EXISTS `linkis_em_meta_data`; -CREATE TABLE `linkis_em_meta_data` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `em_name` varchar(500) COLLATE utf8_bin DEFAULT NULL, - `resource_request_policy` varchar(500) COLLATE utf8_bin DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; SET FOREIGN_KEY_CHECKS=0; @@ -295,7 +122,7 @@ DROP TABLE IF EXISTS `linkis_udf_tree`; CREATE TABLE `linkis_udf_tree` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `parent` bigint(20) NOT NULL, - `name` varchar(200) DEFAULT NULL COMMENT 'Category name of the function. It would be displayed in the front-end', + `name` varchar(100) DEFAULT NULL COMMENT 'Category name of the function. It would be displayed in the front-end', `user_name` varchar(50) NOT NULL, `description` varchar(255) DEFAULT NULL, `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, @@ -473,6 +300,102 @@ CREATE TABLE `linkis_mdq_table_info` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; +-- ---------------------------- +-- Table structure for linkis_role +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_role`; +CREATE TABLE `linkis_role` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `chinese_name` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `description` varchar(255) COLLATE utf8_bin DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +-- ---------------------------- +-- Table structure for linkis_user_role +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_user_role`; + CREATE TABLE `linkis_user_role` ( + `user_id` bigint(20) NOT NULL, + `role_id` bigint(20) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +-- ---------------------------- +-- Table structure for linkis_cs_context_map +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_cs_context_map`; +CREATE TABLE `linkis_cs_context_map` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `key` varchar(128) DEFAULT NULL, + `context_scope` varchar(32) DEFAULT NULL, + `context_type` varchar(32) DEFAULT NULL, + `props` text, + `value` text, + `context_id` int(11) DEFAULT NULL, + `keywords` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `key` (`key`,`context_id`,`context_type`), + KEY `keywords` (`keywords`(191)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- ---------------------------- +-- Table structure for linkis_cs_context_map_listener +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_cs_context_map_listener`; +CREATE TABLE `linkis_cs_context_map_listener` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `listener_source` varchar(255) DEFAULT NULL, + `key_id` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- ---------------------------- +-- Table structure for linkis_cs_context_history +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_cs_context_history`; +CREATE TABLE `linkis_cs_context_history` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `context_id` int(11) DEFAULT NULL, + `source` text, + `context_type` varchar(32) DEFAULT NULL, + `history_json` text, + `keyword` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `keyword` (`keyword`(191)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- ---------------------------- +-- Table structure for linkis_cs_context_id +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_cs_context_id`; +CREATE TABLE `linkis_cs_context_id` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `user` varchar(32) DEFAULT NULL, + `application` varchar(32) DEFAULT NULL, + `source` varchar(255) DEFAULT NULL, + `expire_type` varchar(32) DEFAULT NULL, + `expire_time` datetime DEFAULT NULL, + `instance` varchar(32) DEFAULT NULL, + `backup_instance` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `instance` (`instance`), + KEY `backup_instance` (`backup_instance`(191)), + KEY `instance_2` (`instance`,`backup_instance`(191)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- ---------------------------- +-- Table structure for linkis_cs_context_listener +-- ---------------------------- +DROP TABLE IF EXISTS `linkis_cs_context_listener`; +CREATE TABLE `linkis_cs_context_listener` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `listener_source` varchar(255) DEFAULT NULL, + `context_id` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + + drop table if exists `linkis_resources`; CREATE TABLE if not exists `linkis_resources` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', @@ -566,153 +489,256 @@ CREATE TABLE if not exists `linkis_resources_task` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --- ---------------------------- --- Table structure for linkis_cs_context_map --- ---------------------------- -DROP TABLE IF EXISTS `linkis_cs_context_map`; -CREATE TABLE `linkis_cs_context_map` ( + + +drop table if exists linkis_bml_project; +create table if not exists linkis_bml_project( + `id` int(10) NOT NULL AUTO_INCREMENT, + `name` varchar(128) DEFAULT NULL, + `system` varchar(64) not null default 'dss', + `source` varchar(1024) default null, + `description` varchar(1024) default null, + `creator` varchar(128) not null, + `enabled` tinyint default 1, + `create_time` datetime DEFAULT now(), + unique key(`name`), +PRIMARY KEY (`id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=COMPACT; + + + +drop table if exists linkis_bml_project_user; +create table if not exists linkis_bml_project_user( + `id` int(10) NOT NULL AUTO_INCREMENT, + `project_id` int(10) NOT NULL, + `username` varchar(64) DEFAULT NULL, + `priv` int(10) not null default 7, -- rwx 421 相加, 8是管理员,可以为其他用户授权 + `creator` varchar(128) not null, + `create_time` datetime DEFAULT now(), + `expire_time` datetime default null, + unique key user_project(`username`, `project_id`), +PRIMARY KEY (`id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=COMPACT; + + +drop table if exists linkis_bml_project_resource; +create table if not exists linkis_bml_project_resource( + `id` int(10) NOT NULL AUTO_INCREMENT, + `project_id` int(10) NOT NULL, + `resource_id` varchar(128) DEFAULT NULL, +PRIMARY KEY (`id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=COMPACT; + +DROP TABLE IF EXISTS `linkis_manager_service_instance`; + +CREATE TABLE `linkis_manager_service_instance` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `key` varchar(128) DEFAULT NULL, - `context_scope` varchar(32) DEFAULT NULL, - `context_type` varchar(32) DEFAULT NULL, - `props` text, - `value` text, - `context_id` int(11) DEFAULT NULL, - `keywords` varchar(255) DEFAULT NULL, + `instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `name` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `owner` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `mark` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `updator` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `creator` varchar(32) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `key` (`key`,`context_id`,`context_type`), - KEY `keywords` (`keywords`(191)) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + UNIQUE KEY `instance` (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_cs_context_map_listener --- ---------------------------- -DROP TABLE IF EXISTS `linkis_cs_context_map_listener`; -CREATE TABLE `linkis_cs_context_map_listener` ( +DROP TABLE IF EXISTS `linkis_manager_linkis_resources`; + +CREATE TABLE `linkis_manager_linkis_resources` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `listener_source` varchar(255) DEFAULT NULL, - `key_id` int(11) DEFAULT NULL, + `max_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `min_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `used_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `left_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `expected_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `locked_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `resourceType` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `ticketId` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `updator` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `creator` varchar(255) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_cs_context_history --- ---------------------------- -DROP TABLE IF EXISTS `linkis_cs_context_history`; -CREATE TABLE `linkis_cs_context_history` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `context_id` int(11) DEFAULT NULL, - `source` text, - `context_type` varchar(32) DEFAULT NULL, - `history_json` text, - `keyword` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `keyword` (`keyword`(191)) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +DROP TABLE IF EXISTS `linkis_manager_lock`; --- ---------------------------- --- Table structure for linkis_cs_context_id --- ---------------------------- -DROP TABLE IF EXISTS `linkis_cs_context_id`; -CREATE TABLE `linkis_cs_context_id` ( +CREATE TABLE `linkis_manager_lock` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `user` varchar(32) DEFAULT NULL, - `application` varchar(32) DEFAULT NULL, - `source` varchar(255) DEFAULT NULL, - `expire_type` varchar(32) DEFAULT NULL, - `expire_time` datetime DEFAULT NULL, - `instance` varchar(32) DEFAULT NULL, - `backup_instance` varchar(255) DEFAULT NULL, + `lock_object` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `time_out` longtext COLLATE utf8_bin, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_external_resource_provider`; +CREATE TABLE `linkis_external_resource_provider` ( + `id` int(10) NOT NULL AUTO_INCREMENT, + `resource_type` varchar(32) NOT NULL, + `name` varchar(32) NOT NULL, + `labels` varchar(32) DEFAULT NULL, + `config` text NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +DROP TABLE IF EXISTS `linkis_manager_engine_em`; +CREATE TABLE `linkis_manager_engine_em` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `engine_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `em_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_label`; + +CREATE TABLE `linkis_manager_label` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_key` varchar(32) COLLATE utf8_bin NOT NULL, + `label_value` varchar(255) COLLATE utf8_bin NOT NULL, + `label_feature` varchar(16) COLLATE utf8_bin NOT NULL, + `label_value_size` int(20) NOT NULL, + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - KEY `instance` (`instance`), - KEY `backup_instance` (`backup_instance`(191)), - KEY `instance_2` (`instance`,`backup_instance`(191)) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + UNIQUE KEY `label_key_value` (`label_key`,`label_value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_cs_context_listener --- ---------------------------- -DROP TABLE IF EXISTS `linkis_cs_context_listener`; -CREATE TABLE `linkis_cs_context_listener` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `listener_source` varchar(255) DEFAULT NULL, - `context_id` int(11) DEFAULT NULL, +DROP TABLE IF EXISTS `linkis_manager_label_value_relation`; + +CREATE TABLE `linkis_manager_label_value_relation` ( + `label_value_key` varchar(255) COLLATE utf8_bin NOT NULL, + `label_value_content` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `label_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `label_value_key_label_id` (`label_value_key`,`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_label_resource`; +CREATE TABLE `linkis_manager_label_resource` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL, + `resource_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; +DROP TABLE IF EXISTS `linkis_manager_label_service_instance`; +CREATE TABLE `linkis_manager_label_service_instance` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL, + `service_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_datasource --- ---------------------------- -CREATE TABLE IF NOT EXISTS `linkis_datasource` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `datasource_name` VARCHAR(100) NOT NULL COMMENT 'Data source name', - `datasource_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Data source type id', - `datasource_desc` VARCHAR(200) DEFAULT NULL COMMENT 'Data source description', - `create_identify` VARCHAR(20) DEFAULT 'BDP' COMMENT 'Example: project name', - `create_system` VARCHAR(20) DEFAULT 'BDP' COMMENT 'Create system', - `create_user` VARCHAR(50) DEFAULT NULL COMMENT 'Creator', - `parameter` TEXT COMMENT 'Connect parameters', - `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `modify_user` VARCHAR(50) DEFAULT NULL COMMENT 'Modify user', - `modify_time` DATETIME DEFAULT NULL COMMENT 'Modify time', - `datasource_env_id` BIGINT(20) DEFAULT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB AUTO_INCREMENT=140 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Table structure for linkis_datasource_env --- ---------------------------- -CREATE TABLE IF NOT EXISTS `linkis_datasource_env` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `env_name` VARCHAR(100) NOT NULL COMMENT 'Environment name', - `env_desc` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `create_user` VARCHAR(50) DEFAULT NULL COMMENT 'Creator', - `parameter` TEXT NOT NULL COMMENT 'Connect parameters', - `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `modify_user` VARCHAR(50) DEFAULT NULL COMMENT 'Modify user', - `modify_time` DATETIME DEFAULT NULL COMMENT 'Modify time', - PRIMARY KEY (`id`) - ) ENGINE=InnoDB AUTO_INCREMENT=108 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Table structure for linkis_datasource_type_key --- ---------------------------- -CREATE TABLE IF NOT EXISTS `linkis_datasource_type_key` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `key` VARCHAR(50) DEFAULT NULL COMMENT 'Key of variable', - `description` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `name` VARCHAR(50) DEFAULT NULL COMMENT 'Option name of column in page', - `data_source_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Type id', - `require` TINYINT(1) DEFAULT '0', - `scope` VARCHAR(50) DEFAULT NULL COMMENT 'Scope', - `default_value` VARCHAR(200) DEFAULT NULL COMMENT 'Default value', - `value_type` VARCHAR(50) DEFAULT NULL COMMENT 'Value type', - `value_regex` VARCHAR(100) DEFAULT NULL COMMENT 'Value regex', - `ref_id` BIGINT(20) DEFAULT NULL COMMENT 'Related id', - `ref_value` VARCHAR(100) DEFAULT NULL COMMENT 'Related value', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +DROP TABLE IF EXISTS `linkis_manager_label_user`; +CREATE TABLE `linkis_manager_label_user` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `username` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `label_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_manager_metrics_history`; + +CREATE TABLE `linkis_manager_metrics_history` ( + `instance_status` int(20) DEFAULT NULL, + `overload` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `heartbeat_msg` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `healthy_status` int(20) DEFAULT NULL, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `creator` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `ticketID` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `serviceName` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `instance` varchar(255) COLLATE utf8_bin DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_service_instance_metrics`; + +CREATE TABLE `linkis_manager_service_instance_metrics` ( + `instance` varchar(32) COLLATE utf8_bin NOT NULL, + `instance_status` int(11) DEFAULT NULL, + `overload` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `heartbeat_msg` text COLLATE utf8_bin DEFAULT NULL, + `healthy_status` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_engine_conn_plugin_bml_resources`; +CREATE TABLE `linkis_engine_conn_plugin_bml_resources` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `engine_conn_type` varchar(100) NOT NULL COMMENT '引擎类型', + `version` varchar(100) COMMENT '版本', + `file_name` varchar(255) COMMENT '文件名', + `file_size` bigint(20) DEFAULT 0 NOT NULL COMMENT '文件大小', + `last_modified` bigint(20) COMMENT '文件更新时间', + `bml_resource_id` varchar(100) NOT NULL COMMENT '所属系统', + `bml_resource_version` varchar(200) NOT NULL COMMENT '资源所属者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `last_update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; + +DROP TABLE IF EXISTS `linkis_instance_label`; +CREATE TABLE `linkis_instance_label` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_key` varchar(32) COLLATE utf8_bin NOT NULL COMMENT 'string key', + `label_value` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'string value', + `label_feature` varchar(16) COLLATE utf8_bin NOT NULL COMMENT 'store the feature of label, but it may be redundant', + `label_value_size` int(20) NOT NULL COMMENT 'size of key -> value map', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + PRIMARY KEY (`id`), + UNIQUE KEY `label_key_value` (`label_key`,`label_value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_instance_label_value_relation`; +CREATE TABLE `linkis_instance_label_value_relation` ( + `label_value_key` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'value key', + `label_value_content` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'value content', + `label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_instance_label -> id', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + UNIQUE KEY `label_value_key_label_id` (`label_value_key`,`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_instance_label_relation`; +CREATE TABLE `linkis_instance_label_relation` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_instance_label -> id', + `service_instance` varchar(64) NOT NULL COLLATE utf8_bin COMMENT 'structure like ${host|machine}:${port}', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_instance_info`; +CREATE TABLE `linkis_instance_info` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `instance` varchar(128) COLLATE utf8_bin DEFAULT NULL COMMENT 'structure like ${host|machine}:${port}', + `name` varchar(128) COLLATE utf8_bin DEFAULT NULL COMMENT 'equal application name in registry', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + PRIMARY KEY (`id`), + UNIQUE KEY `instance` (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_datasource_type --- ---------------------------- -CREATE TABLE IF NOT EXISTS `linkis_datasource_type` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `icon` VARCHAR(50) DEFAULT NULL COMMENT 'Icon', - `description` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `name` VARCHAR(50) DEFAULT NULL COMMENT 'Name', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --- ---------------------------- --- Table structure for linkis_datasource_type_env --- ---------------------------- -CREATE TABLE IF NOT EXISTS `linkis_datasource_type_env` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `data_source_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Type id', - `env_id` BIGINT(20) DEFAULT NULL COMMENT 'Environment id', - PRIMARY KEY (`id`) -)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; \ No newline at end of file diff --git a/db/linkis_dml.sql b/db/linkis_dml.sql index 4ffba935b8..cccd2d8f46 100644 --- a/db/linkis_dml.sql +++ b/db/linkis_dml.sql @@ -1,260 +1,318 @@ -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, '通用设置', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'spark', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'IDE', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'hive', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'storage', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'python', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'tidb', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'presto', NULL, NULL); - -SELECT @application_id := id from linkis_application where name = '通用设置'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '队列资源', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '预热机制', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '清理机制', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '驱动器资源', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'spark'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark资源设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark引擎设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'hive'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'hive引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'hive资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'python'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'python引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'python资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'tidb'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'tidb设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'presto'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'presto引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'presto资源设置', NULL, @application_id); - - -SELECT @application_id := id from linkis_application where name = '通用设置'; -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.yarnqueue', 'yarn队列名', 'yarn队列名', @application_id, 'default', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.preheating.time', '预热时间', '预热时间', @application_id, '9:00', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.tmpfile.clean.time', 'tmp文件清理时间', 'tmp文件清理时间', @application_id, '10:00', 'None', NULL, '0', '0', '1'); - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.yarnqueue.cores.max', '取值范围:1-500,单位:个', '队列CPU使用上限', @application_id, '150', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|500)$', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `unit`) VALUES (0, 'wds.linkis.yarnqueue.memory.max', '取值范围:1-1000,单位:G', '队列内存使用上限', @application_id, '300G', 'Regex', '^([1-9]\\d{0,2}|1000)(G|g)$', '0', '0', '1', 'G'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `unit`) VALUES (0, 'wds.linkis.client.memory.max', '取值范围:1-1000,单位:G', '驱动器内存使用上限', @application_id, '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', 'G'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-20,单位:个', '引擎最大并发数', @application_id, '10', 'NumInterval', '[1,20]', '0', '0', '1'); - - -SELECT @application_id := id from linkis_application where name = 'IDE'; -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', @application_id, '2', 'NumInterval', '[1,40]', '0', '0', '2'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', @application_id, '2', 'NumInterval', '[1,2]', '1', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', @application_id, '3', 'NumInterval', '[3,15]', '0', '0', '3'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数', @application_id, '1', 'NumInterval', '[1,1]', '1', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小', @application_id, '2', 'NumInterval', '[1,15]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.client.memory', '取值范围:1-10,单位:G', 'hive引擎初始化内存大小', @application_id, '2', 'NumInterval', '[1,10]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.client.java.opts', 'hive客户端进程参数', 'hive引擎启动时jvm参数', @application_id, '', 'None', NULL, '1', '1', '1'); - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'hive引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'spark引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'python引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'mapred.reduce.tasks', '范围:1-20,单位:个', 'reduce数', @application_id, '10', 'NumInterval', '[1,20]', '0', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'dfs.block.size', '取值范围:2-10,单位:G', 'map数据块大小', @application_id, '10', 'NumInterval', '[2,10]', '0', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.exec.reduce.bytes.per.reducer', '取值范围:2-10,单位:G', 'reduce处理的数据量', @application_id, '10', 'NumInterval', '[2,10]', '0', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'python.java.client.memory', '取值范围:1-2,单位:G', 'python引擎初始化内存大小', @application_id, '1', 'NumInterval', '[1,2]', '0', '0', '1'); - - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'spark引擎最大并发数', @application_id, '1', 'NumInterval', '[1,3]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', @application_id, '2', 'NumInterval', '[1,40]', '0', '0', '2'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', @application_id, '2', 'NumInterval', '[1,2]', '1', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', @application_id, '3', 'NumInterval', '[3,15]', '0', '0', '3'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数 ', @application_id, '1', 'NumInterval', '[1,1]', '1', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小', @application_id, '2', 'NumInterval', '[1,15]', '0', '0', '1'); - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.pd.addresses', NULL, NULL, @application_id, 'pd0:2379', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.addr', NULL, NULL, @application_id, 'tidb', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.password', NULL, NULL, @application_id, NULL, 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.port', NULL, NULL, @application_id, '4000', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.user', NULL, NULL, @application_id, 'root', 'None', NULL, '0', '0', '1'); - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-20,单位:个', 'presto引擎最大并发数', @application_id, '20', 'NumInterval', '[1,20]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'presto.session.query_max_total_memory', '取值范围:1-100,单位:GB/MB', 'presto单次任务最大使用内存', @application_id, '20GB', 'Regex', '^([1-9]\\d{0,2}|1000)(GB|MB|gb|mb)$', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'presto.session.query_max_run_time', '单位:s(秒)/m(分)', 'presto单次任务最大耗时', @application_id, '30m', 'Regex', '^([1-9]\\d{0,2}|1000)(m|s)$', '0', '0', '1'); - -#---------------------------------------全局设置------------------ - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue.cores.max'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue.memory.max'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.preheating.time'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '预热机制'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.tmpfile.clean.time'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '清理机制'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `name` = '引擎最大并发数'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '引擎设置'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.client.memory.max'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '驱动器资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); -#---------------------------------------spark--------------- -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.instances' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- 变量: +SET @SPARK_LABEL="spark-2.4.3"; +SET @HIVE_LABEL="hive-1.2.1"; +SET @PYTHON_LABEL="python-python2"; +SET @PIPELINE_LABEL="pipeline-*"; +SET @JDBC_LABEL="jdbc-4"; + +-- 衍生变量: +SET @SPARK_ALL=CONCAT('*-*,',@SPARK_LABEL); +SET @SPARK_IDE=CONCAT('*-IDE,',@SPARK_LABEL); +SET @SPARK_NODE=CONCAT('*-nodeexecution,',@SPARK_LABEL); +SET @SPARK_VISUALIS=CONCAT('*-Visualis,',@SPARK_LABEL); + +SET @HIVE_ALL=CONCAT('*-*,',@HIVE_LABEL); +SET @HIVE_IDE=CONCAT('*-IDE,',@HIVE_LABEL); +SET @HIVE_NODE=CONCAT('*-nodeexecution,',@HIVE_LABEL); + +SET @PYTHON_ALL=CONCAT('*-*,',@PYTHON_LABEL); +SET @PYTHON_IDE=CONCAT('*-IDE,',@PYTHON_LABEL); +SET @PYTHON_NODE=CONCAT('*-nodeexecution,',@PYTHON_LABEL); + +SET @PIPELINE_ALL=CONCAT('*-*,',@PIPELINE_LABEL); +SET @PIPELINE_IDE=CONCAT('*-IDE,',@PIPELINE_LABEL); + +SET @JDBC_ALL=CONCAT('*-*,',@JDBC_LABEL); +SET @JDBC_IDE=CONCAT('*-IDE,',@JDBC_LABEL); + + + +-- Configuration的默认Key +-- 全局设置 +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`) VALUES ('wds.linkis.rm.yarnqueue', 'yarn队列名', 'yarn队列名', 'default', 'None', NULL, '0', '0', '1', '队列资源'); +-- spark +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.instance.max', '取值范围:1-128,单位:个', 'yarn队列实例最大个数', '30', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.cores.max', '取值范围:1-500,单位:个', '队列CPU使用上限', '150', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|500)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.memory.max', '取值范围:1-1000,单位:G', '队列内存使用上限', '300G', 'Regex', '^([1-9]\\d{0,2}|1000)(G|g)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', '2', 'NumInterval', '[1,40]', '0', '0', '2', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', '2', 'NumInterval', '[1,2]', '1', '0', '1','spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', '3', 'NumInterval', '[3,15]', '0', '0', '3', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数', '1', 'NumInterval', '[1,1]', '1', '1', '1', 'spark资源设置','spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小','2', 'NumInterval', '[1,15]', '0', '0', '1', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.pd.addresses', NULL, NULL, 'pd0:2379', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.addr', NULL, NULL, 'tidb', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.password', NULL, NULL, NULL, 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.port', NULL, NULL, '4000', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.user', NULL, NULL, 'root', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.python.version', '取值范围:python2,python3', 'python版本','python2', 'OFT', '[\"python3\",\"python2\"]', '0', '0', '1', 'spark引擎设置', 'spark'); +-- hive +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.client.memory', '取值范围:1-10,单位:G', 'hive引擎初始化内存大小','2', 'NumInterval', '[1,10]', '0', '0', '1', 'hive引擎设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.client.java.opts', 'hive客户端进程参数', 'hive引擎启动时jvm参数','', 'None', NULL, '1', '1', '1', 'hive引擎设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('mapred.reduce.tasks', '范围:1-20,单位:个', 'reduce数', '10', 'NumInterval', '[1,20]', '0', '1', '1', 'hive资源设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('dfs.block.size', '取值范围:2-10,单位:G', 'map数据块大小', '10', 'NumInterval', '[2,10]', '0', '1', '1', 'hive资源设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.exec.reduce.bytes.per.reducer', '取值范围:2-10,单位:G', 'reduce处理的数据量', '10', 'NumInterval', '[2,10]', '0', '1', '1', 'hive资源设置', 'hive'); +-- python +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('python.java.client.memory', '取值范围:1-2,单位:G', 'python引擎初始化内存大小', '1', 'NumInterval', '[1,2]', '0', '0', '1', 'python引擎设置', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('python.version', '取值范围:python2,python3', 'python版本','python2', 'OFT', '[\"python3\",\"python2\"]', '0', '0', '1', 'python引擎设置', 'python'); +-- pipeline +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.mold', '取值范围:csv或excel', '结果集导出类型','csv', 'OFT', '[\"csv\",\"excel\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.field.split', '取值范围:,或\\t', 'csv分隔符',',', 'OFT', '[\",\",\"\\\\t\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.charset', '取值范围:utf-8或gbk', '结果集导出字符集','gbk', 'OFT', '[\"utf-8\",\"gbk\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.isoverwtite', '取值范围:true或false', '是否覆写','true', 'OFT', '[\"true\",\"false\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.instance', '范围:1-3,单位:个', 'pipeline引擎最大并发数','3', 'NumInterval', '[1,3]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.engine.memory', '取值范围:1-10,单位:G', 'pipeline引擎初始化内存大小','2', 'NumInterval', '[1,10]', '0', '0', '1', 'pipeline资源设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.shuffle.null.type', '取值范围:NULL或者BLANK', '空值替换','NULL', 'OFT', '[\"NULL\",\"BLANK\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +-- jdbc +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.connect.url', '例如:jdbc:hive2://127.0.0.1:10000', 'jdbc连接地址', 'jdbc:hive2://127.0.0.1:10000', 'Regex', '^\s*jdbc:\w+://([^:]+)(:\d+)(/[^\?]+)?(\?\S*)?$', '0', '0', '1', '数据源配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.version', '取值范围:jdbc3,jdbc4', 'jdbc版本','jdbc4', 'OFT', '[\"jdbc3\",\"jdbc4\"]', '0', '0', '1', '数据源配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.username', 'username', '数据库连接用户名', '', '', '', '0', '0', '1', '用户配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.password', 'password', '数据库连接密码', '', '', '', '0', '0', '1', '用户配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.connect.max', '范围:1-20,单位:个', 'jdbc引擎最大连接数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '数据源配置', 'jdbc'); +-- Configuration一级目录 +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-全局设置,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-IDE,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-Visualis,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-nodeexecution,*-*', 'OPTIONAL', 2, now(), now()); + + +-- 引擎级别默认配置 +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PIPELINE_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@JDBC_ALL, 'OPTIONAL', 2, now(), now()); + + +-- Configuration二级目录(creator 级别的默认配置) +-- IDE +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PIPELINE_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@JDBC_IDE, 'OPTIONAL', 2, now(), now()); + +-- Visualis +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_VISUALIS, 'OPTIONAL', 2, now(), now()); +-- nodeexecution +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_NODE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_NODE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_NODE, 'OPTIONAL', 2, now(), now()); + + +-- 关联一级二级目录 +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-全局设置,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-IDE,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-Visualis,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-nodeexecution,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_VISUALIS; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + + +---- 关联label和默认配置 +-- 全局默认配置(此处的'*-*,*-*'与一级目录'*-全局设置,*-*'相同,真正查询全局设置的label时应当查询*-*,*-*,而不是*-全局设置,*-*) +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-*,*-*', 'OPTIONAL', 2, now(), now()); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue' AND `engine_conn_type` IS NULL; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = '*-*,*-*'; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +-- spark默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.instance.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.cores.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.memory.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'spark引擎最大并发数' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark引擎设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.cores' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.memory' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.cores' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.instances' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.memory' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.cores' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#---------------------------------------tidb------------------ +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.memory' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.instances' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.driver.cores' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'spark引擎最大并发数' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark引擎设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.driver.memory' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.cores' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.python.version' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.memory' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- hive默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.cores' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.memory' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.pd.addresses' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.client.memory' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.addr' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.client.java.opts' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.password' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'mapred.reduce.tasks' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.port' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'dfs.block.size' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.user' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.exec.reduce.bytes.per.reducer' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#---------------------------hive----------------- -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'hive引擎最大并发数' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive引擎设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- python默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.client.memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'mapred.reduce.tasks' and a.name = 'IDE'; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'dfs.block.size' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'python.java.client.memory' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.exec.reduce.bytes.per.reducer' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'python.version' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.client.java.opts' and a.name = 'IDE'; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- pipeline默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.mold' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#------------------------python--------------------- +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.field.split' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'python引擎最大并发数' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'python引擎设置' and a.name = 'python' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.charset' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'python.java.client.memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'python资源设置' and a.name = 'python' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.isoverwtite' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.engine.memory' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#------------控制台-jdbc--------- -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (NULL, 'jdbc', NULL, NULL); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.shuffle.null.type' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -select @application_id:=id from `linkis_application` where `name` = 'IDE'; -select @jdbc_id:=id from `linkis_application` where `name` = 'jdbc'; +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.instance' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (NULL, 'jdbc.url', '格式:', 'jdbc连接地址', @application_id, NULL , 'None', NULL , '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (NULL, 'jdbc.username', NULL , 'jdbc连接用户名', @application_id, NULL, 'None', NULL , '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (NULL, 'jdbc.password', NULL , 'jdbc连接密码', @application_id, NULL , 'None', NULL , '0', '0', '1'); +-- jdbc默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.connect.url' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (NULL, '0', 'jdbc连接设置', NULL, @jdbc_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.version' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -select @key_id1:=id from `linkis_config_key` where `application_id` = @application_id and `key` = 'jdbc.url'; -select @key_id2:=id from `linkis_config_key` where `application_id` = @application_id and `key` = 'jdbc.username'; -select @key_id3:=id from `linkis_config_key` where `application_id` = @application_id and `key` = 'jdbc.password'; +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.username' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @tree_id1:=t.id from linkis_config_tree t LEFT JOIN linkis_application a on t.application_id = a.id WHERE t.`name` = 'jdbc连接设置' and a.`name` = 'jdbc'; +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.password' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -insert into `linkis_config_key_tree` VALUES(NULL,@key_id1,@tree_id1); -insert into `linkis_config_key_tree` VALUES(NULL,@key_id2,@tree_id1); -insert into `linkis_config_key_tree` VALUES(NULL,@key_id3,@tree_id1); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.connect.max' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'ElasticSearch'); -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'Hive'); -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'MySql'); -#------------------------presto--------------------- -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'presto引擎最大并发数' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'presto引擎设置' and a.name = 'presto' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'presto.session.query_max_total_memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'presto资源设置' and a.name = 'presto' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'presto.session.query_max_run_time' and a.name = 'IDE'; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'presto资源设置' and a.name = 'presto' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +insert into `linkis_external_resource_provider`(`id`,`resource_type`,`name`,`labels`,`config`) values +(1,'Yarn','sit',NULL,'{\r\n\"rmWebAddress\": \"@YARN_RESTFUL_URL\",\r\n\"hadoopVersion\": \"2.7.2\",\r\n\"authorEnable\":true,\r\n\"user\":\"hadoop\",\r\n\"pwd\":\"897ede66a860\"\r\n}'); diff --git a/db/module/linkis-bml.sql b/db/module/linkis-bml.sql index b2355bfb02..d5f4b3dfab 100644 --- a/db/module/linkis-bml.sql +++ b/db/module/linkis-bml.sql @@ -17,10 +17,10 @@ CREATE TABLE `linkis_resources` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4; --- 修改expire_type的默认值为NULL +--修改expire_type的默认值为NULL alter table linkis_resources alter column expire_type set default null; --- 修改expire_time的默认值为NULL +--修改expire_time的默认值为NULL alter table linkis_resources alter column expire_time set default null; @@ -40,15 +40,15 @@ CREATE TABLE `linkis_resources_version` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --- 添加start_byte 和 end_byte 字段 +--添加start_byte 和 end_byte 字段 ALTER TABLE `linkis_resources_version` ADD COLUMN `start_byte` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 AFTER `size`; ALTER TABLE `linkis_resources_version` ADD COLUMN `end_byte` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 AFTER `start_byte`; --- version字段修改 +--version字段修改 alter table `linkis_resources_version` modify column `version` varchar(20) not null; --- 给resource_id 和 version 加上联合唯一约束 +--给resource_id 和 version 加上联合唯一约束 alter table `linkis_resources_version` add unique key `resource_id_version`(`resource_id`, `version`); @@ -75,13 +75,13 @@ CREATE TABLE `linkis_resources_download_history` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --- 删除resources_version_id 字段 +--删除resources_version_id 字段 alter table `linkis_resources_download_history` drop column `resources_version_id`; --- 添加resource_id 字段 +--添加resource_id 字段 alter table `linkis_resources_download_history` add column `resource_id` varchar(50) not null after `state`; --- 添加version字段 +--添加version字段 alter table `linkis_resources_download_history` add column `version` varchar(20) not null after `resource_id`; create table dws_bml_resources_contentType ( @@ -93,7 +93,7 @@ create table dws_bml_resources_contentType ( UNIQUE KEY `whitelist_contentType_uindex` (`content_type`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --- 创建资源任务表,包括上传,更新,下载 +--创建资源任务表,包括上传,更新,下载 CREATE TABLE `linkis_resources_task` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `resource_id` varchar(50) DEFAULT NULL COMMENT '资源id,资源的uuid', diff --git a/db/module/linkis-datasource.sql b/db/module/linkis-datasource.sql deleted file mode 100644 index 40a7de947c..0000000000 --- a/db/module/linkis-datasource.sql +++ /dev/null @@ -1,67 +0,0 @@ -CREATE TABLE IF NOT EXISTS `linkis_datasource` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `datasource_name` VARCHAR(100) NOT NULL COMMENT 'Data source name', - `datasource_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Data source type id', - `datasource_desc` VARCHAR(200) DEFAULT NULL COMMENT 'Data source description', - `create_identify` VARCHAR(20) DEFAULT 'BDP' COMMENT 'Example: project name', - `create_system` VARCHAR(20) DEFAULT 'BDP' COMMENT 'Create system', - `create_user` VARCHAR(50) DEFAULT NULL COMMENT 'Creator', - `parameter` TEXT COMMENT 'Connect parameters', - `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `modify_user` VARCHAR(50) DEFAULT NULL COMMENT 'Modify user', - `modify_time` DATETIME DEFAULT NULL COMMENT 'Modify time', - `datasource_env_id` BIGINT(20) DEFAULT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB AUTO_INCREMENT=140 DEFAULT CHARSET=utf8; - - -CREATE TABLE IF NOT EXISTS `linkis_datasource_env` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `env_name` VARCHAR(100) NOT NULL COMMENT 'Environment name', - `env_desc` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `create_user` VARCHAR(50) DEFAULT NULL COMMENT 'Creator', - `parameter` TEXT NOT NULL COMMENT 'Connect parameters', - `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `modify_user` VARCHAR(50) DEFAULT NULL COMMENT 'Modify user', - `modify_time` DATETIME DEFAULT NULL COMMENT 'Modify time', - PRIMARY KEY (`id`) - ) ENGINE=InnoDB AUTO_INCREMENT=108 DEFAULT CHARSET=utf8; - - -CREATE TABLE IF NOT EXISTS `linkis_datasource_type_key` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `key` VARCHAR(50) DEFAULT NULL COMMENT 'Key of variable', - `description` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `name` VARCHAR(50) DEFAULT NULL COMMENT 'Option name of column in page', - `data_source_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Type id', - `require` TINYINT(1) DEFAULT '0', - `scope` VARCHAR(50) DEFAULT NULL COMMENT 'Scope', - `default_value` VARCHAR(200) DEFAULT NULL COMMENT 'Default value', - `value_type` VARCHAR(50) DEFAULT NULL COMMENT 'Value type', - `value_regex` VARCHAR(100) DEFAULT NULL COMMENT 'Value regex', - `ref_id` BIGINT(20) DEFAULT NULL COMMENT 'Related id', - `ref_value` VARCHAR(100) DEFAULT NULL COMMENT 'Related value', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - -CREATE TABLE IF NOT EXISTS `linkis_datasource_type` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `icon` VARCHAR(50) DEFAULT NULL COMMENT 'Icon', - `description` VARCHAR(200) DEFAULT NULL COMMENT 'Description', - `name` VARCHAR(50) DEFAULT NULL COMMENT 'Name', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - -CREATE TABLE IF NOT EXISTS `linkis_datasource_type_env` ( - `id` BIGINT(20) NOT NULL AUTO_INCREMENT, - `data_source_type_id` BIGINT(20) DEFAULT NULL COMMENT 'Type id', - `env_id` BIGINT(20) DEFAULT NULL COMMENT 'Environment id', - PRIMARY KEY (`id`) -)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'ElasticSearch'); -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'Hive'); -INSERT INTO `linkis_datasource_type`(`icon`, `name`) VALUES('0x001', 'MySql'); \ No newline at end of file diff --git a/db/module/linkis_application.sql b/db/module/linkis_application.sql deleted file mode 100644 index 2f739ccaa6..0000000000 --- a/db/module/linkis_application.sql +++ /dev/null @@ -1,85 +0,0 @@ -SET FOREIGN_KEY_CHECKS=0; - --- ---------------------------- --- Table structure for linkis_develop_application --- ---------------------------- -DROP TABLE IF EXISTS `linkis_develop_application`; -CREATE TABLE `linkis_develop_application` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(200) DEFAULT NULL, - `source` varchar(50) DEFAULT NULL COMMENT 'Source of the development application', - `version` varchar(50) DEFAULT NULL, - `description` text, - `user_id` bigint(20) DEFAULT NULL, - `is_published` bit(1) DEFAULT NULL, - `create_time` datetime DEFAULT NULL, - `update_time` datetime DEFAULT NULL, - `org_id` bigint(20) DEFAULT NULL COMMENT 'Organization ID', - `visibility` bit(1) DEFAULT NULL, - `is_transfer` bit(1) DEFAULT NULL COMMENT 'Reserved word', - `initial_org_id` bigint(20) DEFAULT NULL, - `json_path` varchar(255) DEFAULT NULL COMMENT 'Path of the jason file which is used for data development in the front-end.', - `isAsh` bit(1) DEFAULT NULL COMMENT 'If it is active', - `pic` varchar(255) DEFAULT NULL, - `star_num` int(11) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_project_list --- ---------------------------- -DROP TABLE IF EXISTS `linkis_project_list`; -CREATE TABLE `linkis_project_list` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(200) DEFAULT NULL COMMENT 'Project service name which needs to be initialized', - `is_project_need_init` bit(1) DEFAULT NULL, - `url` varchar(255) DEFAULT NULL COMMENT 'URL used to initialize a project', - `is_user_need_init` bit(1) DEFAULT NULL, - `is_project_inited` bit(1) DEFAULT NULL, - `json` text COMMENT 'Data provided by project to the front-end would be jsonized after initialization.', - `level` tinyint(255) DEFAULT NULL COMMENT 'Marks the importance of the project. When encounter initialization failure, if a user tried to log in, the project would report an error if its level is greater than 4, otherwise, grey the corresponding function button', - `user_init_url` varchar(255) DEFAULT NULL COMMENT 'URL used to initialize a user', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_project_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_project_user`; -CREATE TABLE `linkis_project_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `project_id` bigint(20) DEFAULT NULL, - `json` varchar(255) DEFAULT NULL COMMENT 'Data returned by initializing a user would be jsonized', - `user_id` bigint(20) DEFAULT NULL, - `is_init_success` bit(1) DEFAULT NULL, - `is_new_feature` bit(1) DEFAULT NULL COMMENT 'If this project is a new function to the user', - PRIMARY KEY (`id`), - UNIQUE KEY `project_id` (`project_id`,`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - --- ---------------------------- --- Table structure for linkis_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_user`; -CREATE TABLE `linkis_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `email` varchar(255) DEFAULT NULL, - `username` varchar(255) NOT NULL, - `password` varchar(255) DEFAULT NULL, - `admin` tinyint(1) DEFAULT NULL COMMENT 'If it is an administrator', - `active` tinyint(1) DEFAULT NULL COMMENT 'If it is active', - `name` varchar(255) DEFAULT NULL COMMENT 'User name', - `description` varchar(255) DEFAULT NULL, - `department` varchar(255) DEFAULT NULL, - `avatar` varchar(255) DEFAULT NULL COMMENT 'Path of the avator', - `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `create_by` bigint(20) DEFAULT '0', - `update_time` timestamp NOT NULL DEFAULT '1970-01-01 08:00:01', - `update_by` bigint(20) DEFAULT '0', - `is_first_login` bit(1) DEFAULT NULL COMMENT 'If it is the first time to log in', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - diff --git a/db/module/linkis_configuration.sql b/db/module/linkis_configuration.sql index 1f433220fc..021a39cb48 100644 --- a/db/module/linkis_configuration.sql +++ b/db/module/linkis_configuration.sql @@ -1,82 +1,42 @@ -SET FOREIGN_KEY_CHECKS=0; - - --- ---------------------------- --- Table structure for linkis_application --- ---------------------------- -DROP TABLE IF EXISTS `linkis_application`; -CREATE TABLE `linkis_application` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `name` varchar(50) DEFAULT NULL COMMENT 'Can be one of the following: execute_application_name(in table linkis_task), request_application_name(i.e. creator), general configuration', - `chinese_name` varchar(50) DEFAULT NULL, - `description` varchar(200) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key_tree --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key_tree`; -CREATE TABLE `linkis_config_key_tree` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `key_id` bigint(20) DEFAULT NULL, - `tree_id` bigint(20) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `key_id` (`key_id`), - KEY `tree_id` (`tree_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key_user --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key_user`; -CREATE TABLE `linkis_config_key_user` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Same as id in tale linkis_application, except that it cannot be the id of creator', - `key_id` bigint(20) DEFAULT NULL, - `user_name` varchar(50) DEFAULT NULL, - `value` varchar(200) DEFAULT NULL COMMENT 'Value of the key', - PRIMARY KEY (`id`), - UNIQUE KEY `application_id_2` (`application_id`,`key_id`,`user_name`), - KEY `key_id` (`key_id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - - --- ---------------------------- --- Table structure for linkis_config_key --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_key`; -CREATE TABLE `linkis_config_key` ( +DROP TABLE IF EXISTS `linkis_configuration_config_key`; +CREATE TABLE `linkis_configuration_config_key`( `id` bigint(20) NOT NULL AUTO_INCREMENT, `key` varchar(50) DEFAULT NULL COMMENT 'Set key, e.g. spark.executor.instances', `description` varchar(200) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Correlate with id in table linkis_application', + `engine_conn_type` varchar(50) DEFAULT NULL COMMENT 'engine type,such as spark,hive etc', `default_value` varchar(200) DEFAULT NULL COMMENT 'Adopted when user does not set key', `validate_type` varchar(50) DEFAULT NULL COMMENT 'Validate type, one of the following: None, NumInterval, FloatInterval, Include, Regex, OPF, Custom Rules', - `validate_range` varchar(100) DEFAULT NULL COMMENT 'Validate range', + `validate_range` varchar(50) DEFAULT NULL COMMENT 'Validate range', `is_hidden` tinyint(1) DEFAULT NULL COMMENT 'Whether it is hidden from user. If set to 1(true), then user cannot modify, however, it could still be used in back-end', `is_advanced` tinyint(1) DEFAULT NULL COMMENT 'Whether it is an advanced parameter. If set to 1(true), parameters would be displayed only when user choose to do so', `level` tinyint(1) DEFAULT NULL COMMENT 'Basis for displaying sorting in the front-end. Higher the level is, higher the rank the parameter gets', - `unit` varchar(64) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + `treeName` varchar(20) DEFAULT NULL COMMENT 'Reserved field, representing the subdirectory of engineType', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; --- ---------------------------- --- Table structure for linkis_config_tree --- ---------------------------- -DROP TABLE IF EXISTS `linkis_config_tree`; -CREATE TABLE `linkis_config_tree` ( +DROP TABLE IF EXISTS `linkis_configuration_config_value`; +CREATE TABLE linkis_configuration_config_value( `id` bigint(20) NOT NULL AUTO_INCREMENT, - `parent_id` bigint(20) DEFAULT NULL COMMENT 'Parent ID', - `name` varchar(50) DEFAULT NULL COMMENT 'Application name or category name under general configuration', - `description` varchar(200) DEFAULT NULL, - `application_id` bigint(20) DEFAULT NULL COMMENT 'Same as id(in table linkis_application), except that it cannot be the id of creator', + `configkey_id` bigint(20), + `config_value` varchar(50), + `config_label_id`int(20), + PRIMARY KEY (`id`), + UNIQUE INDEX(`configkey_id`, `config_label_id`) +)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_configuration_category`; +CREATE TABLE `linkis_configuration_category` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) NOT NULL, + `level` int(20) NOT NULL, + `description` varchar(200), + `tag` varchar(200), + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - KEY `application_id` (`application_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + UNIQUE INDEX(`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + diff --git a/db/module/linkis_configuration_dml.sql b/db/module/linkis_configuration_dml.sql index 4e845aca3d..ca31ec74ca 100644 --- a/db/module/linkis_configuration_dml.sql +++ b/db/module/linkis_configuration_dml.sql @@ -1,246 +1,313 @@ -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, '通用设置', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'spark', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'IDE', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'hive', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'storage', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'python', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'tidb', NULL, NULL); -INSERT INTO `linkis_application` (`id`, `name`, `chinese_name`, `description`) VALUES (0, 'pipeline', NULL, NULL); - -SELECT @application_id := id from linkis_application where name = '通用设置'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '队列资源', NULL, @application_id); -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '预热机制', NULL, @application_id); -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '清理机制', NULL, @application_id); -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '驱动器资源', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'spark'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark资源设置', NULL, @application_id); -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark引擎设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'hive'; -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'hive引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'hive资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'python'; -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'python引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'python资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'tidb'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'tidb设置', NULL, @application_id); -#INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark引擎设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', 'spark资源设置', NULL, @application_id); - -SELECT @application_id := id from linkis_application where name = 'pipeline'; -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '导入导出设置', NULL, @application_id); -INSERT INTO `linkis_config_tree` (`id`, `parent_id`, `name`, `description`, `application_id`) VALUES (0, '0', '导入导出资源设置', NULL, @application_id); - - - -SELECT @application_id := id from linkis_application where name = '通用设置'; -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.yarnqueue', 'yarn队列名', 'yarn队列名', @application_id, 'ide', 'None', NULL, '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.preheating.time', '预热时间', '预热时间', @application_id, '9:00', 'None', NULL, '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.tmpfile.clean.time', 'tmp文件清理时间', 'tmp文件清理时间', @application_id, '10:00', 'None', NULL, '0', '0', '1'); - -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.yarnqueue.cores.max', '取值范围:1-500,单位:个', '队列CPU使用上限', @application_id, '150', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|500)$', '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `unit`) VALUES (0, 'wds.linkis.yarnqueue.memory.max', '取值范围:1-1000,单位:G', '队列内存使用上限', @application_id, '300G', 'Regex', '^([1-9]\\d{0,2}|1000)(G|g)$', '0', '0', '1','G'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `unit`) VALUES (0, 'wds.linkis.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', @application_id, '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', 'G'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-20,单位:个', '引擎最大并发数', @application_id, '10', 'NumInterval', '[1,20]', '0', '0', '1'); - - -SELECT @application_id := id from linkis_application where name = 'IDE'; -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', @application_id, '2', 'NumInterval', '[1,40]', '0', '0', '2'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', @application_id, '2', 'NumInterval', '[1,2]', '1', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', @application_id, '3', 'NumInterval', '[3,15]', '0', '0', '3'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数', @application_id, '1', 'NumInterval', '[1,1]', '1', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小', @application_id, '2', 'NumInterval', '[1,15]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.client.memory', '取值范围:1-10,单位:G', 'hive引擎初始化内存大小', @application_id, '2', 'NumInterval', '[1,10]', '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.client.java.opts', 'hive客户端进程参数', 'hive引擎启动时jvm参数', @application_id, '', 'None', NULL, '1', '1', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'hive引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'spark引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'python引擎最大并发数', @application_id, '3', 'NumInterval', '[1,3]', '0', '0', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'mapred.reduce.tasks', '范围:1-20,单位:个', 'reduce数', @application_id, '10', 'NumInterval', '[1,20]', '0', '1', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'dfs.block.size', '取值范围:2-10,单位:G', 'map数据块大小', @application_id, '10', 'NumInterval', '[2,10]', '0', '1', '1'); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'hive.exec.reduce.bytes.per.reducer', '取值范围:2-10,单位:G', 'reduce处理的数据量', @application_id, '10', 'NumInterval', '[2,10]', '0', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'python.java.client.memory', '取值范围:1-2,单位:G', 'python引擎初始化内存大小', @application_id, '1', 'NumInterval', '[1,2]', '0', '0', '1'); +--变量: +SET @SPARK_LABEL="spark-2.4.3"; +SET @HIVE_LABEL="hive-1.2.1"; +SET @PYTHON_LABEL="python-2"; +SET @PIPELINE_LABEL="pipeline-*"; +SET @JDBC_LABEL="jdbc-4"; + +--衍生变量: +SET @SPARK_ALL=CONCAT('*-*,',@SPARK_LABEL); +SET @SPARK_IDE=CONCAT('*-IDE,',@SPARK_LABEL); +SET @SPARK_NODE=CONCAT('*-nodeexecution,',@SPARK_LABEL); +SET @SPARK_VISUALIS=CONCAT('*-Visualis,',@SPARK_LABEL); + +SET @HIVE_ALL=CONCAT('*-*,',@HIVE_LABEL); +SET @HIVE_IDE=CONCAT('*-IDE,',@HIVE_LABEL); +SET @HIVE_NODE=CONCAT('*-nodeexecution,',@HIVE_LABEL); + +SET @PYTHON_ALL=CONCAT('*-*,',@PYTHON_LABEL); +SET @PYTHON_IDE=CONCAT('*-IDE,',@PYTHON_LABEL); +SET @PYTHON_NODE=CONCAT('*-nodeexecution,',@PYTHON_LABEL); + +SET @PIPELINE_ALL=CONCAT('*-*,',@PIPELINE_LABEL); +SET @PIPELINE_IDE=CONCAT('*-IDE,',@PIPELINE_LABEL); + +SET @JDBC_ALL=CONCAT('*-*,',@JDBC_LABEL); +SET @JDBC_IDE=CONCAT('*-IDE,',@JDBC_LABEL); + + + +---- Configuration的默认Key +-- 全局设置 +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`) VALUES ('wds.linkis.rm.yarnqueue', 'yarn队列名', 'yarn队列名', 'default', 'None', NULL, '0', '0', '1', '队列资源'); +-- spark +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.instance.max', '取值范围:1-128,单位:个', 'yarn队列实例最大个数', '30', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.cores.max', '取值范围:1-500,单位:个', '队列CPU使用上限', '150', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|500)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.yarnqueue.memory.max', '取值范围:1-1000,单位:G', '队列内存使用上限', '300G', 'Regex', '^([1-9]\\d{0,2}|1000)(G|g)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', '2', 'NumInterval', '[1,40]', '0', '0', '2', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', '2', 'NumInterval', '[1,2]', '1', '0', '1','spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', '3', 'NumInterval', '[3,15]', '0', '0', '3', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数', '1', 'NumInterval', '[1,1]', '1', '1', '1', 'spark资源设置','spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小','2', 'NumInterval', '[1,15]', '0', '0', '1', 'spark资源设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.pd.addresses', NULL, NULL, 'pd0:2379', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.addr', NULL, NULL, 'tidb', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.password', NULL, NULL, NULL, 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.port', NULL, NULL, '4000', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.tispark.tidb.user', NULL, NULL, 'root', 'None', NULL, '0', '0', '1', 'tidb设置', 'spark'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('spark.python.version', '取值范围:python2,python3', 'python版本','python2', 'OFT', '[\"python3\",\"python2\"]', '0', '0', '1', 'spark引擎设置', 'spark'); +-- hive +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.client.memory', '取值范围:1-10,单位:G', 'hive引擎初始化内存大小','2', 'NumInterval', '[1,10]', '0', '0', '1', 'hive引擎设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.client.java.opts', 'hive客户端进程参数', 'hive引擎启动时jvm参数','', 'None', NULL, '1', '1', '1', 'hive引擎设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('mapred.reduce.tasks', '范围:1-20,单位:个', 'reduce数', '10', 'NumInterval', '[1,20]', '0', '1', '1', 'hive资源设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('dfs.block.size', '取值范围:2-10,单位:G', 'map数据块大小', '10', 'NumInterval', '[2,10]', '0', '1', '1', 'hive资源设置', 'hive'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('hive.exec.reduce.bytes.per.reducer', '取值范围:2-10,单位:G', 'reduce处理的数据量', '10', 'NumInterval', '[2,10]', '0', '1', '1', 'hive资源设置', 'hive'); +--python +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.memory.max', '取值范围:1-100,单位:G', '驱动器内存使用上限', '20G', 'Regex', '^([1-9]\\d{0,1}|100)(G|g)$', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.client.core.max', '取值范围:1-128,单位:个', '驱动器核心个数上限', '10', 'Regex', '^(?:[1-9]\\d?|[1234]\\d{2}|128)$', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.rm.instance', '范围:1-20,单位:个', '引擎最大并发数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '队列资源', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('python.java.client.memory', '取值范围:1-2,单位:G', 'python引擎初始化内存大小', '1', 'NumInterval', '[1,2]', '0', '0', '1', 'python引擎设置', 'python'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('python.version', '取值范围:python2,python3', 'python版本','python2', 'OFT', '[\"python3\",\"python2\"]', '0', '0', '1', 'python引擎设置', 'python'); +--pipeline +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.mold', '取值范围:csv或excel', '结果集导出类型','csv', 'OFT', '[\"csv\",\"excel\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.field.split', '取值范围:,或\\t', 'csv分隔符',',', 'OFT', '[\",\",\"\\\\t\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.charset', '取值范围:utf-8或gbk', '结果集导出字符集','gbk', 'OFT', '[\"utf-8\",\"gbk\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.isoverwtite', '取值范围:true或false', '是否覆写','true', 'OFT', '[\"true\",\"false\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.instance', '范围:1-3,单位:个', 'pipeline引擎最大并发数','3', 'NumInterval', '[1,3]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.engine.memory', '取值范围:1-10,单位:G', 'pipeline引擎初始化内存大小','2', 'NumInterval', '[1,10]', '0', '0', '1', 'pipeline资源设置', 'pipeline'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('pipeline.output.shuffle.null.type', '取值范围:NULL或者BLANK', '空值替换','NULL', 'OFT', '[\"NULL\",\"BLANK\"]', '0', '0', '1', 'pipeline引擎设置', 'pipeline'); +--jdbc +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.connect.url', '例如:jdbc:hive2://127.0.0.1:10000', 'jdbc连接地址', 'jdbc:hive2://127.0.0.1:10000', 'Regex', '^\s*jdbc:\w+://([^:]+)(:\d+)(/[^\?]+)?(\?\S*)?$', '0', '0', '1', '数据源配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.version', '取值范围:jdbc3,jdbc4', 'jdbc版本','jdbc4', 'OFT', '[\"jdbc3\",\"jdbc4\"]', '0', '0', '1', '数据源配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.username', 'username', '数据库连接用户名', '', '', '', '0', '0', '1', '用户配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.password', 'password', '数据库连接密码', '', '', '', '0', '0', '1', '用户配置', 'jdbc'); +INSERT INTO `linkis_configuration_config_key` (`key`, `description`, `name`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`, `treeName`, `engine_conn_type`) VALUES ('wds.linkis.jdbc.connect.max', '范围:1-20,单位:个', 'jdbc引擎最大连接数', '10', 'NumInterval', '[1,20]', '0', '0', '1', '数据源配置', 'jdbc'); +---- Configuration一级目录 +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-全局设置,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-IDE,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-Visualis,*-*', 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-nodeexecution,*-*', 'OPTIONAL', 2, now(), now()); + + +---- 引擎级别默认配置 +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PIPELINE_ALL, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@JDBC_ALL, 'OPTIONAL', 2, now(), now()); + + +---- Configuration二级目录(creator 级别的默认配置) +-- IDE +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PIPELINE_IDE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@JDBC_IDE, 'OPTIONAL', 2, now(), now()); + +-- Visualis +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_VISUALIS, 'OPTIONAL', 2, now(), now()); +-- nodeexecution +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@SPARK_NODE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@HIVE_NODE, 'OPTIONAL', 2, now(), now()); +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator',@PYTHON_NODE, 'OPTIONAL', 2, now(), now()); + + +-- 关联一级二级目录 +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-全局设置,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-IDE,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-Visualis,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = '*-nodeexecution,*-*'; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 1); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_IDE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_VISUALIS; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + +SELECT @label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_NODE; +INSERT INTO linkis_configuration_category (`label_id`, `level`) VALUES (@label_id, 2); + + +---- 关联label和默认配置 +-- 全局默认配置(此处的'*-*,*-*'与一级目录'*-全局设置,*-*'相同,真正查询全局设置的label时应当查询*-*,*-*,而不是*-全局设置,*-*) +INSERT INTO `linkis_manager_label` (`label_key`, `label_value`, `label_feature`, `label_value_size`, `update_time`, `create_time`) VALUES ('combined_engineType_userCreator','*-*,*-*', 'OPTIONAL', 2, now(), now()); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue' AND `engine_conn_type` IS NULL; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = '*-*,*-*'; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +-- spark默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.instance.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.cores.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.yarnqueue.memory.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'wds.linkis.instance', '范围:1-3,单位:个', 'spark引擎最大并发数', @application_id, '1', 'NumInterval', '[1,3]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.instances', '取值范围:1-40,单位:个', '执行器实例最大并发数', @application_id, '2', 'NumInterval', '[1,40]', '0', '0', '2'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.cores', '取值范围:1-8,单位:个', '执行器核心个数', @application_id, '2', 'NumInterval', '[1,2]', '1', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.executor.memory', '取值范围:3-15,单位:G', '执行器内存大小', @application_id, '3', 'NumInterval', '[3,15]', '0', '0', '3'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.cores', '取值范围:只能取1,单位:个', '驱动器核心个数 ', @application_id, '1', 'NumInterval', '[1,1]', '1', '1', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.driver.memory', '取值范围:1-15,单位:G', '驱动器内存大小', @application_id, '2', 'NumInterval', '[1,15]', '0', '0', '1'); - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'pipeline.output.mold', '取值范围:csv或excel', '结果集导出类型', @application_id, 'csv', 'OFT', '[csv,excel]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'pipeline.field.split', '取值范围:,或\\t', 'csv分隔符', @application_id, ',', 'OFT', '[\",\",\"\\\\t\"]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'pipeline.output.charset', '取值范围:utf-8或gbk', '结果集导出字符集', @application_id, 'gbk', 'OFT', '[utf-8,gbk]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'pipeline.output.isoverwtite', '取值范围:true或false', '是否覆写', @application_id, 'true', 'OFT', '[true,false]', '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'pipeline.engine.memory', '取值范围:1-10,单位:G', 'pipeline引擎初始化内存大小', @application_id, '2', 'NumInterval', '[1,10]', '0', '0', '1'); - - -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.pd.addresses', NULL, NULL, @application_id, 'pd0:2379', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.addr', NULL, NULL, @application_id, 'tidb', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.password', NULL, NULL, @application_id, NULL, 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.port', NULL, NULL, @application_id, '4000', 'None', NULL, '0', '0', '1'); -INSERT INTO `linkis_config_key` (`id`, `key`, `description`, `name`, `application_id`, `default_value`, `validate_type`, `validate_range`, `is_hidden`, `is_advanced`, `level`) VALUES (0, 'spark.tispark.tidb.user', NULL, NULL, @application_id, 'root', 'None', NULL, '0', '0', '1'); - - -#---------------------------------------全局设置------------------ +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue.cores.max'; -#SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.yarnqueue.memory.max'; -#SELECT @tree_id := id from linkis_config_tree WHERE `name` = '队列资源'; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.preheating.time'; -#SELECT @tree_id := id from linkis_config_tree WHERE `name` = '预热机制'; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.tmpfile.clean.time'; -#SELECT @tree_id := id from linkis_config_tree WHERE `name` = '清理机制'; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#SELECT @key_id := id from linkis_config_key WHERE `name` = '引擎最大并发数'; -#SELECT @tree_id := id from linkis_config_tree WHERE `name` = '引擎设置'; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.instances' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := id from linkis_config_key WHERE `key` = 'wds.linkis.client.memory.max'; -SELECT @tree_id := id from linkis_config_tree WHERE `name` = '驱动器资源'; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.cores' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#---------------------------------------spark--------------- +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.executor.memory' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.instances' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.driver.cores' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'spark引擎最大并发数' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark引擎设置' and a.name = 'spark' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.driver.memory' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.cores' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'spark.python.version' AND `engine_conn_type` = 'spark'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @SPARK_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.memory' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- hive默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.cores' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.memory' and a.name = 'IDE' ORDER BY k.id limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'spark' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -#---------------------------------------tidb------------------ +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.client.memory' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.instances' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'spark引擎最大并发数' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark引擎设置' and a.name = 'tidb' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.client.java.opts' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.cores' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'mapred.reduce.tasks' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.executor.memory' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'dfs.block.size' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.cores' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'hive.exec.reduce.bytes.per.reducer' AND `engine_conn_type` = 'hive'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @HIVE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id:=id from(SELECT k.id as 'id'from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.driver.memory' and a.name = 'IDE' ORDER BY k.id desc limit 1) as tmp; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'spark资源设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +-- python默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.memory.max' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.pd.addresses' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.client.core.max' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.addr' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.password' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.port' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'spark.tispark.tidb.user' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'tidb设置' and a.name = 'tidb' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#---------------------------hive----------------- -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'hive引擎最大并发数' and a.name = 'IDE' ; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive引擎设置' and a.name = 'hive' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.client.memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'mapred.reduce.tasks' and a.name = 'IDE'; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'dfs.block.size' and a.name = 'IDE' ; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.exec.reduce.bytes.per.reducer' and a.name = 'IDE' ; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'hive.client.java.opts' and a.name = 'IDE'; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'hive资源设置' and a.name = 'hive' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#------------------------python--------------------- - -#SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`name` = 'python引擎最大并发数' and a.name = 'IDE' ; -#SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'python引擎设置' and a.name = 'python' ; -#INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'python.java.client.memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = 'python资源设置' and a.name = 'python' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -#---------------------------pipeline----------------- -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'pipeline.output.mold' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = '导入导出设置' and a.name = 'pipeline' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'pipeline.field.split' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = '导入导出设置' and a.name = 'pipeline' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'pipeline.output.charset' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = '导入导出设置' and a.name = 'pipeline' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'pipeline.output.isoverwtite' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = '导入导出设置' and a.name = 'pipeline' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); - -SELECT @key_id := k.id from linkis_config_key k left join linkis_application a on k.application_id = a.id WHERE k.`key` = 'pipeline.engine.memory' and a.name = 'IDE' ; -SELECT @tree_id := t.id from linkis_config_tree t left join linkis_application a on t.application_id = a.id WHERE t.`name` = '导入导出资源设置' and a.name = 'pipeline' ; -INSERT INTO `linkis_config_key_tree` (`id`, `key_id`, `tree_id`) VALUES (0, @key_id, @tree_id); \ No newline at end of file +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.rm.instance' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'python.java.client.memory' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'python.version' AND `engine_conn_type` = 'python'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PYTHON_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +-- pipeline默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.mold' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.field.split' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.charset' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.isoverwtite' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.engine.memory' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'pipeline.output.shuffle.null.type' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.instance' AND `engine_conn_type` = 'pipeline'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @PIPELINE_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +-- jdbc默认配置 +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.connect.url' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.version' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.username' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.password' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); + +SELECT @configkey_id := id from linkis_configuration_config_key WHERE `key` = 'wds.linkis.jdbc.connect.max' AND `engine_conn_type` = 'jdbc'; +SELECT @config_label_id := id from linkis_manager_label WHERE `label_value` = @JDBC_ALL; +INSERT INTO `linkis_configuration_config_value` (`configkey_id`, `config_value`, `config_label_id`) VALUES (@configkey_id, '', @config_label_id); diff --git a/db/module/linkis_ecp.sql b/db/module/linkis_ecp.sql new file mode 100644 index 0000000000..c310c37a3b --- /dev/null +++ b/db/module/linkis_ecp.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS `linkis_engine_conn_plugin_bml_resources`; +CREATE TABLE `linkis_engine_conn_plugin_bml_resources` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `engine_conn_type` varchar(100) NOT NULL COMMENT '引擎类型', + `version` varchar(100) COMMENT '版本', + `file_name` varchar(255) COMMENT '文件名', + `file_size` bigint(20) DEFAULT 0 NOT NULL COMMENT '文件大小', + `last_modified` bigint(20) COMMENT '文件更新时间', + `bml_resource_id` varchar(100) NOT NULL COMMENT '所属系统', + `bml_resource_version` varchar(200) NOT NULL COMMENT '资源所属者', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `last_update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; \ No newline at end of file diff --git a/db/module/linkis_instance_label.sql b/db/module/linkis_instance_label.sql new file mode 100644 index 0000000000..cdf8f8a1d2 --- /dev/null +++ b/db/module/linkis_instance_label.sql @@ -0,0 +1,42 @@ +CREATE TABLE `linkis_instance_label` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_key` varchar(32) COLLATE utf8_bin NOT NULL COMMENT 'string key', + `label_value` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'string value', + `label_feature` varchar(16) COLLATE utf8_bin NOT NULL COMMENT 'store the feature of label, but it may be redundant', + `label_value_size` int(20) NOT NULL COMMENT 'size of key -> value map', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + PRIMARY KEY (`id`), + UNIQUE KEY `label_key_value` (`label_key`,`label_value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +CREATE TABLE `linkis_instance_label_value_relation` ( + `label_value_key` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'value key', + `label_value_content` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'value content', + `label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_instance_label -> id', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + UNIQUE KEY `label_value_key_label_id` (`label_value_key`,`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +CREATE TABLE `linkis_instance_label_relation` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_instance_label -> id', + `service_instance` varchar(64) NOT NULL COLLATE utf8_bin COMMENT 'structure like ${host|machine}:${port}', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +CREATE TABLE `linkis_instance_info` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `instance` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT 'structure like ${host|machine}:${port}', + `name` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT 'equal application name in registry', + `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp', + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp', + PRIMARY KEY (`id`), + UNIQUE KEY `instance` (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + + diff --git a/db/module/linkis_manager.sql b/db/module/linkis_manager.sql new file mode 100644 index 0000000000..255a04d1ad --- /dev/null +++ b/db/module/linkis_manager.sql @@ -0,0 +1,151 @@ +DROP TABLE IF EXISTS `linkis_manager_service_instance`; + +CREATE TABLE `linkis_manager_service_instance` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `name` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `owner` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `mark` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `updator` varchar(32) COLLATE utf8_bin DEFAULT NULL, + `creator` varchar(32) COLLATE utf8_bin DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `instance` (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_linkis_resources`; + +CREATE TABLE `linkis_manager_linkis_resources` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `max_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `min_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `used_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `left_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `expected_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `locked_resource` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `resourceType` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `ticketId` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `updator` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `creator` varchar(255) COLLATE utf8_bin DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_lock`; + +CREATE TABLE `linkis_manager_lock` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `lock_object` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `time_out` longtext COLLATE utf8_bin, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_external_resource_provider`; +CREATE TABLE `linkis_external_resource_provider` ( + `id` int(10) NOT NULL AUTO_INCREMENT, + `resource_type` varchar(32) NOT NULL, + `name` varchar(32) NOT NULL, + `labels` varchar(32) DEFAULT NULL, + `config` text NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +DROP TABLE IF EXISTS `linkis_manager_engine_em`; +CREATE TABLE `linkis_manager_engine_em` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `engine_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `em_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_label`; + +CREATE TABLE `linkis_manager_label` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_key` varchar(32) COLLATE utf8_bin NOT NULL, + `label_value` varchar(255) COLLATE utf8_bin NOT NULL, + `label_feature` varchar(16) COLLATE utf8_bin NOT NULL, + `label_value_size` int(20) NOT NULL, + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `label_key_value` (`label_key`,`label_value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_label_value_relation`; + +CREATE TABLE `linkis_manager_label_value_relation` ( + `label_value_key` varchar(255) COLLATE utf8_bin NOT NULL, + `label_value_content` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `label_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `label_value_key_label_id` (`label_value_key`,`label_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_label_resource`; +CREATE TABLE `linkis_manager_label_resource` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL, + `resource_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_manager_label_service_instance`; +CREATE TABLE `linkis_manager_label_service_instance` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `label_id` int(20) DEFAULT NULL, + `service_instance` varchar(64) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_manager_label_user`; +CREATE TABLE `linkis_manager_label_user` ( + `id` int(20) NOT NULL AUTO_INCREMENT, + `username` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `label_id` int(20) DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + + +DROP TABLE IF EXISTS `linkis_manager_metrics_history`; + +CREATE TABLE `linkis_manager_metrics_history` ( + `instance_status` int(20) DEFAULT NULL, + `overload` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `heartbeat_msg` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `healthy_status` int(20) DEFAULT NULL, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + `creator` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `ticketID` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `serviceName` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `instance` varchar(255) COLLATE utf8_bin DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; + +DROP TABLE IF EXISTS `linkis_manager_service_instance_metrics`; + +CREATE TABLE `linkis_manager_service_instance_metrics` ( + `instance` varchar(32) COLLATE utf8_bin NOT NULL, + `instance_status` int(11) DEFAULT NULL, + `overload` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `heartbeat_msg` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `healthy_status` varchar(255) COLLATE utf8_bin DEFAULT NULL, + `update_time` datetime DEFAULT CURRENT_TIMESTAMP, + `create_time` datetime DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; diff --git a/db/module/linkis_query.sql b/db/module/linkis_query.sql index 1262fba7b8..af76c6bc79 100644 --- a/db/module/linkis_query.sql +++ b/db/module/linkis_query.sql @@ -9,22 +9,25 @@ CREATE TABLE `linkis_task` ( `instance` varchar(50) DEFAULT NULL COMMENT 'An instance of Entrance, consists of IP address of the entrance server and port', `exec_id` varchar(50) DEFAULT NULL COMMENT 'execution ID, consists of jobID(generated by scheduler), executeApplicationName , creator and instance', `um_user` varchar(50) DEFAULT NULL COMMENT 'User name', + `submit_user` varchar(50) DEFAULT NULL COMMENT 'submitUser name', `execution_code` text COMMENT 'Run script. When exceeding 6000 lines, script would be stored in HDFS and its file path would be stored in database', `progress` float DEFAULT NULL COMMENT 'Script execution progress, between zero and one', `log_path` varchar(200) DEFAULT NULL COMMENT 'File path of the log files', `result_location` varchar(200) DEFAULT NULL COMMENT 'File path of the result', - `status` varchar(50) DEFAULT NULL COMMENT 'Script execution status, must be one of the following: Inited, WaitForRetry, Scheduled, Running, Succeed, Failed, Cancelled, Timeout', + `status` varchar(50) DEFAULT NULL COMMENT 'Script execution status, must be one of the following: Inited, WaitForRetry, Scheduled, Running, Succeed, Failed, Cancelled, Timeout', `created_time` datetime DEFAULT NULL COMMENT 'Creation time', `updated_time` datetime DEFAULT NULL COMMENT 'Update time', `run_type` varchar(50) DEFAULT NULL COMMENT 'Further refinement of execution_application_time, e.g, specifying whether to run pySpark or SparkR', `err_code` int(11) DEFAULT NULL COMMENT 'Error code. Generated when the execution of the script fails', - `err_desc` text COMMENT 'Execution description. Generated when the execution of script fails', + `err_desc` text COMMENT 'Execution description. Generated when the execution of script fails', `execute_application_name` varchar(200) DEFAULT NULL COMMENT 'The service a user selects, e.g, Spark, Python, R, etc', `request_application_name` varchar(200) DEFAULT NULL COMMENT 'Parameter name for creator', `script_path` varchar(200) DEFAULT NULL COMMENT 'Path of the script in workspace', - `params` text COMMENT 'Configuration item of the parameters', + `params` text COMMENT 'Configuration item of the parameters', `engine_instance` varchar(50) DEFAULT NULL COMMENT 'An instance of engine, consists of IP address of the engine server and port', + `task_resource` varchar(1024) DEFAULT NULL, `engine_start_time` time DEFAULT NULL, + `label_json` varchar(200) DEFAULT NULL COMMENT 'label json', PRIMARY KEY (`id`), KEY `created_time` (`created_time`), KEY `um_user` (`um_user`) diff --git a/docs/zh_CN/README.md b/docs/zh_CN/README.md deleted file mode 100644 index e4f330a13c..0000000000 --- a/docs/zh_CN/README.md +++ /dev/null @@ -1,141 +0,0 @@ -Linkis -============ - -[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) - -[English](../../README.md) | 中文 - -# 引言: - -Linkis是一个打通了多个计算存储引擎如:Spark、TiSpark、Hive、Python和HBase等,对外提供统一REST/WebSocket/JDBC接口,提交执行SQL、Pyspark、HiveQL、Scala等脚本的计算中间件。 - -Linkis基于微服务架构,提供了金融级多租户隔离、资源管控、权限隔离等企业级特性,支持统一变量、UDF、函数、用户资源文件管理,具备高并发、高性能、高可用的大数据作业/请求全生命周期管理能力。 - - -![Linkis效果图](images/ch3/解决方案.jpg) - - - -基于Linkis计算中间件的架构设计理念,我们在上层构建了很多的应用系统。目前已开源的有: -- [**DataSphere Studio - 数据应用开发管理门户**](https://github.com/WeBankFinTech/DataSphereStudio) -- [**Qualitis - 数据质量工具**](https://github.com/WeBankFinTech/Qualitis) -- [**Scriptis - 数据研发IDE工具**](https://github.com/WeBankFinTech/Scriptis) -- [**Visualis - 数据可视化工具**](https://github.com/WeBankFinTech/Visualis) - -更多工具准备开源中,敬请期待! - ----- - -# 核心特点: - -- **统一作业执行服务**:一个分布式的REST/WebSocket服务,用于接收用户提交的各种脚本请求。 - - **目前支持的计算引擎有**:Spark、Python、TiSpark、Hive和Shell等。 - - **支持的脚本语言有**:SparkSQL、Spark Scala、Pyspark、R、Python、HQL和Shell等; - - - -- **资源管理服务**: 支持实时管控每个系统和用户的资源使用情况,限制系统和用户的资源使用量和并发数,并提供实时的资源动态图表,方便查看和管理系统和用户的资源; - - **目前已支持的资源类型**:Yarn队列资源、服务器(CPU和内存)、用户并发个数等。 - - - -- **应用管理服务**:管理所有系统的所有用户应用,包括离线批量应用、交互式查询应用和实时流式应用,为离线和交互式应用提供强大的复用能力,并提供应用全生命周期管理,自动释放用户多余的空闲应用; - - - -- **统一存储服务**:通用的IO架构,能快速对接各种存储系统,提供统一调用入口,支持所有常用格式数据,集成度高,简单易用; - - - -- **统一上下文服务**:统一用户和系统资源文件(JAR、ZIP、Properties等),用户、系统、计算引擎的参数和变量统一管理,一处设置,处处自动引用; - - - -- **物料库**:系统和用户级物料管理,可分享和流转,支持全生命周期自动管理; - - - -- **元数据服务**:实时的库表结构和分区情况展示。 - -## 与类似系统的对比: - -Linkis跟Apache Livy和Apache Zeppelin Interpreter的定位不一样,但是由于开源社区目前尚没有同类竞品,所以这里做一个简单对比供大家参考。 - -![comparison_table](images/introduction/comparison_table.png) - - - ----- - -# 文档列表 - -[Linkis快速安装使用文档](https://github.com/WeBankFinTech/Linkis/wiki/%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8Linkis) - -[上层前端应用的HTTP接入文档](https://github.com/WeBankFinTech/Linkis/wiki/%E4%B8%8A%E5%B1%82%E5%89%8D%E7%AB%AF%E5%BA%94%E7%94%A8HTTP%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3) - -[上层前端应用的WebSocket接入文档](https://github.com/WeBankFinTech/Linkis/wiki/%E4%B8%8A%E5%B1%82%E5%89%8D%E7%AB%AF%E5%BA%94%E7%94%A8WebSocket%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3) - -[Linkis架构文档](https://github.com/WeBankFinTech/Linkis/wiki/%E6%80%BB%E4%BD%93%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1%E4%BB%8B%E7%BB%8D) - -**更多文档,请[点我访问](https://github.com/WeBankFinTech/Linkis/wiki)** - - ----- - -# Architecture: - -![introduction_new](images/introduction/introduction_new.png) - ----- - -# RoadMap - -### 1. Linkis管理台 - -- 用户可以查看和管理自己的Job -- 用户可以查看和管理自己的引擎 -- 用户可以查看Yarn的资源使用情况和用户资源使用排名 -- 用户可以配置引擎的启动参数 -- 用户可以设置变量 - -### 2. 支持标签功能 - -- 支持给EngineManager打标签 -- 启动引擎时,支持为引擎打标签 -- 支持通过标签访问目标引擎 - -### 3. AppGovernance应用治理实现 - -- 系统级、用户级应用全生命周期管理,包括离线批量、交互式查询和实时流式应用 -- 为离线和交互式应用提供复用能力和智能切换能力 -- 智能限流、应用智能保护 - -### 4. 支持Flink和Spark Structured Streaming - - - - -**如果您有任何需求,欢迎给我们提issue,我们将会及时给您回复。** - ----- - -# Contributing - -非常欢迎广大的社区伙伴给我们贡献新引擎和代码! - ----- - -# Communication - -如果您想得到最快的响应,请给我们提issue,或者您也可以扫码进群: - -![introduction05](images/introduction/introduction05.png) - ----- - -# License - -**Linkis is under the Apache 2.0 license. See the [LICENSE](/LICENSE) file for details.** diff --git a/docs/zh_CN/SUMMARY.md b/docs/zh_CN/SUMMARY.md index 391a4e1e36..dca2f1fdc1 100644 --- a/docs/zh_CN/SUMMARY.md +++ b/docs/zh_CN/SUMMARY.md @@ -1,16 +1,8 @@ # Summary -* [Introduction](README.md) * [系统部署文档](ch1/deploy.md) * [快速使用文档](ch2/linkis快速使用文档.md) * [系统使用手册](ch3/linkis使用文档.md) -* [架构设计]() +* 架构设计 * [UJES架构设计](ch4/Linkis-UJES设计文档.md) - * [RM架构设计](ch4/Linkis-RM设计文档.md) - * [AM架构设计]() -* [开发文档]() -* [FAQ]() -* [版本升级文档]() -* [历次版本发布内容]() - - + * [RM架构设计](ch4/Linkis-RM设计文档.md) \ No newline at end of file diff --git a/emr-base/Dockerfile b/emr-base/Dockerfile deleted file mode 100644 index c42b7315b3..0000000000 --- a/emr-base/Dockerfile +++ /dev/null @@ -1,73 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM centos:latest -MAINTAINER wedatasphere@webank.com - -RUN yum -y install wget tar && \ - mkdir /opt/{flink,hadoop,spark,hive} - -WORKDIR /tmp - -RUN wget -O jdk-8u221-linux-x64.tar.gz \ - -c --content-disposition \ - "https://javadl.oracle.com/webapps/download/AutoDL?BundleId=239835_230deb18db3e4014bb8e3e8324f81b43" && \ - wget "https://archive.apache.org/dist/flink/flink-1.7.2/flink-1.7.2-bin-hadoop27-scala_2.11.tgz" && \ - wget "https://downloads.lightbend.com/scala/2.11.8/scala-2.11.8.tgz" && \ - wget "http://archive.apache.org/dist/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz" && \ - wget "http://archive.apache.org/dist/hive/hive-2.3.6/apache-hive-2.3.6-bin.tar.gz" && \ - wget "http://archive.apache.org/dist/hadoop/common/hadoop-2.7.7/hadoop-2.7.7.tar.gz" - - -#COPY flink-1.7.2-bin-hadoop27-scala_2.11.tgz . -#COPY scala-2.11.8.tgz . -#COPY jdk-8u221-linux-x64.tar.gz . -#COPY hadoop-2.7.7.tar.gz . -#COPY spark-2.4.4-bin-hadoop2.7.tgz . -#COPY apache-hive-2.3.6-bin.tar.gz . - -RUN tar xf flink-1.7.2-bin-hadoop27-scala_2.11.tgz -C /opt/flink/ && \ - tar xf scala-2.11.8.tgz -C /usr/local/ && \ - tar xf jdk-8u221-linux-x64.tar.gz -C /usr/local/ && \ - tar xf hadoop-2.7.7.tar.gz -C /opt/hadoop/ && \ - tar xf spark-2.4.4-bin-hadoop2.7.tgz -C /opt/spark/ && \ - tar xf apache-hive-2.3.6-bin.tar.gz -C /opt/hive/ && \ - rm -f *.tgz *.tar.gz - -#COPY hive/conf /opt/hive/apache-hive-2.3.6-bin/conf -#COPY hadoop/conf /opt/hadoop/hadoop-2.7.7/etc/hadoop -#COPY jdk-8u221-linux-x64.tar.gz /tmp -#COPY scala-2.11.8.tgz /tmp -#COPY spark-2.4.4-bin-hadoop2.7.tgz /tmp -# -#RUN tar xf jdk-8u221-linux-x64.tar.gz -C /usr/local/ && \ -# tar xf scala-2.11.8.tgz -C /usr/local/ && \ -# tar xf spark-2.4.4-bin-hadoop2.7.tgz -C /opt/spark/ && \ -# rm -f *.tgz *.tar.gz - -ENV TIME_ZONE Asia/Shanghai -ENV SPARK_HOME=/opt/spark/spark-2.4.4-bin-hadoop2.7 -ENV SPARK_CONF_DIR=$SPARK_HOME/conf -ENV PYSPARK_ALLOW_INSECURE_GATEWAY=1 -ENV HIVE_HOME=/opt/hive/apache-hive-2.3.6-bin -ENV FLINK_HOME=/opt/flink/flink-1.7.2 -ENV HIVE_CONF_DIR=$HIVE_HOME/conf -ENV SCALA_HOME=/usr/local/scala-2.11.8 -ENV HADOOP_HOME=/opt/hadoop/hadoop-2.7.7 -ENV HADOOP_CONF_PATH=$HADOOP_HOME/etc/hadoop -ENV HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop -ENV JAVA_HOME /usr/local/jdk1.8.0_221 -ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar -ENV PATH ${JAVA_HOME}/bin/:${SPARK_HOME}/bin:${HIVE_HOME}/bin:${SCALA_HOME}/bin:${FLINK_HOME}/bin:${HADOOP_HOME}/sbin:${HADOOP_HOME}/bin:$PATH \ No newline at end of file diff --git a/emr-base/README.md b/emr-base/README.md deleted file mode 100644 index ff758fdb6e..0000000000 --- a/emr-base/README.md +++ /dev/null @@ -1,4 +0,0 @@ -该目录下放入jdk,scala,spark二进制压缩包编译基础镜像使用,其他linkis module都是基于基础镜像做扩展 -spark需要二进制包,因为spark-engine调用了spark-submit脚本 - -hadoop,hive 配置文件core-site.xml,hdfs-sit.xml,hive-site.xml等也放在同一级目录hive/conf,hadoop/conf,按Dockerfile的指定层级 \ No newline at end of file diff --git a/eurekaServer/bin/start-eureka.sh b/eurekaServer/bin/start-eureka.sh deleted file mode 100755 index fd70203b43..0000000000 --- a/eurekaServer/bin/start-eureka.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export EUREKA_SERVER_PID=$HOME/bin/linkis.pid - -if [[ -f "${EUREKA_SERVER_PID}" ]]; then - pid=$(cat ${EUREKA_SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "EUREKA_SERVER Remote Server is already running." - exit 1 - fi -fi - -export EUREKA_SERVER_LOG_PATH=$HOME/logs -export EUREKA_SERVER_HEAP_SIZE="512M" -export EUREKA_SERVER_CLASS=${EUREKA_SERVER_CLASS:-com.webank.wedatasphere.linkis.eureka.SpringCloudEurekaApplication} - -profiles='eureka' -if [ $1 ];then - type=$1 -fi - -export EUREKA_SERVER_JAVA_OPTS=" -Xmx$EUREKA_SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-gc.log" - -java $EUREKA_SERVER_JAVA_OPTS -cp $HOME/conf:$HOME/lib/* $EUREKA_SERVER_CLASS --spring.profiles.active=$profiles 2>&1 > $EUREKA_SERVER_LOG_PATH/linkis.out & -pid=$! -sleep 2 -if [[ -z "${pid}" ]]; then - echo "EUREKA SERVER start failed!" - exit 1 -else - echo "EUREKA SERVER start succeed!" - echo $pid > $EUREKA_SERVER_PID -fi diff --git a/eurekaServer/bin/stop-eureka.sh b/eurekaServer/bin/stop-eureka.sh deleted file mode 100755 index f032887111..0000000000 --- a/eurekaServer/bin/stop-eureka.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/eurekaServer/pom.xml b/eurekaServer/pom.xml deleted file mode 100644 index 513b43a833..0000000000 --- a/eurekaServer/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../pom.xml - - - linkis-eureka-server - 4.0.0 - jar - - - - org.springframework.cloud - spring-cloud-starter - - - org.springframework.boot - spring-boot-starter - - - - - org.springframework.cloud - spring-cloud-starter-eureka-server - ${spring.eureka.version} - - - hibernate-validator - org.hibernate.validator - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - src/main/assembly/distribution.xml - - - - - - false - eureka - false - false - - src/main/assembly/distribution.xml - - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - \ No newline at end of file diff --git a/eurekaServer/src/main/assembly/distribution.xml b/eurekaServer/src/main/assembly/distribution.xml deleted file mode 100644 index 6e9cb5c1f5..0000000000 --- a/eurekaServer/src/main/assembly/distribution.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - eurekaServer - - zip - - true - eureka - - - - - - lib - true - true - false - true - true - - - - - - ${basedir}/src/main/resources - - * - - 0777 - conf - unix - - - ${basedir}/bin - - * - - 0777 - bin - unix - - - . - - */** - - logs - - - - - diff --git a/extensions/spark-excel/pom.xml b/extensions/spark-excel/pom.xml deleted file mode 100644 index dd2e4af8a9..0000000000 --- a/extensions/spark-excel/pom.xml +++ /dev/null @@ -1,190 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - 4.0.0 - - com.webank.weDataSphere - spark-excel_2.11 - - - UTF-8 - UTF-8 - 1.7 - 3.3.3 - 2.11.7 - 2.11 - 2.1.0 - 2.7.2 - 0.8.2.0 - 1.7.12 - 1.2.2 - 2.7.0 - 1.1.2 - 1.2.17 - 3.2.11 - 12.0.1 - provided - provided - - - - - com.webank.wedatasphere.linkis - linkis-common - provided - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - org.apache.poi - poi-ooxml - 3.17 - - - com.norbitltd - spoiwo_${scala.compat.version} - 1.2.0 - - - com.monitorjbl - xlsx-streamer - 1.2.1 - - - org.apache.poi - ooxml-schemas - - - - - com.fasterxml.jackson.module - jackson-module-scala_${scala.compat.version} - 2.8.8 - ${spark-scope} - - - org.scalatest - scalatest_${scala.compat.version} - 3.0.1 - ${spark-scope} - - - org.scalacheck - scalacheck_${scala.compat.version} - 1.13.4 - ${spark-scope} - - - com.github.alexarchambault - scalacheck-shapeless_1.13_${scala.compat.version} - 1.1.6 - ${spark-scope} - - - com.holdenkarau - spark-testing-base_${scala.compat.version} - 2.1.0_0.9.0 - ${spark-scope} - - - org.scalamock - scalamock-scalatest-support_${scala.compat.version} - 3.5.0 - ${spark-scope} - - - - org.apache.spark - spark-core_${scala.compat.version} - ${spark.version} - ${spark-scope} - - - - org.apache.spark - spark-sql_${scala.compat.version} - ${spark.version} - ${spark-scope} - - - - org.apache.hadoop - hadoop-hdfs - ${hadoop.version} - ${spark-scope} - - - servlet-api - javax.servlet - - - com.google.guava - guava - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - ${java.version} - ${java.version} - UTF-8 - - - - net.alchim31.maven - scala-maven-plugin - 3.2.2 - - incremental - - -target:jvm-${java.version} - - - -source - ${java.version} - -target - ${java.version} - - - - - process-resources - - compile - - - - scala-test-compile - process-test-resources - - testCompile - - - - - - - - \ No newline at end of file diff --git a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/DefaultSource15.scala b/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/DefaultSource15.scala deleted file mode 100644 index 27d04ef709..0000000000 --- a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/DefaultSource15.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.webank.wedatasphere.spark.excel - -import org.apache.spark.sql.sources.DataSourceRegister - -class DefaultSource15 extends DefaultSource with DataSourceRegister { - override def shortName(): String = "excel" -} diff --git a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/ExcelFileSaver.scala b/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/ExcelFileSaver.scala deleted file mode 100644 index 5e0ddd14a9..0000000000 --- a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/ExcelFileSaver.scala +++ /dev/null @@ -1,146 +0,0 @@ -package com.webank.wedatasphere.spark.excel - -import java.io.{BufferedOutputStream, OutputStream} -import java.text.SimpleDateFormat -import java.util.Date - -import org.apache.hadoop.fs.{FileSystem, Path} -import org.apache.poi.ss.usermodel.IndexedColors -import org.apache.poi.xssf.streaming.SXSSFWorkbook -import org.apache.poi.ss.usermodel._ -import org.apache.spark.sql.DataFrame - -import scala.language.postfixOps - -object ExcelFileSaver { - final val DEFAULT_SHEET_NAME = "Sheet1" - final val DEFAULT_DATE_FORMAT = "yyyy-MM-dd" - final val DEFAULT_TIMESTAMP_FORMAT = "yyyy-mm-dd hh:mm:ss.000" -} - -class ExcelFileSaver(fs: FileSystem) { - - import ExcelFileSaver._ - - def save( - location: Path, - dataFrame: DataFrame, - sheetName: String = DEFAULT_SHEET_NAME, - useHeader: Boolean = true, - dateFormat: String = DEFAULT_DATE_FORMAT, - timestampFormat: String = DEFAULT_TIMESTAMP_FORMAT - ): Unit = { - fs.setVerifyChecksum(false) - val headerRow = dataFrame.schema.map(_.name) - val dataRows = dataFrame.toLocalIterator() - val excelWriter = new ExcelWriter(sheetName, dateFormat, timestampFormat) - if (useHeader) excelWriter.writeHead(headerRow) - while (dataRows.hasNext) { - val line = dataRows.next().toSeq - excelWriter.writerRow(line) - } - excelWriter.close(new BufferedOutputStream(fs.create(location))) - } - - def autoClose[A <: AutoCloseable, B](closeable: A)(fun: (A) => B): B = { - try { - fun(closeable) - } finally { - closeable.close() - } - } - - -} - -class ExcelWriter(sheetName: String, dateFormat: String, timestampFormat: String) { - - - val wb = new SXSSFWorkbook(100) - val sheet = wb.createSheet(sheetName) - val df = new SimpleDateFormat(dateFormat) - val tf = new SimpleDateFormat(timestampFormat) - val createHelper = wb.getCreationHelper - val sdf = wb.createCellStyle() - sdf.setDataFormat(createHelper.createDataFormat().getFormat(dateFormat)) - val stf = wb.createCellStyle() - stf.setDataFormat(createHelper.createDataFormat().getFormat(timestampFormat)) - - var rowNum = 0 - var columnsLen = 0 - - def writeHead(headRow: Seq[String]): Unit = { - columnsLen = headRow.length - //设置header的格式 - val headerFont = wb.createFont() - headerFont.setBold(true) - headerFont.setFontHeightInPoints(14) - headerFont.setColor(IndexedColors.RED.getIndex()) - val headerCellStyle = wb.createCellStyle() - headerCellStyle.setFont(headerFont) - val row = sheet.createRow(rowNum) - for (i <- headRow.indices) { - createCell(row, i, headRow(i), headerCellStyle) - } - rowNum = rowNum + 1 - } - - def writerRow(line: Seq[Any]): Unit = { - val row = sheet.createRow(rowNum) - for (i <- line.indices) { - createCell(row, i, line(i)) - } - rowNum = rowNum + 1 - } - - def createCell(row: Row, col: Int, value: String, cellStyle: CellStyle): Unit = { - val cell = row.createCell(col) - cell.setCellValue(value) - cell.setCellStyle(cellStyle) - } - - def setDateValue(cell:Cell, date: Date): Unit ={ - cell.setCellStyle(sdf) - cell.setCellValue(date) - } - def setTimestampValue(cell:Cell, date: Date): Unit ={ - cell.setCellStyle(stf) - cell.setCellValue(date) - } - - def createCell(row: Row, col: Int, value: Any): Unit = { - val cell = row.createCell(col) - value match { - case t: java.sql.Timestamp => setTimestampValue(cell, new Date(t.getTime)) - case d: java.sql.Date => setDateValue(cell, new Date(d.getTime)) - case s: String => cell.setCellValue(s) - case f: Float => cell.setCellValue(f) - case d: Double => cell.setCellValue(d) - case b: Boolean => cell.setCellValue(b) - case b: Byte => cell.setCellValue(b) - case s: Short => cell.setCellValue(s) - case i: Int => cell.setCellValue(i) - case l: Long => cell.setCellValue(l) - case b: BigDecimal => cell.setCellValue(b.doubleValue()) - case b: java.math.BigDecimal => cell.setCellValue(b.doubleValue()) - case null => cell.setCellValue("NULL") - case _ => cell.setCellValue(value.toString) - } - } - - def close(outputStream: OutputStream): Unit = { - try { - sheet.trackAllColumnsForAutoSizing() - for (i <- 0 until columnsLen) { - sheet.autoSizeColumn(i) - } - wb.write(outputStream); - } catch { - case e: Throwable => - throw e - } finally { - outputStream.close() - wb.close() - } - } -} diff --git a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/package.scala b/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/package.scala deleted file mode 100644 index d9e3733af6..0000000000 --- a/extensions/spark-excel/src/main/scala/com/webank/wedatasphere/spark/excel/package.scala +++ /dev/null @@ -1,30 +0,0 @@ -package com.webank.wedatasphere.spark - -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy -import org.apache.poi.ss.usermodel.{Cell, Row} - -package object excel { - - implicit class RichRow(val row: Row) extends AnyVal { - - def eachCellIterator(startColumn: Int, endColumn: Int): Iterator[Option[Cell]] = new Iterator[Option[Cell]] { - private val lastCellInclusive = row.getLastCellNum - 1 - private val endCol = Math.min(endColumn, Math.max(startColumn, lastCellInclusive)) - require(startColumn >= 0 && startColumn <= endCol) - - private var nextCol = startColumn - - override def hasNext: Boolean = nextCol <= endCol && nextCol <= lastCellInclusive - - override def next(): Option[Cell] = { - val next = - if (nextCol > endCol) throw new NoSuchElementException(s"column index = $nextCol") - else Option(row.getCell(nextCol, MissingCellPolicy.RETURN_NULL_AND_BLANK)) - nextCol += 1 - next - } - } - - } - -} diff --git a/gateway/core/pom.xml b/gateway/core/pom.xml deleted file mode 100644 index 0bc8ed2bfc..0000000000 --- a/gateway/core/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - - 4.0.0 - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - linkis-gateway-core - - - - com.webank.wedatasphere.linkis - linkis-cloudRPC - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-jetty - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-webapp - - - websocket-server - org.eclipse.jetty.websocket - - - io.netty - netty-all - - - json4s-jackson_2.11 - org.json4s - - - - - org.eclipse.jetty.websocket - websocket-client - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-servlet - ${jetty.version} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - **/*.yml - **/*.properties - **/*.sh - - true - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - diff --git a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/ProxyUserUtils.scala b/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/ProxyUserUtils.scala deleted file mode 100644 index c223ebe793..0000000000 --- a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/ProxyUserUtils.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.security - -import java.util.Properties -import java.util.concurrent.TimeUnit - -import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} -import com.webank.wedatasphere.linkis.gateway.config.GatewayConfiguration._ -import org.apache.commons.lang.StringUtils - -object ProxyUserUtils extends Logging { - - private val props = new Properties - if(ENABLE_PROXY_USER.getValue){ - Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { - override def run(): Unit = { - info("loading proxy users.") - val newProps = new Properties - newProps.load(this.getClass.getResourceAsStream(PROXY_USER_CONFIG.getValue)) - props.clear() - props.putAll(newProps) - } - }, 0, PROXY_USER_SCAN_INTERVAL.getValue, TimeUnit.MILLISECONDS) - } - - def getProxyUser(umUser: String): String = if(ENABLE_PROXY_USER.getValue) { - val proxyUser = props.getProperty(umUser) - if(StringUtils.isBlank(proxyUser)) umUser else { - info(s"switched to proxy user $proxyUser for umUser $umUser.") - proxyUser - } - } else umUser - -} diff --git a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/SecurityFilter.scala b/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/SecurityFilter.scala deleted file mode 100644 index 0011fb8aa2..0000000000 --- a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/SecurityFilter.scala +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.security - -import java.text.DateFormat -import java.util.{Date, Locale} - -import com.webank.wedatasphere.linkis.common.conf.Configuration -import com.webank.wedatasphere.linkis.common.exception.DWCException -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.gateway.config.GatewayConfiguration -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext -import com.webank.wedatasphere.linkis.gateway.security.sso.SSOInterceptor -import com.webank.wedatasphere.linkis.gateway.security.token.TokenAuthentication -import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration -import com.webank.wedatasphere.linkis.server.exception.{LoginExpireException, NonLoginException} -import com.webank.wedatasphere.linkis.server.{Message, validateFailed} -import org.apache.commons.lang.StringUtils -import org.apache.commons.lang.exception.ExceptionUtils - -/** - * created by cooperyang on 2019/1/9. - */ -object SecurityFilter { - - private val refererValidate = ServerConfiguration.BDP_SERVER_SECURITY_REFERER_VALIDATE.getValue - private val localAddress = ServerConfiguration.BDP_SERVER_ADDRESS.getValue - protected val testUser: String = ServerConfiguration.BDP_TEST_USER.getValue - - private var userRestful: UserRestful = _ - def setUserRestful(userRestful: UserRestful): Unit = this.userRestful = userRestful - - def filterResponse(gatewayContext: GatewayContext, message: Message): Unit = { - gatewayContext.getResponse.setStatus(Message.messageToHttpStatus(message)) - gatewayContext.getResponse.write(message) - gatewayContext.getResponse.sendResponse() - } - - def doFilter(gatewayContext: GatewayContext): Boolean = { - addAccessHeaders(gatewayContext) - if(refererValidate) { - //Security certification support, referer limited(安全认证支持,referer限定) - val referer = gatewayContext.getRequest.getHeaders.get("Referer") - if(referer != null && referer.nonEmpty && StringUtils.isNotEmpty(referer.head) && !referer.head.trim.contains(localAddress)) { - filterResponse(gatewayContext, validateFailed("Unallowed cross-site request(不允许的跨站请求)!")) - return false - } - //Security certification support, solving verb tampering(安全认证支持,解决动词篡改) - gatewayContext.getRequest.getMethod.toUpperCase match { - case "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "TRACE" | "CONNECT" | "OPTIONS" => - case _ => - filterResponse(gatewayContext, validateFailed("Do not use HTTP verbs to tamper with(不可使用HTTP动词篡改)!")) - return false - } - } - val isPassAuthRequest = GatewayConfiguration.PASS_AUTH_REQUEST_URI.exists(gatewayContext.getRequest.getRequestURI.startsWith) - if(gatewayContext.getRequest.getRequestURI.startsWith(ServerConfiguration.BDP_SERVER_USER_URI.getValue)) { - Utils.tryCatch(userRestful.doUserRequest(gatewayContext)){ t => - val message = t match { - case dwc: DWCException => dwc.getMessage - case _ => "login failed! reason: " + ExceptionUtils.getRootCauseMessage(t) - } - GatewaySSOUtils.error("login failed!", t) - filterResponse(gatewayContext, Message.error(message).<<(gatewayContext.getRequest.getRequestURI)) - } - false - } else if(isPassAuthRequest && !GatewayConfiguration.ENABLE_SSO_LOGIN.getValue) { - GatewaySSOUtils.info("No login needed for proxy uri: " + gatewayContext.getRequest.getRequestURI) - true - } else if(TokenAuthentication.isTokenRequest(gatewayContext)) { - TokenAuthentication.tokenAuth(gatewayContext) - } else { - val userName = Utils.tryCatch(GatewaySSOUtils.getLoginUser(gatewayContext)){ - case n @ (_: NonLoginException | _: LoginExpireException )=> - if(Configuration.IS_TEST_MODE.getValue) None else { - filterResponse(gatewayContext, Message.noLogin(n.getMessage) << gatewayContext.getRequest.getRequestURI) - return false - } - case t: Throwable => - GatewaySSOUtils.warn("", t) - throw t - } - if(userName.isDefined) { - true - } else if(Configuration.IS_TEST_MODE.getValue) { - GatewaySSOUtils.info("test mode! login for uri: " + gatewayContext.getRequest.getRequestURI) - GatewaySSOUtils.setLoginUser(gatewayContext, testUser) - true - } else if(GatewayConfiguration.ENABLE_SSO_LOGIN.getValue) { - val user = SSOInterceptor.getSSOInterceptor.getUser(gatewayContext) - if(StringUtils.isNotBlank(user)) { - GatewaySSOUtils.setLoginUser(gatewayContext, user) - GatewaySSOUtils.setLoginUser(gatewayContext.getRequest, user) - true - } else if(isPassAuthRequest) { - gatewayContext.getResponse.redirectTo(SSOInterceptor.getSSOInterceptor.redirectTo(gatewayContext.getRequest.getURI)) - gatewayContext.getResponse.sendResponse() - false - } else { - filterResponse(gatewayContext, Message.noLogin("You are not logged in, please login first(您尚未登录,请先登录)!") - .data("enableSSO", true).data("SSOURL", SSOInterceptor.getSSOInterceptor.redirectTo(gatewayContext.getRequest.getURI)) << gatewayContext.getRequest.getRequestURI) - false - } - } else { - filterResponse(gatewayContext, Message.noLogin("You are not logged in, please login first(您尚未登录,请先登录)!") << gatewayContext.getRequest.getRequestURI) - false - } - } - } - - protected def addAccessHeaders(gatewayContext: GatewayContext) { - val response = gatewayContext.getResponse - response.setHeader("Access-Control-Allow-Origin", "*") - response.setHeader("Access-Control-Allow-Credentials", "true") - response.setHeader("Access-Control-Allow-Headers", "authorization,Content-Type") - response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, HEAD, DELETE") - val fullDateFormatEN = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, new Locale("EN", "en")) - response.setHeader("Date", fullDateFormatEN.format(new Date)) - } - -} diff --git a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/UserRestful.scala b/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/UserRestful.scala deleted file mode 100644 index d01b9dbf07..0000000000 --- a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/UserRestful.scala +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.security - -import com.google.gson.Gson -import com.webank.wedatasphere.linkis.common.utils.{Logging, RSAUtils, Utils} -import com.webank.wedatasphere.linkis.gateway.config.GatewayConfiguration -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext -import com.webank.wedatasphere.linkis.gateway.security.sso.SSOInterceptor -import com.webank.wedatasphere.linkis.protocol.usercontrol.{RequestLogin, RequestRegister, ResponseLogin, ResponseRegister} -import com.webank.wedatasphere.linkis.rpc.Sender -import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration -import com.webank.wedatasphere.linkis.server.security.SSOUtils -import com.webank.wedatasphere.linkis.server.{Message, _} -import org.apache.commons.lang.StringUtils - -/** - * created by cooperyang on 2019/1/9. - */ -trait UserRestful { - - def doUserRequest(gatewayContext: GatewayContext): Unit - -} -abstract class AbstractUserRestful extends UserRestful with Logging { - - private var securityHooks: Array[SecurityHook] = Array.empty - - def setSecurityHooks(securityHooks: Array[SecurityHook]): Unit = this.securityHooks = securityHooks - - private val userRegex = { - var userURI = ServerConfiguration.BDP_SERVER_USER_URI.getValue - if(!userURI.endsWith("/")) userURI += "/" - userURI - } - - override def doUserRequest(gatewayContext: GatewayContext): Unit = { - val path = gatewayContext.getRequest.getRequestURI.replace(userRegex, "") - val message = path match { - case "register" => register(gatewayContext) - case "login" => - Utils.tryCatch { - val loginUser = GatewaySSOUtils.getLoginUsername(gatewayContext) - Message.error(loginUser + "Already logged in, please log out before signing in(已经登录,请先退出再进行登录)!").data("redirectToIndex", true) - }(_ => login(gatewayContext)) - case "logout" => logout(gatewayContext) - case "userInfo" => userInfo(gatewayContext) - case "publicKey" => publicKey(gatewayContext) - case "heartbeat" => heartbeat(gatewayContext) - case _ => - warn(s"Unknown request URI" + path) - Message.error("unknown request URI " + path) - } - gatewayContext.getResponse.write(message) - gatewayContext.getResponse.setStatus(Message.messageToHttpStatus(message)) - gatewayContext.getResponse.sendResponse() - } - - def login(gatewayContext: GatewayContext): Message = { - val message = tryLogin(gatewayContext) - if(securityHooks != null) securityHooks.foreach(_.postLogin(gatewayContext)) - message - } - - def register(gatewayContext: GatewayContext): Message = { - val message = tryRegister(gatewayContext) - message - } - - protected def tryLogin(context: GatewayContext): Message - - def logout(gatewayContext: GatewayContext): Message = { - GatewaySSOUtils.removeLoginUser(gatewayContext) - if(GatewayConfiguration.ENABLE_SSO_LOGIN.getValue) SSOInterceptor.getSSOInterceptor.logout(gatewayContext) - if(securityHooks != null) securityHooks.foreach(_.preLogout(gatewayContext)) - "Logout successful(退出登录成功)!" - } - - def userInfo(gatewayContext: GatewayContext): Message = { - "get user information succeed!".data("userName", GatewaySSOUtils.getLoginUsername(gatewayContext)) - } - - def publicKey(gatewayContext: GatewayContext): Message = { - val message = Message.ok("Gain success(获取成功)!").data("enable", SSOUtils.sslEnable) - if(SSOUtils.sslEnable) message.data("publicKey", RSAUtils.getDefaultPublicKey()) - message - } - - def heartbeat(gatewayContext: GatewayContext): Message = Utils.tryCatch { - GatewaySSOUtils.getLoginUsername(gatewayContext) - "Maintain heartbeat success(维系心跳成功)!" - }(t => Message.noLogin(t.getMessage)) - - protected def tryRegister(context: GatewayContext): Message -} -abstract class UserPwdAbstractUserRestful extends AbstractUserRestful with Logging{ - - private val sender: Sender = Sender.getSender(GatewayConfiguration.USERCONTROL_SPRING_APPLICATION_NAME.getValue) - private val LINE_DELIMITER = "" - - override protected def tryLogin(gatewayContext: GatewayContext): Message = { - val userNameArray = gatewayContext.getRequest.getQueryParams.get("userName") - val passwordArray = gatewayContext.getRequest.getQueryParams.get("password") - val (userName, password) = if(userNameArray != null && userNameArray.nonEmpty && - passwordArray != null && passwordArray.nonEmpty) - (userNameArray.head, passwordArray.head) - else if(StringUtils.isNotBlank(gatewayContext.getRequest.getRequestBody)){ - val json = BDPJettyServerHelper.gson.fromJson(gatewayContext.getRequest.getRequestBody, classOf[java.util.Map[String, Object]]) - (json.get("userName"), json.get("password")) - } else (null, null) - if(userName == null || StringUtils.isBlank(userName.toString)) { - Message.error("Username can not be empty(用户名不能为空)!") - } else if(password == null || StringUtils.isBlank(password.toString)) { - Message.error("Password can not be blank(密码不能为空)!") - } else { - //warn: For easy to useing linkis,Admin skip login - if(GatewayConfiguration.ADMIN_USER.getValue.equals(userName.toString) && userName.toString.equals(password.toString)){ - GatewaySSOUtils.setLoginUser(gatewayContext, userName.toString) - "login successful(登录成功)!".data("userName", userName) - .data("isAdmin", true) - } else { - // firstly for test user - var message = Message.ok() - if (GatewayConfiguration.USERCONTROL_SWITCH_ON.getValue) { - message = userControlLogin(userName.toString, password.toString, gatewayContext) - } else { - // standard login - val lowerCaseUserName = userName.toString.toLowerCase - message = login(lowerCaseUserName, password.toString) - if(message.getStatus == 0) GatewaySSOUtils.setLoginUser(gatewayContext, lowerCaseUserName) - } - if (message.getData.containsKey("errmsg")) { - message.setMessage(message.getMessage + LINE_DELIMITER + message.getData.get("errmsg").toString) - } - message - } - } - } - - protected def login(userName: String, password: String): Message - - protected def register(gatewayContext: GatewayContext) : Message - - def userControlLogin(userName: String, password: String, gatewayContext: GatewayContext): Message = { - var message = Message.ok() - // usercontrol switch on(开启了用户控制开关) - val requestLogin = new RequestLogin - requestLogin.setUserName(userName.toString).setPassword(password.toString) - Utils.tryCatch(sender.ask(requestLogin) match { - case r: ResponseLogin => - message.setStatus(r.getStatus) - if (StringUtils.isNotBlank(r.getErrMsg)) { - message.data("errmsg", r.getErrMsg) - } - if (0 == r.getStatus) { - GatewaySSOUtils.setLoginUser(gatewayContext, userName.toString) - message.setStatus(0) - message.setMessage("Login successful(登录成功)") - } else { - message = Message.error("Invalid username or password, please check and try again later(用户名或密码无效,请稍后再试)") - } - }) { - t => { - warn(s"Login rpc request error, err message ", t) - message.setStatus(1) - message.setMessage("System error, please try again later(系统异常,请稍后再试)") - message.data("errmsg", t.getMessage) - } - } - message - } - - override def tryRegister(gatewayContext: GatewayContext): Message = { - var message = Message.ok() - if (GatewayConfiguration.USERCONTROL_SWITCH_ON.getValue) { - message = userControlRegister(gatewayContext) - } else { - // TODO use normal register only when it's implemented(仅当实现了通用注册,才可以调注册接口) - message = register(gatewayContext) - } - message - } - - /** - * userControl register(用户控制模块登录) - * @param gatewayContext - * @return - */ - private def userControlRegister(gatewayContext: GatewayContext): Message = { - val message = Message.ok() - val gson = new Gson - val requestRegister = new RequestRegister - val requestBody: String = gatewayContext.getRequest.getRequestBody - Utils.tryCatch({ - requestRegister.setParams(requestBody) - sender.ask(requestRegister) match { - case r: ResponseRegister => - message.setStatus(r.getStatus) - message.setMessage(r.getMessage) - var map = r.getData - message.setData(map) - message.setMethod(r.getMethod) - info(s"Register rpc success. requestRegister=" + gson.toJson(requestRegister) + ", response=" + gson.toJson(r)) - } - }) { - e => - warn(s"Register rpc request error. err message ", e) - message.setStatus(1) - message.setMessage("System, please try again later(系统异常,请稍后再试)") - } - if (message.getData.containsKey("errmsg")) { - // for frontend display - message.setMessage(message.getMessage + LINE_DELIMITER + message.getData.get("errmsg").toString) - } - message - } -} \ No newline at end of file diff --git a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/sso/SSOInterceptor.scala b/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/sso/SSOInterceptor.scala deleted file mode 100644 index 5e50654ab6..0000000000 --- a/gateway/core/src/main/scala/com/webank/wedatasphere/linkis/gateway/security/sso/SSOInterceptor.scala +++ /dev/null @@ -1,47 +0,0 @@ -package com.webank.wedatasphere.linkis.gateway.security.sso - -import java.net.URI - -import com.webank.wedatasphere.linkis.DataWorkCloudApplication -import com.webank.wedatasphere.linkis.common.utils.ClassUtils -import com.webank.wedatasphere.linkis.gateway.config.GatewayConfiguration -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext - -trait SSOInterceptor { - - /** - * 如果打开SSO单点登录功能,当前端跳转SSO登录页面登录成功后,前端再次转发请求给gateway。 - * 用户需实现该接口,通过Request返回user - * @param gatewayContext - * @return - */ - def getUser(gatewayContext: GatewayContext): String - - /** - * 通过前端的requestUrl,用户传回一个可跳转的SSO登录页面URL。 - * 要求:需带上原请求URL,以便登录成功后能跳转回来 - * @param requestUrl - * @return - */ - def redirectTo(requestUrl: URI): String - - /** - * gateway退出时,会调用此接口,以保证gateway清除cookie后,SSO单点登录也会把登录信息清除掉 - * @param gatewayContext - */ - def logout(gatewayContext: GatewayContext): Unit - -} -object SSOInterceptor { - import scala.collection.JavaConversions._ - private var interceptor: SSOInterceptor = _ - def getSSOInterceptor: SSOInterceptor = if(interceptor != null) interceptor else { - val ssoInterceptors = DataWorkCloudApplication.getApplicationContext.getBeansOfType(classOf[SSOInterceptor]) - if(ssoInterceptors != null && !ssoInterceptors.isEmpty) { - interceptor = ssoInterceptors.head._2 - } else { - interceptor = ClassUtils.getClassInstance(GatewayConfiguration.SSO_INTERCEPTOR_CLASS.getValue) - } - interceptor - } -} \ No newline at end of file diff --git a/gateway/gateway-httpclient-support/pom.xml b/gateway/gateway-httpclient-support/pom.xml deleted file mode 100644 index 65f64e5756..0000000000 --- a/gateway/gateway-httpclient-support/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - - 4.0.0 - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - linkis-gateway-httpclient-support - - - - com.webank.wedatasphere.linkis - linkis-httpclient - - - com.webank.wedatasphere.linkis - linkis-storage - provided - - - commons-beanutils - commons-beanutils - 1.9.4 - - - org.reflections - reflections - 0.9.10 - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/gateway/gateway-httpclient-support/src/main/scala/com/webank/wedatasphere/linkis/httpclient/dws/DWSHttpClient.scala b/gateway/gateway-httpclient-support/src/main/scala/com/webank/wedatasphere/linkis/httpclient/dws/DWSHttpClient.scala deleted file mode 100644 index d36005c115..0000000000 --- a/gateway/gateway-httpclient-support/src/main/scala/com/webank/wedatasphere/linkis/httpclient/dws/DWSHttpClient.scala +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * created by cooperyang on 2019/07/24. - */ - -package com.webank.wedatasphere.linkis.httpclient.dws - -import java.text.SimpleDateFormat -import java.util - -import com.fasterxml.jackson.databind.ObjectMapper -import com.webank.wedatasphere.linkis.common.io.{Fs, FsPath} -import com.webank.wedatasphere.linkis.httpclient.AbstractHttpClient -import com.webank.wedatasphere.linkis.httpclient.discovery.Discovery -import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfig -import com.webank.wedatasphere.linkis.httpclient.dws.discovery.DWSGatewayDiscovery -import com.webank.wedatasphere.linkis.httpclient.dws.request.DWSHttpAction -import com.webank.wedatasphere.linkis.httpclient.dws.response.{DWSHttpMessageFactory, DWSHttpMessageResultInfo, DWSResult} -import com.webank.wedatasphere.linkis.httpclient.request.HttpAction -import com.webank.wedatasphere.linkis.httpclient.response.{HttpResult, ListResult, Result} -import com.webank.wedatasphere.linkis.storage.FSFactory -import org.apache.commons.beanutils.BeanUtils -import org.apache.commons.lang.ClassUtils -import org.apache.http.HttpResponse - -import scala.collection.JavaConversions.mapAsJavaMap - -/** - * created by cooperyang on 2019/5/20. - */ -class DWSHttpClient(clientConfig: DWSClientConfig, clientName: String) - extends AbstractHttpClient(clientConfig, clientName) { - - override protected def createDiscovery(): Discovery = new DWSGatewayDiscovery - - - override protected def prepareAction(requestAction: HttpAction): HttpAction = { - requestAction match { - case dwsAction: DWSHttpAction => dwsAction.setDWSVersion(clientConfig.getDWSVersion) - case _ => - } - requestAction - } - - override protected def httpResponseToResult(response: HttpResponse, requestAction: HttpAction, responseBody: String): Option[Result] = { - var entity = response.getEntity - val statusCode: Int = response.getStatusLine.getStatusCode - val url: String = requestAction.getURL - val contentType: String = entity.getContentType.getValue - DWSHttpMessageFactory.getDWSHttpMessageResult(url).map { case DWSHttpMessageResultInfo(_, clazz) => - clazz match { - case c if ClassUtils.isAssignable(c, classOf[DWSResult]) => - val dwsResult = clazz.getConstructor().newInstance().asInstanceOf[DWSResult] - dwsResult.set(responseBody, statusCode, url, contentType) - BeanUtils.populate(dwsResult, dwsResult.getData) - return Some(dwsResult) - case _ => - } - - def transfer(value: Result, map: Map[String, Object]): Unit = { - value match { - case httpResult: HttpResult => - httpResult.set(responseBody, statusCode, url, contentType) - case _ => - } - val javaMap = mapAsJavaMap(map) - BeanUtils.populate(value, javaMap) - fillResultFields(javaMap, value) - } - deserializeResponseBody(response) match { - case map: Map[String, Object] => - val value = clazz.getConstructor().newInstance().asInstanceOf[Result] - transfer(value, map) - value - case list: List[Map[String, Object]] => - val results = list.map { map => - val value = clazz.getConstructor().newInstance().asInstanceOf[Result] - transfer(value, map) - value - }.toArray - new ListResult(responseBody, results) - } - }.orElse(nonDWSResponseToResult(response, requestAction)) - } - - protected def nonDWSResponseToResult(response: HttpResponse, requestAction: HttpAction): Option[Result] = None - - protected def fillResultFields(responseMap: util.Map[String, Object], value: Result): Unit = {} - - //TODO Consistent with workspace, plus expiration time(与workspace保持一致,加上过期时间) - override protected def getFsByUser(user: String, path: FsPath): Fs = FSFactory.getFsByProxyUser(path, user) - -} -object DWSHttpClient { - val jacksonJson = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")) -} \ No newline at end of file diff --git a/gateway/gateway-ujes-support/Dockerfile b/gateway/gateway-ujes-support/Dockerfile deleted file mode 100644 index e7016a1236..0000000000 --- a/gateway/gateway-ujes-support/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM wedatasphere/linkis:emr-base-spark2.4.4 - -MAINTAINER wedatasphere@webank.com - -RUN yum install -y unzip -WORKDIR /opt/linkis - -COPY target/linkis-gateway.zip /opt/linkis -RUN unzip linkis-gateway.zip - -WORKDIR /opt/linkis/linkis-gateway/bin -ENTRYPOINT ["/opt/linkis/linkis-gateway/bin/startup.sh"] diff --git a/gateway/gateway-ujes-support/bin/start-gateway.sh b/gateway/gateway-ujes-support/bin/start-gateway.sh deleted file mode 100755 index 56cab6df00..0000000000 --- a/gateway/gateway-ujes-support/bin/start-gateway.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-gc.log" -fi - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -nohup java $SERVER_JAVA_OPTS -cp $HOME/conf:$HOME/lib/* $SERVER_CLASS 2>&1 > $SERVER_LOG_PATH/linkis.out & -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi \ No newline at end of file diff --git a/gateway/gateway-ujes-support/bin/startup.sh b/gateway/gateway-ujes-support/bin/startup.sh deleted file mode 100755 index 2b531e25e9..0000000000 --- a/gateway/gateway-ujes-support/bin/startup.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_LOG_PATH=$HOME/logs -export SERVER_CLASS=com.webank.wedatasphere.linkis.DataWorkCloudApplication - - -if test -z "$SERVER_HEAP_SIZE" -then - export SERVER_HEAP_SIZE="512M" -fi - -if test -z "$SERVER_JAVA_OPTS" -then - export SERVER_JAVA_OPTS=" -Xmx$SERVER_HEAP_SIZE -XX:+UseG1GC -Xloggc:$HOME/logs/linkis-gateway-gc.log" -fi - -if test -z "$START_PORT" -then - export START_PORT=14001 -fi - -export SERVER_PID=$HOME/bin/linkis.pid - -if [[ -f "${SERVER_PID}" ]]; then - pid=$(cat ${SERVER_PID}) - if kill -0 ${pid} >/dev/null 2>&1; then - echo "Server is already running." - exit 1 - fi -fi - -cp -f /opt/linkis/conf/linkis.properties /opt/linkis/linkis-gateway/conf - -nohup java $SERVER_JAVA_OPTS -Deurekaurl=$EUREKA_URL -Duser.timezone=Asia/Shanghai -cp $HOME/conf:$HOME/lib/* $SERVER_CLASS --server.port=$START_PORT 2>&1 > $SERVER_LOG_PATH/linkis-gateway.log & - -pid=$! -if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME start failed!" - exit 1 -else - echo "server $SERVER_NAME start succeeded!" - echo $pid > $SERVER_PID - sleep 1 -fi - -tail -f /dev/null diff --git a/gateway/gateway-ujes-support/bin/stop-gateway.sh b/gateway/gateway-ujes-support/bin/stop-gateway.sh deleted file mode 100755 index f032887111..0000000000 --- a/gateway/gateway-ujes-support/bin/stop-gateway.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/gateway/gateway-ujes-support/bin/stop.sh b/gateway/gateway-ujes-support/bin/stop.sh deleted file mode 100755 index f032887111..0000000000 --- a/gateway/gateway-ujes-support/bin/stop.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -cd `dirname $0` -cd .. -HOME=`pwd` - -export SERVER_PID=$HOME/bin/linkis.pid - -function wait_for_server_to_die() { - local pid - local count - pid=$1 - timeout=$2 - count=0 - timeoutTime=$(date "+%s") - let "timeoutTime+=$timeout" - currentTime=$(date "+%s") - forceKill=1 - - while [[ $currentTime -lt $timeoutTime ]]; do - $(kill ${pid} > /dev/null 2> /dev/null) - if kill -0 ${pid} > /dev/null 2>&1; then - sleep 3 - else - forceKill=0 - break - fi - currentTime=$(date "+%s") - done - - if [[ forceKill -ne 0 ]]; then - $(kill -9 ${pid} > /dev/null 2> /dev/null) - fi -} - -if [[ ! -f "${SERVER_PID}" ]]; then - echo "server $SERVER_NAME is not running" -else - pid=$(cat ${SERVER_PID}) - if [[ -z "${pid}" ]]; then - echo "server $SERVER_NAME is not running" - else - wait_for_server_to_die $pid 40 - $(rm -f ${SERVER_PID}) - echo "server $SERVER_NAME is stopped." - fi -fi \ No newline at end of file diff --git a/gateway/gateway-ujes-support/dockerinfo/image-id b/gateway/gateway-ujes-support/dockerinfo/image-id deleted file mode 100644 index 4cbd2fafaf..0000000000 --- a/gateway/gateway-ujes-support/dockerinfo/image-id +++ /dev/null @@ -1 +0,0 @@ -4a6d1f2107f5 diff --git a/gateway/gateway-ujes-support/dockerinfo/image-name b/gateway/gateway-ujes-support/dockerinfo/image-name deleted file mode 100644 index c17be8314f..0000000000 --- a/gateway/gateway-ujes-support/dockerinfo/image-name +++ /dev/null @@ -1 +0,0 @@ -wedatasphere/linkis:linkis-gateway diff --git a/gateway/gateway-ujes-support/dockerinfo/repository b/gateway/gateway-ujes-support/dockerinfo/repository deleted file mode 100644 index d2b33f60b5..0000000000 --- a/gateway/gateway-ujes-support/dockerinfo/repository +++ /dev/null @@ -1 +0,0 @@ -wedatasphere/linkis diff --git a/gateway/gateway-ujes-support/dockerinfo/tag b/gateway/gateway-ujes-support/dockerinfo/tag deleted file mode 100644 index 865786b3c5..0000000000 --- a/gateway/gateway-ujes-support/dockerinfo/tag +++ /dev/null @@ -1 +0,0 @@ -linkis-gateway diff --git a/gateway/gateway-ujes-support/pom.xml b/gateway/gateway-ujes-support/pom.xml deleted file mode 100644 index f80ef6aa5e..0000000000 --- a/gateway/gateway-ujes-support/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - - 4.0.0 - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - - linkis-gateway-ujes-support - - - - com.webank.wedatasphere.linkis - linkis-gateway-springcloudgateway - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty - jetty-server - - - - - - javax.servlet.jsp - jsp-api - 2.1 - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - ../gateway-ujes-support/src/main/assembly/distribution.xml - - - - - - false - linkis-gateway - false - false - - ../gateway-ujes-support/src/main/assembly/distribution.xml - - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/gateway/gateway-ujes-support/pom_k8s.xml b/gateway/gateway-ujes-support/pom_k8s.xml deleted file mode 100644 index e5379771b4..0000000000 --- a/gateway/gateway-ujes-support/pom_k8s.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - - - 4.0.0 - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - - linkis-gateway-ujes-support - - - - com.webank.wedatasphere.linkis - linkis-gateway-springcloudgateway - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty - jetty-server - - - - - - javax.servlet.jsp - jsp-api - 2.1 - - - org.json4s - json4s-jackson_2.11 - 3.2.11 - - - com.fasterxml.jackson.core - jackson-databind - 2.9.6 - - - io.netty - netty-all - 4.1.25.Final - - - io.netty - netty-transport-native-epoll - 4.1.25.Final - - - com.webank.wedatasphere.linkis - linkis-cs-common - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - false - - - make-assembly - package - - single - - - - ../gateway-ujes-support/src/main/assembly/distribution.xml - - - - - - false - linkis-gateway - false - false - - ../gateway-ujes-support/src/main/assembly/distribution.xml - - - - - - - - - - - - - - - - - - - - - - - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/assembly/distribution.xml b/gateway/gateway-ujes-support/src/main/assembly/distribution.xml deleted file mode 100644 index bd07b723c6..0000000000 --- a/gateway/gateway-ujes-support/src/main/assembly/distribution.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - linkis-gateway - - zip - - true - linkis-gateway - - - - - - lib - true - true - false - true - true - - - - - - ${basedir}/src/main/resources - - * - - 0777 - conf - unix - - - ${basedir}/bin - - * - - 0777 - bin - unix - - - . - - */** - - logs - - - - - diff --git a/gateway/gateway-ujes-support/src/main/resources/application.yml b/gateway/gateway-ujes-support/src/main/resources/application.yml deleted file mode 100644 index 60b63ee6ca..0000000000 --- a/gateway/gateway-ujes-support/src/main/resources/application.yml +++ /dev/null @@ -1,39 +0,0 @@ -server: - port: 9001 -spring: - application: - name: DataWorkCloud-Gateway - cloud: - gateway: - routes: - - id: dws - uri: http://localhost:port/ - predicates: - - Path=/dws/ - - id: dws/vg - uri: http://localhost:port/ - predicates: - - Path=/dws/vg/ - - id: dws/easyide - uri: http://localhost:port/ - predicates: - - Path=/dws/easyide/ - -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - lease-renewal-interval-in-second: 5 - lease-expiration-duration-in-second: 10 - prefer-ip-address: true - instance-id: ${spring.cloud.client.ip-address}:${server.port} - metadata-map: - test: wedatasphere - -management: - endpoints: - web: - exposure: - include: refresh,info diff --git a/gateway/gateway-ujes-support/src/main/resources/linkis.properties b/gateway/gateway-ujes-support/src/main/resources/linkis.properties deleted file mode 100644 index 786777975e..0000000000 --- a/gateway/gateway-ujes-support/src/main/resources/linkis.properties +++ /dev/null @@ -1,34 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -#wds.linkis.test.mode=true - -wds.linkis.server.version=v1 - -wds.linkis.ldap.proxy.url= -wds.linkis.ldap.proxy.baseDN= - -wds.linkis.server.restful.uri=/ - -wds.linkis.server.web.session.timeout=1h - -wds.linkis.gateway.conf.enable.proxy.user=false - -wds.linkis.gateway.conf.url.pass.auth=/dss/ - -wds.linkis.gateway.admin.user=hadoop - -wds.linkis.gateway.conf.enable.token.auth=true \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/resources/log4j.properties b/gateway/gateway-ujes-support/src/main/resources/log4j.properties deleted file mode 100644 index 178f8dfa26..0000000000 --- a/gateway/gateway-ujes-support/src/main/resources/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -### set log levels ### - -log4j.rootCategory=INFO,console - -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.Threshold=INFO -log4j.appender.console.layout=org.apache.log4j.PatternLayout -#log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n -log4j.appender.console.layout.ConversionPattern= %d{ISO8601} %-5p (%t) %p %c{1} - %m%n - - -log4j.appender.com.webank.bdp.ide.core=org.apache.log4j.DailyRollingFileAppender -log4j.appender.com.webank.bdp.ide.core.Threshold=INFO -log4j.additivity.com.webank.bdp.ide.core=false -log4j.appender.com.webank.bdp.ide.core.layout=org.apache.log4j.PatternLayout -log4j.appender.com.webank.bdp.ide.core.Append=true -log4j.appender.com.webank.bdp.ide.core.File=logs/linkis.log -log4j.appender.com.webank.bdp.ide.core.layout.ConversionPattern= %d{ISO8601} %-5p (%t) [%F:%M(%L)] - %m%n - -log4j.logger.org.springframework=INFO \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/resources/token.properties b/gateway/gateway-ujes-support/src/main/resources/token.properties deleted file mode 100644 index 136141cebf..0000000000 --- a/gateway/gateway-ujes-support/src/main/resources/token.properties +++ /dev/null @@ -1,5 +0,0 @@ -QML-AUTH=* -BML-AUTH=* -WS-AUTH=* -dss-AUTH=* -QUALITIS-AUTH=* \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceExecutionGatewayParser.scala b/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceExecutionGatewayParser.scala deleted file mode 100644 index 939c89ac73..0000000000 --- a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceExecutionGatewayParser.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.ujes.parser - -import com.webank.wedatasphere.linkis.common.ServiceInstance -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext -import com.webank.wedatasphere.linkis.gateway.parser.AbstractGatewayParser -import com.webank.wedatasphere.linkis.gateway.springcloud.SpringCloudGatewayConfiguration._ -import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant -import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper -import org.apache.commons.lang.StringUtils -import org.springframework.stereotype.Component - -/** - * created by cooperyang on 2019/5/15. - */ -@Component -class EntranceExecutionGatewayParser extends AbstractGatewayParser { - - override def shouldContainRequestBody(gatewayContext: GatewayContext): Boolean = gatewayContext.getRequest.getRequestURI match { - case EntranceExecutionGatewayParser.ENTRANCE_EXECUTION_REGEX(_, _) => true - case _ => false - } - - override def parse(gatewayContext: GatewayContext): Unit = gatewayContext.getRequest.getRequestURI match { - case EntranceExecutionGatewayParser.ENTRANCE_EXECUTION_REGEX(version, _) => - if(sendResponseWhenNotMatchVersion(gatewayContext, version)) return - //var (creator, executeApplicationName): (String, String) = null - var creator:String = null - var executeApplicationName:String = null - if(StringUtils.isNotBlank(gatewayContext.getRequest.getRequestBody)) { - val json = BDPJettyServerHelper.gson.fromJson(gatewayContext.getRequest.getRequestBody, classOf[java.util.Map[String, Object]]) - json.get(TaskConstant.EXECUTEAPPLICATIONNAME) match { - case s: String => executeApplicationName = s - case _ => - } - json.get(TaskConstant.REQUESTAPPLICATIONNAME) match { - case s: String => creator = s - case _ => - } - } - val path = gatewayContext.getRequest.getRequestURI - if(StringUtils.isBlank(executeApplicationName)) { - sendErrorResponse(s"requestUri $path need request parameter " + TaskConstant.EXECUTEAPPLICATIONNAME, gatewayContext) - } else { - info(s"GatewayParser parse requestUri $path to service $creator or $executeApplicationName.") - if(StringUtils.isNotBlank(creator)) gatewayContext.getGatewayRoute.getParams.put(TaskConstant.REQUESTAPPLICATIONNAME, creator) - gatewayContext.getGatewayRoute.setServiceInstance(ServiceInstance(executeApplicationName, null)) - } - case _ => - } -} - -object EntranceExecutionGatewayParser { - val ENTRANCE_HEADER = normalPath(API_URL_PREFIX) + "rest_[a-zA-Z][a-zA-Z_0-9]*/(v\\d+)/entrance/" - val ENTRANCE_EXECUTION_REGEX = (ENTRANCE_HEADER + "(execute|backgroundservice)").r -} \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceRequestGatewayParser.scala b/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceRequestGatewayParser.scala deleted file mode 100644 index 4775203889..0000000000 --- a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/parser/EntranceRequestGatewayParser.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.ujes.parser - -import com.webank.wedatasphere.linkis.common.ServiceInstance -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext -import com.webank.wedatasphere.linkis.gateway.parser.AbstractGatewayParser -import com.webank.wedatasphere.linkis.gateway.ujes.parser.EntranceExecutionGatewayParser._ -import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant -import com.webank.wedatasphere.linkis.protocol.utils.ZuulEntranceUtils -import org.springframework.stereotype.Component - -/** - * created by cooperyang on 2019/5/15. - */ -@Component -class EntranceRequestGatewayParser extends AbstractGatewayParser { - override def shouldContainRequestBody(gatewayContext: GatewayContext): Boolean = false - - override def parse(gatewayContext: GatewayContext): Unit = gatewayContext.getRequest.getRequestURI match { - case EntranceRequestGatewayParser.ENTRANCE_REQUEST_REGEX(version, execId) => - if(sendResponseWhenNotMatchVersion(gatewayContext, version)) return - val moduleInfo = ZuulEntranceUtils.parseExecID(execId) - val serviceInstance = if(moduleInfo.length == 3) ServiceInstance(moduleInfo(0), moduleInfo(1)) - else { - gatewayContext.getGatewayRoute.getParams.put(TaskConstant.REQUESTAPPLICATIONNAME, moduleInfo(0)) - ServiceInstance(moduleInfo(1), moduleInfo(2)) - } - gatewayContext.getGatewayRoute.setServiceInstance(serviceInstance) - case _ => - } -} - -object EntranceRequestGatewayParser { - val ENTRANCE_REQUEST_REGEX = (ENTRANCE_HEADER + "([^/]+)/.+").r -} \ No newline at end of file diff --git a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/EntranceGatewayRouterRuler.scala b/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/EntranceGatewayRouterRuler.scala deleted file mode 100644 index 9b819cd3be..0000000000 --- a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/EntranceGatewayRouterRuler.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2019 WeBank - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.webank.wedatasphere.linkis.gateway.ujes.route - -import com.webank.wedatasphere.linkis.gateway.http.GatewayContext - -/** - * - * @author wang_zh - * @date 2020/5/21 - */ -trait EntranceGatewayRouterRuler { - - def rule(serviceId: String, gatewayContext: GatewayContext) - -} diff --git a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/contextservice/ContextIdParserImpl.scala b/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/contextservice/ContextIdParserImpl.scala deleted file mode 100644 index a0fed9ea9c..0000000000 --- a/gateway/gateway-ujes-support/src/main/scala/com/webank/wedatasphere/linkis/gateway/ujes/route/contextservice/ContextIdParserImpl.scala +++ /dev/null @@ -1,52 +0,0 @@ -package com.webank.wedatasphere.linkis.gateway.ujes.route.contextservice - -import java.util -import java.util.{ArrayList, List} - -import com.webank.wedatasphere.linkis.common.utils.Logging -import com.webank.wedatasphere.linkis.cs.common.entity.source.{ContextIDParser, HAContextID} -import com.webank.wedatasphere.linkis.cs.common.utils.CSHighAvailableUtils -import com.webank.wedatasphere.linkis.rpc.instancealias.InstanceAliasManager -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Component - - -/** - * created by cooperyang on 2020/2/19 - * Description: 如果id为HAID,则解析出对应的instance - */ -@Component -class ContextIdParserImpl extends ContextIDParser with Logging { - - @Autowired - var instanceAliasManager : InstanceAliasManager = _ - - override def parse(contextId: String): util.List[String] = { - - if (CSHighAvailableUtils.checkHAIDBasicFormat(contextId)) { - val instances = new util.ArrayList[String](2) - val haContextID = CSHighAvailableUtils.decodeHAID(contextId) - if (instanceAliasManager.isInstanceAliasValid(haContextID.getInstance)) { - instances.add(instanceAliasManager.getInstanceByAlias(haContextID.getInstance).getInstance) - } else { - error(s"parse HAID instance invalid. haIDKey : " + contextId) - } - if (instanceAliasManager.isInstanceAliasValid(haContextID.getBackupInstance)) { - instances.add(instanceAliasManager.getInstanceByAlias(haContextID.getBackupInstance).getInstance) - } else { - error("parse HAID backupInstance invalid. haIDKey : " + contextId) - } - instances - } else { - new util.ArrayList[String](0) - } - } - - private def isNumberic(s:String):Boolean = { - s.toCharArray foreach { - c => if (c < 48 || c >57) return false - } - true - } - -} diff --git a/gateway/plugins/gateway-ujes-datasource-ruler/pom.xml b/gateway/plugins/gateway-ujes-datasource-ruler/pom.xml deleted file mode 100644 index 9d5cb864f8..0000000000 --- a/gateway/plugins/gateway-ujes-datasource-ruler/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - - 4.0.0 - - linkis-gateway-ujes-datasource-ruler - - - - com.webank.wedatasphere.linkis - linkis-gateway-ujes-support - ${project.version} - provided - - - - com.webank.wedatasphere.linkis - linkis-mybatis - ${project.version} - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.10 - - - copy-dependencies - package - - copy-dependencies - - - target/lib - provided - - - - - - - - - src/main/java - - **/*.xml - - - - src/main/resources - - **/*.properties - **/application.yml - **/bootstrap.yml - **/log4j2.xml - - - - - - - \ No newline at end of file diff --git a/gateway/springcloudgateway/pom.xml b/gateway/springcloudgateway/pom.xml deleted file mode 100644 index e27c004f27..0000000000 --- a/gateway/springcloudgateway/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - 4.0.0 - - - linkis - com.webank.wedatasphere.linkis - 0.11.0 - ../../pom.xml - - linkis-gateway-springcloudgateway - - - - com.webank.wedatasphere.linkis - linkis-gateway-core - - - json4s-jackson_2.11 - org.json4s - - - - - org.springframework.cloud - spring-cloud-starter-gateway - 2.0.1.RELEASE - - - hibernate-validator - org.hibernate.validator - - - spring-boot-starter-logging - org.springframework.boot - - - jackson-databind - com.fasterxml.jackson.core - - - - - org.springframework.boot - spring-boot-starter-reactor-netty - 2.0.3.RELEASE - - - io.projectreactor - reactor-core - 3.2.2.RELEASE - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - net.alchim31.maven - scala-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - - - ${basedir}/src/main/resources - - - ${project.artifactId}-${project.version} - - - \ No newline at end of file diff --git a/gateway/springcloudgateway/src/main/resources/application.yml b/gateway/springcloudgateway/src/main/resources/application.yml deleted file mode 100644 index 3af5bcba99..0000000000 --- a/gateway/springcloudgateway/src/main/resources/application.yml +++ /dev/null @@ -1,35 +0,0 @@ -server: - port: 9001 #该模块提供服务的端口(必须) -spring: - application: - name: DataWorkCloud-Gateway #模块名,用于做高可用(必须) - cloud: - gateway: - routes: - - id: dws - uri: locahost - predicates: - - Path=/dws/ - - id: dws/vg - uri: locahost - predicates: - - Path=/dws/vg/ - - id: dws/easyide - uri: locahost - predicates: - - Path=/dws/easyide/ -#指定eureka Server的地址,用于注册(必须) -eureka: - client: - serviceUrl: - defaultZone: ${eurekaurl} - registry-fetch-interval-seconds: 5 - instance: - metadata-map: - test: wedatasphere -#(必须) -management: - endpoints: - web: - exposure: - include: refresh,info diff --git a/gateway/springcloudgateway/src/main/resources/linkis.properties b/gateway/springcloudgateway/src/main/resources/linkis.properties deleted file mode 100644 index 28dc7d8a4b..0000000000 --- a/gateway/springcloudgateway/src/main/resources/linkis.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -#wds.linkis.test.mode=true - - -wds.linkis.ldap.proxy.url= -wds.linkis.ldap.proxy.baseDN= -#wds.linkis.ldap.proxy.userNameFormat=cn=%s@xxx.com,OU=xxx,DC=xxx,DC=com - -wds.linkis.server.restful.uri=/ - -wds.linkis.server.web.session.timeout=1h - -wds.linkis.gateway.conf.enable.proxy.user=false - -wds.linkis.gateway.conf.url.pass.auth=/dws/ - -wds.linkis.gateway.admin.user=hadoop \ No newline at end of file diff --git a/gateway/springcloudgateway/src/main/resources/log4j2.xml b/gateway/springcloudgateway/src/main/resources/log4j2.xml deleted file mode 100644 index ad88ea570e..0000000000 --- a/gateway/springcloudgateway/src/main/resources/log4j2.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gateway/springcloudgateway/src/main/resources/token.properties b/gateway/springcloudgateway/src/main/resources/token.properties deleted file mode 100644 index 136141cebf..0000000000 --- a/gateway/springcloudgateway/src/main/resources/token.properties +++ /dev/null @@ -1,5 +0,0 @@ -QML-AUTH=* -BML-AUTH=* -WS-AUTH=* -dss-AUTH=* -QUALITIS-AUTH=* \ No newline at end of file diff --git a/images/en_US/Linkis1.0/architecture/Linkis1.0-architecture.png b/images/en_US/Linkis1.0/architecture/Linkis1.0-architecture.png new file mode 100644 index 0000000000..825672bc23 Binary files /dev/null and b/images/en_US/Linkis1.0/architecture/Linkis1.0-architecture.png differ diff --git a/images/zh_CN/Linkis1.0/architecture/Linkis0.X-NewEngine-architecture.png b/images/zh_CN/Linkis1.0/architecture/Linkis0.X-NewEngine-architecture.png new file mode 100644 index 0000000000..57c83b3a58 Binary files /dev/null and b/images/zh_CN/Linkis1.0/architecture/Linkis0.X-NewEngine-architecture.png differ diff --git a/images/zh_CN/Linkis1.0/architecture/Linkis1.0-EngineConn-architecture.png b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-EngineConn-architecture.png new file mode 100644 index 0000000000..d95da89127 Binary files /dev/null and b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-EngineConn-architecture.png differ diff --git a/images/zh_CN/Linkis1.0/architecture/Linkis1.0-NewEngine-architecture.png b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-NewEngine-architecture.png new file mode 100644 index 0000000000..b1d60bf9ef Binary files /dev/null and b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-NewEngine-architecture.png differ diff --git a/images/zh_CN/Linkis1.0/architecture/Linkis1.0-architecture.png b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-architecture.png new file mode 100644 index 0000000000..c3cb24cecc Binary files /dev/null and b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-architecture.png differ diff --git a/images/zh_CN/Linkis1.0/architecture/Linkis1.0-newEngine-initialization.png b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-newEngine-initialization.png new file mode 100644 index 0000000000..003b38eda5 Binary files /dev/null and b/images/zh_CN/Linkis1.0/architecture/Linkis1.0-newEngine-initialization.png differ diff --git a/images/zh_CN/Linkis1.0/installation/Linkis0.X-services-list.png b/images/zh_CN/Linkis1.0/installation/Linkis0.X-services-list.png new file mode 100644 index 0000000000..c669abfb68 Binary files /dev/null and b/images/zh_CN/Linkis1.0/installation/Linkis0.X-services-list.png differ diff --git a/images/zh_CN/Linkis1.0/installation/Linkis1.0-services-list.png b/images/zh_CN/Linkis1.0/installation/Linkis1.0-services-list.png new file mode 100644 index 0000000000..f7685452fe Binary files /dev/null and b/images/zh_CN/Linkis1.0/installation/Linkis1.0-services-list.png differ diff --git a/k8s/README.MD b/k8s/README.MD deleted file mode 100644 index f21d236297..0000000000 --- a/k8s/README.MD +++ /dev/null @@ -1,104 +0,0 @@ -Linkis on kubernetes - -#重点解决问题 -1.每个人在部署过程中,都会遇到包冲突,操作系统不兼容,openjdk,hotspot jdk兼容问题,docker交付可以从根本上解决这些问题 - -2.docker基于cgroup资源隔离,共享文件系统,namespace 可以轻量限制计算资源,秒级扩缩容 - - 例如:限制某个进程只能使用CPU一个核的20%资源 - cd /sys/fs/cgroup/cpu - touch test - $ echo 10000 > cpu.cfs_quota_us - $ echo 50000 > cpu.cfs_period_us - 启动一个进程,请不要在生产做这样操作!!!! - $ while :; do :; done & - 记录当前进程Id - $ echo pid >> tasks - -#部署文档 - -##基础镜像及各服务镜像编译方法 - - 目前所有微服务镜像都上传到dockerhub,https://hub.docker.com/repository/docker/wedatasphere/linkis - - 出于对虚机部署版本的考虑,新增了pom_k8s.xml,默认打包方式跟之前保持一致,如果想要自己编译镜像,需要引用pom_k8s.xml - - mvn clean package -f gateway/gateway-ujes-support/pom_k8s.xml - - 一.创建kubernetes docker secret - - k8s/registry.yaml 修改对应harbor的账号,密码,镜像仓库地址 - 或者手动创建secret,后续拉取镜像使用,私有docker仓库请修改成私有reposity地址 - $kubectl create secret docker-registry registry-key \ - --docker-server=https://hub.docker.com \ - --docker-username=wedatasphere \ - --docker-password=***** \ - --docker-email=wedatasphere@webank.com - - 二.NFS/ceph 搭建 - - 搭建NFS或者ceph完成后,publicservice等微服务的deployment需要修改nfs的地址 - - 三.基础镜像创建文件(使用官方维护的镜像可以跳过该步骤) - 自己制作基础镜像方法如下: - * 环境变量设置 - - > 设置harbor的地址环境变量 - ``` - export HARBOR_LINKIS= - ``` - - * 基础镜像编译打包 - > 打包 - ``` - cd Linkis/emr-base - docker build -t $HARBOR_LINKIS/linkis:emr-base-spark2.4.4 . - ``` - > 推送 - ``` - docker push $HARBOR_LINKIS/linkis:emr-base-spark2.4.4 - ``` - * 基础依赖包编译 - ``` - mvn clean install -Dmaven.test.skip=true - ``` - - * 替换各个微服务Dockerfile的基础镜像为自己的私服地址 - ``` - find . -name Dockerfile | xargs grep -rl "FROM wedatasphere/linkis" | xargs sed -i "" "s?FROM wedatasphere/linkis?FROM $HARBOR_LINKIS/linkis?" - find . -name "*.yaml" | xargs grep -rl "image: wedatasphere/linkis" | xargs sed -i "" "s?image: wedatasphere/linkis?image: $HARBOR_LINKIS/linkis?" - ``` - - * 编译各微服务镜像 - - > 各个微服务basedir下面有对应 module 的 Dockerfile - 与公司内部的CI/CD集成,可以通过mvn docker插件直接编译docker镜像 - ``` - sh k8s/package.sh - sh k8s/build.sh - sh k8s/push.sh - ``` - - 四、K8S部署 - - 1.大数据环境配置 - > 主要涉及 hadoop,hive,spark环境配置,需要将几个组件的配置在k8s各个节点上 - - | 组件 | 版本 | 节点目录 | - | --- | --- | --- | - | hadoop | 2.7.7 | /opt/hadoop/hadoop-2.7.7 | - | hive | 2.3.6 | /opt/hive/apache-hive-2.3.6-bin | - | spark | 2.4 | /opt/spark/spark-2.4.4-bin-hadoop2.7 | - - 2.启动eureka - eureka部署在k8s的任意一个node节点上就可以 - 启动eureka成功后 - 修改Linkis/k8s/linkis-eureka-configmap.yaml中的eurekaUrl - - 3.修改k8s目录下的linkis-*- configmap.yaml - 特别注意配置文件的正确性,避免后续部署的低级问题出现,如数据库连接不上,hdfs地址不正确等等 - 例如gateway/linkis.properties 复制到k8s/linkis-gateway-configmap.yaml - - 4.运行k8s目录下的 - sh init.sh - 观察eureka上注册的服务,一共22个,都启动成功基本就没有问题 diff --git a/k8s/build.sh b/k8s/build.sh deleted file mode 100644 index 948ad27ef2..0000000000 --- a/k8s/build.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash - -# docker build -t $HARBOR_LINKIS/linkis:emr-base-spark2.4.4 -f emr-base/Dockerfile . - -docker build -t $HARBOR_LINKIS/linkis:linkis-bml-0.11.0 -f bml/bmlserver/Dockerfile bml/bmlserver - -docker build -t $HARBOR_LINKIS/linkis:linkis-dsm-server-0.11.0 -f datasource/datasourcemanager/server/Dockerfile datasource/datasourcemanager/server - -docker build -t $HARBOR_LINKIS/linkis:linkis-mdm-server-0.11.0 -f datasource/metadatamanager/server/Dockerfile datasource/metadatamanager/server -docker build -t $HARBOR_LINKIS/linkis:linkis-mdm-service-mysql-0.11.0 -f datasource/metadatamanager/service/mysql/Dockerfile datasource/metadatamanager/service/mysql -docker build -t $HARBOR_LINKIS/linkis:linkis-mdm-service-es-0.11.0 -f datasource/metadatamanager/service/elasticsearch/Dockerfile datasource/metadatamanager/service/elasticsearch -docker build -t $HARBOR_LINKIS/linkis:linkis-mdm-service-hive-0.11.0 -f datasource/metadatamanager/service/hive/Dockerfile datasource/metadatamanager/service/hive - -docker build -t $HARBOR_LINKIS/linkis:linkis-gateway-0.11.0 -f gateway/gateway-ujes-support/Dockerfile gateway/gateway-ujes-support - -docker build -t $HARBOR_LINKIS/linkis:linkis-resourcemanager-0.11.0 -f resourceManager/resourcemanagerserver/Dockerfile resourceManager/resourcemanagerserver - -docker build -t $HARBOR_LINKIS/linkis:linkis-cs-server-0.11.0 -f contextservice/cs-server/Dockerfile contextservice/cs-server - -docker build -t $HARBOR_LINKIS/linkis:linkis-metadata-0.11.0 -f metadata/Dockerfile metadata - -docker build -t $HARBOR_LINKIS/linkis:linkis-publicservice-0.11.0 -f publicService/Dockerfile publicService - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-spark-enginemanager-0.11.0 -f ujes/definedEngines/spark/enginemanager/Dockerfile ujes/definedEngines/spark/enginemanager -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-spark-entrance-0.11.0 -f ujes/definedEngines/spark/entrance/Dockerfile ujes/definedEngines/spark/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-hive-enginemanager-0.11.0 -f ujes/definedEngines/hive/enginemanager/Dockerfile ujes/definedEngines/hive/enginemanager -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-hive-entrance-0.11.0 -f ujes/definedEngines/hive/entrance/Dockerfile ujes/definedEngines/hive/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-python-enginemanager-0.11.0 -f ujes/definedEngines/python/enginemanager/Dockerfile ujes/definedEngines/python/enginemanager -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-python-entrance-0.11.0 -f ujes/definedEngines/python/entrance/Dockerfile ujes/definedEngines/python/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-pipeline-enginemanager-0.11.0 -f ujes/definedEngines/pipeline/enginemanager/Dockerfile ujes/definedEngines/pipeline/enginemanager -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-pipeline-entrance-0.11.0 -f ujes/definedEngines/pipeline/entrance/Dockerfile ujes/definedEngines/pipeline/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-jdbc-enginemanager-0.11.0 -f ujes/definedEngines/jdbc/entrance/Dockerfile ujes/definedEngines/jdbc/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-mlsql-entrance-0.11.0 -f ujes/definedEngines/mlsql/entrance/Dockerfile ujes/definedEngines/mlsql/entrance - -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-shell-enginemanager-0.11.0 -f ujes/definedEngines/shell/entrance/Dockerfile ujes/definedEngines/shell/entrance -docker build -t $HARBOR_LINKIS/linkis:linkis-ujes-shell-entrance-0.11.0 -f ujes/definedEngines/shell/enginemanager/Dockerfile ujes/definedEngines/shell/enginemanager - - diff --git a/k8s/delete.sh b/k8s/delete.sh deleted file mode 100644 index e7179f8790..0000000000 --- a/k8s/delete.sh +++ /dev/null @@ -1,54 +0,0 @@ -kubectl delete -f register.yaml - -kubectl delete -f linkis-gateway-configmap.yaml -kubectl delete -f linkis-metadata-configmap.yaml -kubectl delete -f linkis-publicservice-configmap.yaml -kubectl delete -f linkis-resourcemanager-configmap.yaml -kubectl delete -f linkis-bml-configmap.yaml -kubectl delete -f linkis-ujes-hive-enginemanager-configmap.yaml -kubectl delete -f linkis-ujes-hive-entrance-configmap.yaml -kubectl delete -f linkis-ujes-jdbc-entrance-configmap.yaml -kubectl delete -f linkis-ujes-mlsql-entrance-configmap.yaml -kubectl delete -f linkis-ujes-pipeline-enginemanager-configmap.yaml -kubectl delete -f linkis-ujes-pipeline-entrance-configmap.yaml -kubectl delete -f linkis-ujes-python-enginemanager-configmap.yaml -kubectl delete -f linkis-ujes-python-entrance-configmap.yaml -kubectl delete -f linkis-ujes-shell-enginemanager-configmap.yaml -kubectl delete -f linkis-ujes-shell-entrance-configmap.yaml -kubectl delete -f linkis-ujes-spark-entrance-configmap.yaml -kubectl delete -f linkis-ujes-spark-enginemanager-configmap.yaml - -kubectl delete -f linkis-dsm-server-configmap.yaml -kubectl delete -f linkis-mdm-server-configmap.yaml -kubectl delete -f linkis-mdm-service-es-configmap.yaml -kubectl delete -f linkis-mdm-service-hive-configmap.yaml -kubectl delete -f linkis-mdm-service-mysql-configmap.yaml - -kubectl delete -f linkis-gateway-deployment.yaml -kubectl delete -f linkis-bml-deployment.yaml -kubectl delete -f linkis-metadata-deployment.yaml -kubectl delete -f linkis-publicservice-deployment.yaml -kubectl delete -f linkis-resourcemanager-deployment.yaml -kubectl delete -f linkis-ujes-jdbc-entrance-deployment.yaml -kubectl delete -f linkis-ujes-hive-entrance-deployment.yaml -kubectl delete -f linkis-ujes-hive-enginemanager-deployment.yaml -kubectl delete -f linkis-ujes-mlsql-entrance-deployment.yaml -kubectl delete -f linkis-ujes-pipeline-entrance-deployment.yaml -kubectl delete -f linkis-ujes-pipeline-enginemanager-deployment.yaml -kubectl delete -f linkis-ujes-python-entrance-deployment.yaml -kubectl delete -f linkis-ujes-python-enginemanager-deployment.yaml -kubectl delete -f linkis-ujes-shell-entrance-deployment.yaml -kubectl delete -f linkis-ujes-shell-enginemanager-deployment.yaml -kubectl delete -f linkis-ujes-spark-entrance-deployment.yaml -kubectl delete -f linkis-ujes-spark-enginemanager-deployment.yaml - -kubectl delete -f linkis-gateway-service.yaml - -kubectl delete -f linkis-dsm-server-deployment.yaml -kubectl delete -f linkis-mdm-server-deployment.yaml -kubectl delete -f linkis-mdm-service-es-deployment.yaml -kubectl delete -f linkis-mdm-service-hive-deployment.yaml -kubectl delete -f linkis-mdm-service-mysql-deployment.yaml - - - diff --git a/k8s/ingress-nginx-controller.yaml b/k8s/ingress-nginx-controller.yaml deleted file mode 100644 index 910531082b..0000000000 --- a/k8s/ingress-nginx-controller.yaml +++ /dev/null @@ -1,678 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -kind: Namespace -metadata: - name: ingress-nginx - labels: - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - ---- -# Source: ingress-nginx/templates/controller-serviceaccount.yaml -apiVersion: v1 -kind: ServiceAccount -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx - namespace: ingress-nginx ---- -# Source: ingress-nginx/templates/controller-configmap.yaml -apiVersion: v1 -kind: ConfigMap -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx-controller - namespace: ingress-nginx -data: ---- -# Source: ingress-nginx/templates/clusterrole.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - name: ingress-nginx - namespace: ingress-nginx -rules: - - apiGroups: - - '' - resources: - - configmaps - - endpoints - - nodes - - pods - - secrets - verbs: - - list - - watch - - apiGroups: - - '' - resources: - - nodes - verbs: - - get - - apiGroups: - - '' - resources: - - services - verbs: - - get - - list - - update - - watch - - apiGroups: - - extensions - - networking.k8s.io # k8s 1.14+ - resources: - - ingresses - verbs: - - get - - list - - watch - - apiGroups: - - '' - resources: - - events - verbs: - - create - - patch - - apiGroups: - - extensions - - networking.k8s.io # k8s 1.14+ - resources: - - ingresses/status - verbs: - - update - - apiGroups: - - networking.k8s.io # k8s 1.14+ - resources: - - ingressclasses - verbs: - - get - - list - - watch ---- -# Source: ingress-nginx/templates/clusterrolebinding.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - name: ingress-nginx - namespace: ingress-nginx -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: ingress-nginx -subjects: - - kind: ServiceAccount - name: ingress-nginx - namespace: ingress-nginx ---- -# Source: ingress-nginx/templates/controller-role.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx - namespace: ingress-nginx -rules: - - apiGroups: - - '' - resources: - - namespaces - verbs: - - get - - apiGroups: - - '' - resources: - - configmaps - - pods - - secrets - - endpoints - verbs: - - get - - list - - watch - - apiGroups: - - '' - resources: - - services - verbs: - - get - - list - - update - - watch - - apiGroups: - - extensions - - networking.k8s.io # k8s 1.14+ - resources: - - ingresses - verbs: - - get - - list - - watch - - apiGroups: - - extensions - - networking.k8s.io # k8s 1.14+ - resources: - - ingresses/status - verbs: - - update - - apiGroups: - - networking.k8s.io # k8s 1.14+ - resources: - - ingressclasses - verbs: - - get - - list - - watch - - apiGroups: - - '' - resources: - - configmaps - resourceNames: - - ingress-controller-leader-nginx - verbs: - - get - - update - - apiGroups: - - '' - resources: - - configmaps - verbs: - - create - - apiGroups: - - '' - resources: - - endpoints - verbs: - - create - - get - - update - - apiGroups: - - '' - resources: - - events - verbs: - - create - - patch ---- -# Source: ingress-nginx/templates/controller-rolebinding.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx - namespace: ingress-nginx -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: ingress-nginx -subjects: - - kind: ServiceAccount - name: ingress-nginx - namespace: ingress-nginx ---- -# Source: ingress-nginx/templates/controller-service-webhook.yaml -apiVersion: v1 -kind: Service -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx-controller-admission - namespace: ingress-nginx -spec: - type: ClusterIP - ports: - - name: https-webhook - port: 443 - targetPort: webhook - selector: - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/component: controller ---- -# Source: ingress-nginx/templates/controller-service.yaml -apiVersion: v1 -kind: Service -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - name: ingress-nginx-controller - namespace: ingress-nginx -spec: - type: NodePort - ports: - - name: http - port: 80 - protocol: TCP - #targetPort: http - nodePort: 31234 - - name: https - port: 443 - protocol: TCP - #targetPort: https - nodePort: 31235 - selector: - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/component: controller ---- -# Source: ingress-nginx/templates/controller-deployment.yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: controller - nginx.ingress.kubernetes.io/proxy-connect-timeout: "600" - nginx.ingress.kubernetes.io/proxy-read-timeout: "600" - nginx.ingress.kubernetes.io/proxy-send-timeout: "600" - name: ingress-nginx-controller - namespace: ingress-nginx -spec: - selector: - matchLabels: - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/component: controller - revisionHistoryLimit: 10 - strategy: - rollingUpdate: - maxUnavailable: 1 - type: RollingUpdate - minReadySeconds: 0 - template: - metadata: - labels: - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/component: controller - spec: - dnsPolicy: ClusterFirst - containers: - - name: controller - image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.33.0 - imagePullPolicy: IfNotPresent - lifecycle: - preStop: - exec: - command: - - /wait-shutdown - args: - - /nginx-ingress-controller - - --election-id=ingress-controller-leader - - --ingress-class=nginx - - --configmap=ingress-nginx/ingress-nginx-controller - - --validating-webhook=:8443 - - --validating-webhook-certificate=/usr/local/certificates/cert - - --validating-webhook-key=/usr/local/certificates/key - - --publish-status-address=localhost - securityContext: - capabilities: - drop: - - ALL - add: - - NET_BIND_SERVICE - runAsUser: 101 - allowPrivilegeEscalation: true - env: - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - livenessProbe: - httpGet: - path: /healthz - port: 10254 - scheme: HTTP - initialDelaySeconds: 10 - periodSeconds: 10 - timeoutSeconds: 1 - successThreshold: 1 - failureThreshold: 3 - readinessProbe: - httpGet: - path: /healthz - port: 10254 - scheme: HTTP - initialDelaySeconds: 10 - periodSeconds: 10 - timeoutSeconds: 1 - successThreshold: 1 - failureThreshold: 3 - ports: - - name: http - containerPort: 80 - protocol: TCP - hostPort: 80 - - name: https - containerPort: 443 - protocol: TCP - hostPort: 443 - - name: webhook - containerPort: 8443 - protocol: TCP - volumeMounts: - - name: webhook-cert - mountPath: /usr/local/certificates/ - readOnly: true - resources: - requests: - cpu: 100m - memory: 90Mi - nodeSelector: - ingress-ready: 'true' - tolerations: - - effect: NoSchedule - key: node-role.kubernetes.io/master - operator: Equal - serviceAccountName: ingress-nginx - terminationGracePeriodSeconds: 0 - volumes: - - name: webhook-cert - secret: - secretName: ingress-nginx-admission ---- -# Source: ingress-nginx/templates/admission-webhooks/validating-webhook.yaml -apiVersion: admissionregistration.k8s.io/v1beta1 -kind: ValidatingWebhookConfiguration -metadata: - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - name: ingress-nginx-admission - namespace: ingress-nginx -webhooks: - - name: validate.nginx.ingress.kubernetes.io - rules: - - apiGroups: - - extensions - - networking.k8s.io - apiVersions: - - v1beta1 - operations: - - CREATE - - UPDATE - resources: - - ingresses - failurePolicy: Fail - clientConfig: - service: - namespace: ingress-nginx - name: ingress-nginx-controller-admission - path: /extensions/v1beta1/ingresses ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/clusterrole.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: ingress-nginx-admission - annotations: - helm.sh/hook: pre-install,pre-upgrade,post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -rules: - - apiGroups: - - admissionregistration.k8s.io - resources: - - validatingwebhookconfigurations - verbs: - - get - - update ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/clusterrolebinding.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: ingress-nginx-admission - annotations: - helm.sh/hook: pre-install,pre-upgrade,post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: ingress-nginx-admission -subjects: - - kind: ServiceAccount - name: ingress-nginx-admission - namespace: ingress-nginx ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/job-createSecret.yaml -apiVersion: batch/v1 -kind: Job -metadata: - name: ingress-nginx-admission-create - annotations: - helm.sh/hook: pre-install,pre-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -spec: - template: - metadata: - name: ingress-nginx-admission-create - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - spec: - containers: - - name: create - image: jettech/kube-webhook-certgen:v1.2.0 - imagePullPolicy: IfNotPresent - args: - - create - - --host=ingress-nginx-controller-admission,ingress-nginx-controller-admission.ingress-nginx.svc - - --namespace=ingress-nginx - - --secret-name=ingress-nginx-admission - restartPolicy: OnFailure - serviceAccountName: ingress-nginx-admission - securityContext: - runAsNonRoot: true - runAsUser: 2000 ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/job-patchWebhook.yaml -apiVersion: batch/v1 -kind: Job -metadata: - name: ingress-nginx-admission-patch - annotations: - helm.sh/hook: post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -spec: - template: - metadata: - name: ingress-nginx-admission-patch - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - spec: - containers: - - name: patch - image: jettech/kube-webhook-certgen:v1.2.0 - imagePullPolicy: IfNotPresent - args: - - patch - - --webhook-name=ingress-nginx-admission - - --namespace=ingress-nginx - - --patch-mutating=false - - --secret-name=ingress-nginx-admission - - --patch-failure-policy=Fail - restartPolicy: OnFailure - serviceAccountName: ingress-nginx-admission - securityContext: - runAsNonRoot: true - runAsUser: 2000 ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/role.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: ingress-nginx-admission - annotations: - helm.sh/hook: pre-install,pre-upgrade,post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -rules: - - apiGroups: - - '' - resources: - - secrets - verbs: - - get - - create ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/rolebinding.yaml -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: ingress-nginx-admission - annotations: - helm.sh/hook: pre-install,pre-upgrade,post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: ingress-nginx-admission -subjects: - - kind: ServiceAccount - name: ingress-nginx-admission - namespace: ingress-nginx ---- -# Source: ingress-nginx/templates/admission-webhooks/job-patch/serviceaccount.yaml -apiVersion: v1 -kind: ServiceAccount -metadata: - name: ingress-nginx-admission - annotations: - helm.sh/hook: pre-install,pre-upgrade,post-install,post-upgrade - helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded - labels: - helm.sh/chart: ingress-nginx-2.4.0 - app.kubernetes.io/name: ingress-nginx - app.kubernetes.io/instance: ingress-nginx - app.kubernetes.io/version: 0.33.0 - app.kubernetes.io/managed-by: Helm - app.kubernetes.io/component: admission-webhook - namespace: ingress-nginx \ No newline at end of file diff --git a/k8s/ingress.yaml b/k8s/ingress.yaml deleted file mode 100644 index 6811557df7..0000000000 --- a/k8s/ingress.yaml +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: extensions/v1beta1 -kind: Ingress -metadata: - name: linkis-gateway-ingress -spec: - rules: - - host: - http: - paths: - - path: /api - backend: - serviceName: linkis-gateway-service - servicePort: 14001 - - path: /ws - backend: - serviceName: linkis-gateway-service - servicePort: 14001 - - path: / - backend: - serviceName: scriptis-service - servicePort: 80 \ No newline at end of file diff --git a/k8s/init.sh b/k8s/init.sh deleted file mode 100644 index 61748af2ed..0000000000 --- a/k8s/init.sh +++ /dev/null @@ -1,58 +0,0 @@ -kubectl create -f register.yaml - -kubectl apply -f linkis-eureka-configmap.yaml - -kubectl create -f linkis-gateway-configmap.yaml -kubectl create -f linkis-metadata-configmap.yaml -kubectl create -f linkis-publicservice-configmap.yaml -kubectl create -f linkis-resourcemanager-configmap.yaml -kubectl create -f linkis-cs-server-configmap.yaml -kubectl create -f linkis-bml-configmap.yaml -kubectl create -f linkis-ujes-hive-enginemanager-configmap.yaml -kubectl create -f linkis-ujes-hive-entrance-configmap.yaml -kubectl create -f linkis-ujes-jdbc-entrance-configmap.yaml -kubectl create -f linkis-ujes-mlsql-entrance-configmap.yaml -kubectl create -f linkis-ujes-pipeline-enginemanager-configmap.yaml -kubectl create -f linkis-ujes-pipeline-entrance-configmap.yaml -kubectl create -f linkis-ujes-python-enginemanager-configmap.yaml -kubectl create -f linkis-ujes-python-entrance-configmap.yaml -kubectl create -f linkis-ujes-shell-enginemanager-configmap.yaml -kubectl create -f linkis-ujes-shell-entrance-configmap.yaml -kubectl create -f linkis-ujes-spark-entrance-configmap.yaml -kubectl create -f linkis-ujes-spark-enginemanager-configmap.yaml - -kubectl create -f linkis-dsm-server-configmap.yaml -kubectl create -f linkis-mdm-server-configmap.yaml -kubectl create -f linkis-mdm-service-es-configmap.yaml -kubectl create -f linkis-mdm-service-hive-configmap.yaml -kubectl create -f linkis-mdm-service-mysql-configmap.yaml - - -kubectl create -f linkis-gateway-deployment.yaml -kubectl create -f linkis-bml-deployment.yaml -kubectl create -f linkis-metadata-deployment.yaml -kubectl create -f linkis-publicservice-deployment.yaml -kubectl create -f linkis-resourcemanager-deployment.yaml -kubectl create -f linkis-cs-server-deployment.yaml -kubectl create -f linkis-ujes-jdbc-entrance-deployment.yaml -kubectl create -f linkis-ujes-hive-entrance-deployment.yaml -kubectl create -f linkis-ujes-hive-enginemanager-deployment.yaml -kubectl create -f linkis-ujes-mlsql-entrance-deployment.yaml -kubectl create -f linkis-ujes-pipeline-entrance-deployment.yaml -kubectl create -f linkis-ujes-pipeline-enginemanager-deployment.yaml -kubectl create -f linkis-ujes-python-entrance-deployment.yaml -kubectl create -f linkis-ujes-python-enginemanager-deployment.yaml -kubectl create -f linkis-ujes-shell-entrance-deployment.yaml -kubectl create -f linkis-ujes-shell-enginemanager-deployment.yaml -kubectl create -f linkis-ujes-spark-entrance-deployment.yaml -kubectl create -f linkis-ujes-spark-enginemanager-deployment.yaml - -kubectl create -f linkis-gateway-service.yaml - - -kubectl create -f linkis-dsm-server-deployment.yaml -kubectl create -f linkis-mdm-server-deployment.yaml -kubectl create -f linkis-mdm-service-es-deployment.yaml -kubectl create -f linkis-mdm-service-hive-deployment.yaml -kubectl create -f linkis-mdm-service-mysql-deployment.yaml - diff --git a/k8s/linkis-bml-configmap.yaml b/k8s/linkis-bml-configmap.yaml deleted file mode 100644 index 0ced16555d..0000000000 --- a/k8s/linkis-bml-configmap.yaml +++ /dev/null @@ -1,46 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/bml/dao/impl/*.xml - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.bml.dao - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.bml.dao - wds.test.mode=true - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.bml.restful - - #sit - wds.linkis.server.mybatis.datasource.url= - wds.linkis.server.mybatis.datasource.username= - wds.linkis.server.mybatis.datasource.password= - wds.linkis.server.version=v1 - - #hadoop.config.dir - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-bml-config - namespace: default - diff --git a/k8s/linkis-bml-deployment.yaml b/k8s/linkis-bml-deployment.yaml deleted file mode 100644 index 390ebd128c..0000000000 --- a/k8s/linkis-bml-deployment.yaml +++ /dev/null @@ -1,111 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-bml-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-bml - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - - template: - metadata: - labels: - app: linkis-bml - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-bml - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-bml - image: wedatasphere/linkis:linkis-bml-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-bml/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14009 - livenessProbe: - tcpSocket: - port: 14009 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14009" - volumeMounts: - - name: linkis-bml-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-bml/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: eureka-config - configMap: - name: eureka-config - - name: linkis-bml-config - configMap: - name: linkis-bml-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-cs-server-configmap.yaml b/k8s/linkis-cs-server-configmap.yaml deleted file mode 100644 index 4ed38082ef..0000000000 --- a/k8s/linkis-cs-server-configmap.yaml +++ /dev/null @@ -1,44 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - #wds.linkis.test.mode=true - wds.linkis.server.mybatis.datasource.url=jdbc:mysql://127.0.0.1:3306/ide_gz_bdap_sit_01?characterEncoding=UTF-8 - wds.linkis.server.mybatis.datasource.username= - wds.linkis.server.mybatis.datasource.password= - wds.linkis.log.clear=true - wds.linkis.server.version=v1 - ##restful - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.cs.server.restful - ##mybatis - wds.linkis.server.mybatis.mapperLocations=classpath*:com\\webank\\wedatasphere\\linkis\\cs\\persistence\\dao\\impl\\*.xml - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.cs.persistence.entity - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.cs.persistence.dao - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-cs-server.properties: {} - manager: kubectl - operation: Update - name: linkis-cs-server-config - namespace: default - diff --git a/k8s/linkis-cs-server-deployment.yaml b/k8s/linkis-cs-server-deployment.yaml deleted file mode 100644 index 1afcd5a1e8..0000000000 --- a/k8s/linkis-cs-server-deployment.yaml +++ /dev/null @@ -1,115 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-cs-server-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-cs-server - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-cs-server - release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-cs-server - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-cs-server - image: wedatasphere/linkis:linkis-cs-server-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-cs-server/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14004 - livenessProbe: - tcpSocket: - port: 14004 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14004" - volumeMounts: - - name: linkis-cs-server-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-cs-server/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-cs-server-config - configMap: - name: linkis-cs-server-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-dsm-server-configmap.yaml b/k8s/linkis-dsm-server-configmap.yaml deleted file mode 100644 index 835fdb9cfd..0000000000 --- a/k8s/linkis-dsm-server-configmap.yaml +++ /dev/null @@ -1,68 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - # - # Copyright 2019 WeBank - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # http://www.apache.org/licenses/LICENSE-2.0 - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - - wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/datasourcemanager/core/dao/mapper/*.xml - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.datasourcemanager.common.domain - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.datasourcemanager.core.dao - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.datasourcemanager.core.restful - - #sit - wds.linkis.server.version=v1 - - #test - wds.linkis.test.mode=true - wds.linkis.test.user= - wds.linkis.server.mybatis.datasource.url= - wds.linkis.server.mybatis.datasource.username= - wds.linkis.server.mybatis.datasource.password= - - #dsm - wds.linkis.server.dsm.admin.users= - - #bml - wds.linkis.gateway.ip= - wds.linkis.gateway.port= - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-dsm-server-config - namespace: default - diff --git a/k8s/linkis-dsm-server-deployment.yaml b/k8s/linkis-dsm-server-deployment.yaml deleted file mode 100644 index 175c8af0fd..0000000000 --- a/k8s/linkis-dsm-server-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-dsm-server-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-dsm-server - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-dsm-server - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-dsm-server - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-dsm-server - image: wedatasphere/linkis:linkis-dsm-server-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-dsm-server/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 22000 - livenessProbe: - tcpSocket: - port: 22000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "22000" - volumeMounts: - - name: linkis-dsm-server-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-dsm-server/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: eureka-config - configMap: - name: eureka-config - - name: linkis-dsm-server-config - configMap: - name: linkis-dsm-server-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-eureka-configmap.yaml b/k8s/linkis-eureka-configmap.yaml deleted file mode 100644 index 03d4c1d7cf..0000000000 --- a/k8s/linkis-eureka-configmap.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -kind: ConfigMap -metadata: - name: eureka-config -data: - eurekaUrl: http://10.206.0.12:20230/eureka/ - diff --git a/k8s/linkis-gateway-configmap.yaml b/k8s/linkis-gateway-configmap.yaml deleted file mode 100644 index cdfb4fe47b..0000000000 --- a/k8s/linkis-gateway-configmap.yaml +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - wds.linkis.test.mode=true - wds.linkis.server.version=v1 - wds.linkis.ldap.proxy.url= - wds.linkis.ldap.proxy.baseDN= - wds.linkis.server.restful.uri=/ - wds.linkis.server.web.session.timeout=1h - wds.linkis.gateway.conf.enable.proxy.user=false - wds.linkis.gateway.conf.url.pass.auth=/dws/ - wds.linkis.gateway.admin.user=root - wds.linkis.gateway.conf.enable.token.auth=true - #wds.linkis.gateway.conf.enable.sso=true - wds.linkis.gateway.conf.enable.cloud-publicservice=true - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-gateway.properties: {} - manager: kubectl - operation: Update - name: linkis-gateway-config - namespace: default - diff --git a/k8s/linkis-gateway-deployment.yaml b/k8s/linkis-gateway-deployment.yaml deleted file mode 100644 index 71acf981c7..0000000000 --- a/k8s/linkis-gateway-deployment.yaml +++ /dev/null @@ -1,110 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-gateway-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-gateway - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - - template: - metadata: - labels: - app: linkis-gateway - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-gateway - topologyKey: "kubernetes.io/hostname" - - containers: - - name: linkis-gateway - image: wedatasphere/linkis:linkis-gateway-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-gateway/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14001 - protocol: TCP - livenessProbe: - tcpSocket: - port: 14001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14001" - volumeMounts: - - name: linkis-gateway-config - mountPath: /opt/linkis/conf -# - name: resultset -# mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-gateway/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-gateway-config - configMap: - name: linkis-gateway-config -# - name: resultset -# nfs: -# path: /data/k8s -# server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-gateway-service.yaml b/k8s/linkis-gateway-service.yaml deleted file mode 100644 index 73b2aeb28a..0000000000 --- a/k8s/linkis-gateway-service.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -kind: Service -metadata: - name: linkis-gateway-service -spec: - selector: - app: linkis-gateway - ports: - - name: http - port: 14001 - protocol: TCP - targetPort: 14001 - nodePort: 32111 - type: NodePort diff --git a/k8s/linkis-mdm-server-configmap.yaml b/k8s/linkis-mdm-server-configmap.yaml deleted file mode 100644 index 6631a49347..0000000000 --- a/k8s/linkis-mdm-server-configmap.yaml +++ /dev/null @@ -1,57 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - # - # Copyright 2019 WeBank - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # http://www.apache.org/licenses/LICENSE-2.0 - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - - wds.linkis.server.mybatis.mapperLocations= - wds.linkis.server.mybatis.typeAliasesPackage= - wds.linkis.server.mybatis.BasePackage= - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.metadatamanager.server.restful - - #sit - wds.linkis.server.version=v1 - - #test - wds.linkis.test.mode=true - wds.linkis.test.user=davidhua - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-mdm-server-config - namespace: default - diff --git a/k8s/linkis-mdm-server-deployment.yaml b/k8s/linkis-mdm-server-deployment.yaml deleted file mode 100644 index f6c3c5ed01..0000000000 --- a/k8s/linkis-mdm-server-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-mdm-server-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-mdm-server - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-mdm-server - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-mdm-server - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-mdm-server - image: wedatasphere/linkis:linkis-mdm-server-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-mdm-server/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 22001 - livenessProbe: - tcpSocket: - port: 22001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "22001" - volumeMounts: - - name: linkis-mdm-server-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-mdm-server/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-mdm-server-config - configMap: - name: linkis-mdm-server-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-mdm-service-es-configmap.yaml b/k8s/linkis-mdm-service-es-configmap.yaml deleted file mode 100644 index 6ea3ee0b39..0000000000 --- a/k8s/linkis-mdm-service-es-configmap.yaml +++ /dev/null @@ -1,55 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - # - # Copyright 2019 WeBank - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # http://www.apache.org/licenses/LICENSE-2.0 - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - - wds.linkis.server.mybatis.mapperLocations= - wds.linkis.server.mybatis.typeAliasesPackage= - wds.linkis.server.mybatis.BasePackage= - wds.linkis.server.restful.scan.packages= - - #sit - wds.linkis.server.version=v1 - - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-mdm-service-es-config - namespace: default - diff --git a/k8s/linkis-mdm-service-es-deployment.yaml b/k8s/linkis-mdm-service-es-deployment.yaml deleted file mode 100644 index 26ce240c34..0000000000 --- a/k8s/linkis-mdm-service-es-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-mdm-service-es-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-mdm-service-es - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-mdm-service-es - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-mdm-service-es - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-mdm-service-es - image: wedatasphere/linkis:linkis-mdm-service-es-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-mdm-service-es/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 22002 - livenessProbe: - tcpSocket: - port: 22002 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "22002" - volumeMounts: - - name: linkis-mdm-service-es-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-mdm-service-es/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-mdm-service-es-config - configMap: - name: linkis-mdm-service-es-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-mdm-service-hive-configmap.yaml b/k8s/linkis-mdm-service-hive-configmap.yaml deleted file mode 100644 index 518b2f480d..0000000000 --- a/k8s/linkis-mdm-service-hive-configmap.yaml +++ /dev/null @@ -1,59 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - # - # Copyright 2019 WeBank - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # http://www.apache.org/licenses/LICENSE-2.0 - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - - wds.linkis.server.mybatis.mapperLocations= - wds.linkis.server.mybatis.typeAliasesPackage= - wds.linkis.server.mybatis.BasePackage= - wds.linkis.server.restful.scan.packages= - - #sit - wds.linkis.server.version=v1 - - #bml - wds.linkis.gateway.ip= - wds.linkis.gateway.port= - - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-mdm-service-hive-config - namespace: default - diff --git a/k8s/linkis-mdm-service-hive-deployment.yaml b/k8s/linkis-mdm-service-hive-deployment.yaml deleted file mode 100644 index 4ff8fdf7d8..0000000000 --- a/k8s/linkis-mdm-service-hive-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-mdm-service-hive-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-mdm-service-hive - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-mdm-service-hive - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-mdm-service-hive - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-mdm-service-hive - image: wedatasphere/linkis:linkis-mdm-service-hive-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-mdm-service-hive/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 22003 - livenessProbe: - tcpSocket: - port: 22003 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "22003" - volumeMounts: - - name: linkis-mdm-service-hive-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-mdm-service-hive/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-mdm-service-hive-config - configMap: - name: linkis-mdm-service-hive-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-mdm-service-mysql-configmap.yaml b/k8s/linkis-mdm-service-mysql-configmap.yaml deleted file mode 100644 index 096d8ee88c..0000000000 --- a/k8s/linkis-mdm-service-mysql-configmap.yaml +++ /dev/null @@ -1,53 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - # - # Copyright 2019 WeBank - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # http://www.apache.org/licenses/LICENSE-2.0 - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. - # - - wds.linkis.server.mybatis.mapperLocations= - wds.linkis.server.mybatis.typeAliasesPackage= - wds.linkis.server.mybatis.BasePackage= - wds.linkis.server.restful.scan.packages= - - #sit - wds.linkis.server.version=v1 - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-bml.properties: {} - manager: kubectl - operation: Update - name: linkis-mdm-service-mysql-config - namespace: default - diff --git a/k8s/linkis-mdm-service-mysql-deployment.yaml b/k8s/linkis-mdm-service-mysql-deployment.yaml deleted file mode 100644 index 34d4b9d9d3..0000000000 --- a/k8s/linkis-mdm-service-mysql-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-mdm-service-mysql-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-mdm-service-mysql - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-mdm-service-mysql - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-mdm-service-mysql - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-mdm-service-mysql - image: wedatasphere/linkis:linkis-mdm-service-mysql-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-mdm-service-mysql/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 22004 - livenessProbe: - tcpSocket: - port: 22004 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "22004" - volumeMounts: - - name: linkis-mdm-service-mysql-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-mdm-service-mysql/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-mdm-service-mysql-config - configMap: - name: linkis-mdm-service-mysql-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-metadata-configmap.yaml b/k8s/linkis-metadata-configmap.yaml deleted file mode 100644 index 7f1c6623eb..0000000000 --- a/k8s/linkis-metadata-configmap.yaml +++ /dev/null @@ -1,64 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - #wds.linkis.test.mode=true - - wds.linkis.server.mybatis.datasource.url=${mysql.url} - - wds.linkis.server.mybatis.datasource.username=${mysql.username} - - wds.linkis.server.mybatis.datasource.password=${mysql.password} - - - wds.linkis.log.clear=true - wds.linkis.server.version=v1 - - ##restful - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.metadata.restful.api - - ##mybatis - wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/metadata/hive/dao/impl/*.xml,com/webank/wedatasphere/linkis/metadata/dao/impl/*.xml - - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.metadata.domain - - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.metadata.hive.dao,com.webank.wedatasphere.linkis.metadata.dao - - ##datasource - hive.meta.url=${hivemeta.url} - hive.meta.user=${hivemeta.username} - hive.meta.password=${hivemeta.password} - - #hive.config.dir - - - wds.linkis.engine.creation.wait.time.max=2m - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-metadata.properties: {} - manager: kubectl - operation: Update - name: linkis-metadata-config - namespace: default - diff --git a/k8s/linkis-metadata-deployment.yaml b/k8s/linkis-metadata-deployment.yaml deleted file mode 100644 index 8b896502d2..0000000000 --- a/k8s/linkis-metadata-deployment.yaml +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-metadata-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-metadata - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-metadata - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-metadata - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-metadata - image: wedatasphere/linkis:linkis-metadata-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-metadata/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14002 - livenessProbe: - tcpSocket: - port: 14002 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14002" - volumeMounts: - - name: linkis-metadata-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-metadata/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-metadata-config - configMap: - name: linkis-metadata-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-publicservice-configmap.yaml b/k8s/linkis-publicservice-configmap.yaml deleted file mode 100644 index d3ae969ee7..0000000000 --- a/k8s/linkis-publicservice-configmap.yaml +++ /dev/null @@ -1,69 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - #wds.linkis.test.mode=true - - wds.linkis.server.mybatis.datasource.url=${mysql.url} - - wds.linkis.server.mybatis.datasource.username=${mysql.username} - - wds.linkis.server.mybatis.datasource.password=${mysql.password} - - - wds.linkis.log.clear=true - wds.linkis.server.version=v1 - - ##restful - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.jobhistory.restful,com.webank.wedatasphere.linkis.variable.restful,com.webank.wedatasphere.linkis.application.restful,com.webank.wedatasphere.linkis.configuration.restful,com.webank.wedatasphere.linkis.udf.api,com.webank.wedatasphere.linkis.filesystem.restful - - ##mybatis - wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/jobhistory/dao/impl/*.xml,classpath:com/webank/wedatasphere/linkis/variable/dao/impl/*.xml,classpath:com/webank/wedatasphere/linkis/application/dao/impl/*.xml,classpath:com/webank/wedatasphere/linkis/configuration/dao/impl/*.xml,classpath:com/webank/wedatasphere/linkis/udf/dao/impl/*.xml - - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.application.entity,com.webank.wedatasphere.linkis.configuration.entity,com.webank.wedatasphere.linkis.query.entity,com.webank.wedatasphere.linkis.udf.entity,com.webank.wedatasphere.linkis.variable.entity - - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.jobhistory.dao,com.webank.wedatasphere.linkis.variable.dao,com.webank.wedatasphere.linkis.application.dao,com.webank.wedatasphere.linkis.configuration.dao,com.webank.wedatasphere.linkis.udf.dao - - ##workspace - wds.linkis.workspace.filesystem.localuserrootpath=hdfs:///tmp/ - wds.linkis.workspace.filesystem.hdfsuserrootpath.prefix=hdfs:///tmp/ - wds.linkis.workspace.filesystem.hdfsuserrootpath.suffix=/linkis/ - - #hadoopconfig - #hadoop.config.dir - - ##UDF - wds.linkis.storage.is.share.node=true - wds.linkis.gateway.ip=linkis-gateway.sit.ihomefnt.org - wds.linkis.gateway.port=13429 - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-publicservice.properties: {} - manager: kubectl - operation: Update - name: linkis-publicservice-config - namespace: default - diff --git a/k8s/linkis-publicservice-deployment.yaml b/k8s/linkis-publicservice-deployment.yaml deleted file mode 100644 index 5e2175ff48..0000000000 --- a/k8s/linkis-publicservice-deployment.yaml +++ /dev/null @@ -1,113 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-publicservice-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-publicservice - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-publicservice - release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-publicservice - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-publicservice - image: wedatasphere/linkis:linkis-publicservice-0.11.0 - imagePullPolicy: Always - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-publicservice/bin/stop.sh"] - ports: - - name: http - containerPort: 14003 - livenessProbe: - tcpSocket: - port: 14003 - initialDelaySeconds: 30 - periodSeconds: 60 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14003" - volumeMounts: - - name: linkis-publicservice-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-publicservice/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-publicservice-config - configMap: - name: linkis-publicservice-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-resourcemanager-configmap.yaml b/k8s/linkis-resourcemanager-configmap.yaml deleted file mode 100644 index 0c498bf78b..0000000000 --- a/k8s/linkis-resourcemanager-configmap.yaml +++ /dev/null @@ -1,46 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - #wds.linkis.test.mode=true - wds.linkis.server.mybatis.datasource.url=${mysql.url} - wds.linkis.server.mybatis.datasource.username=${mysql.username} - wds.linkis.server.mybatis.datasource.password=${mysql.password} - wds.linkis.log.clear=true - wds.linkis.server.version=v1 - ##restful - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.resourcemanager.restful - ##mybatis - wds.linkis.server.mybatis.mapperLocations=classpath:com/webank/wedatasphere/linkis/resourcemanager/dao/impl/*.xml - wds.linkis.server.mybatis.typeAliasesPackage=com.webank.wedatasphere.linkis.resourcemanager.dao - wds.linkis.server.mybatis.BasePackage=com.webank.wedatasphere.linkis.resourcemanager.dao - wds.linkis.yarn.rm.web.address=http://zt-hadoop.sit.ihomefnt.org:18088 - #hadoop.config.dir= - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-resourcemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-resourcemanager-config - namespace: default - diff --git a/k8s/linkis-resourcemanager-deployment.yaml b/k8s/linkis-resourcemanager-deployment.yaml deleted file mode 100644 index f761161937..0000000000 --- a/k8s/linkis-resourcemanager-deployment.yaml +++ /dev/null @@ -1,115 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-resourcemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-resourcemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-resourcemanager - release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-resourcemanager - topologyKey: "kubernetes.io/hostname" - containers: - - name: linkis-resourcemanager - image: wedatasphere/linkis:linkis-resourcemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-resourcemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14004 - livenessProbe: - tcpSocket: - port: 14004 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14004" - volumeMounts: - - name: linkis-resourcemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-resourcemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-resourcemanager-config - configMap: - name: linkis-resourcemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-hive-enginemanager-configmap.yaml b/k8s/linkis-ujes-hive-enginemanager-configmap.yaml deleted file mode 100644 index f83fc225f1..0000000000 --- a/k8s/linkis-ujes-hive-enginemanager-configmap.yaml +++ /dev/null @@ -1,48 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=hiveEngine - wds.linkis.server.component.exclude.packages=com.webank.wedatasphere.linkis.engine.,com.webank.wedatasphere.linkis.udf. - wds.linkis.server.version=v1 - - #sudo script - wds.linkis.enginemanager.sudo.script=/appcom/Install/WillinkInstall/linkis-ujes-spark-enginemanager/bin/rootScript.sh - - #hadoop config - #hadoop.config.dir=/appcom/config/hadoop-config - - #hive config - #hive.config.dir= - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-hive-enginemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-hive-enginemanager-config - namespace: default - diff --git a/k8s/linkis-ujes-hive-enginemanager-deployment.yaml b/k8s/linkis-ujes-hive-enginemanager-deployment.yaml deleted file mode 100644 index 87f27cf7a8..0000000000 --- a/k8s/linkis-ujes-hive-enginemanager-deployment.yaml +++ /dev/null @@ -1,124 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-hive-enginemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-hive-enginemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-hive-enginemanager - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-hive-enginemanager - - linkis-ujes-spark-enginemanager - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node1 - containers: - - name: linkis-ujes-hive-enginemanager - image: wedatasphere/linkis:linkis-ujes-hive-enginemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-hive-enginemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 16001 - livenessProbe: - tcpSocket: - port: 16001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "16001" - volumeMounts: - - name: linkis-ujes-hive-enginemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-hive-enginemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-hive-enginemanager-config - configMap: - name: linkis-ujes-hive-enginemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-hive-entrance-configmap.yaml b/k8s/linkis-ujes-hive-entrance-configmap.yaml deleted file mode 100644 index af81b47c7f..0000000000 --- a/k8s/linkis-ujes-hive-entrance-configmap.yaml +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=hiveEngine - wds.linkis.enginemanager.application.name=hiveEngineManager - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=20m - wds.linkis.server.version=v1 - #hadoop config dir - #hadoop.config.dir=/appcom/config/hadoop-config - wds.linkis.entrance.config.logPath=file:///appcom/logs/dataworkcloud/dwc/ - - wds.linkis.resultSet.store.path=hdfs:/// - - wds.linkis.server.socket.mode=true - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-hive-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-hive-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-hive-entrance-deployment.yaml b/k8s/linkis-ujes-hive-entrance-deployment.yaml deleted file mode 100644 index 1af0d8fbf8..0000000000 --- a/k8s/linkis-ujes-hive-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-hive-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-hive-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-hive-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-hive-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node1 - containers: - - name: linkis-ujes-hive-entrance - image: wedatasphere/linkis:linkis-ujes-hive-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-hive-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 16000 - livenessProbe: - tcpSocket: - port: 16000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "16000" - volumeMounts: - - name: linkis-ujes-hive-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-hive-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-hive-entrance-config - configMap: - name: linkis-ujes-hive-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-jdbc-entrance-configmap.yaml b/k8s/linkis-ujes-jdbc-entrance-configmap.yaml deleted file mode 100644 index 614659cfec..0000000000 --- a/k8s/linkis-ujes-jdbc-entrance-configmap.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=jdbcEngine - wds.linkis.enginemanager.application.name=jdbc - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=2m - wds.linkis.server.version=v1 - #hadoop.config.dir= - wds.linkis.entrance.config.logPath=hdfs://zt-hadoop1.sit.ihomefnt.org:9000/tmp/linkis/log - - wds.linkis.resultSet.store.path=hdfs://zt-hadoop.sit.ihomefnt.org:9000/tmp/linkis/resultset - - wds.linkis.server.socket.mode=true - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-jdbc-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-jdbc-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-jdbc-entrance-deployment.yaml b/k8s/linkis-ujes-jdbc-entrance-deployment.yaml deleted file mode 100644 index 978e0e3723..0000000000 --- a/k8s/linkis-ujes-jdbc-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-jdbc-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-jdbc-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-jdbc-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-jdbc-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-jdbc-entrance - image: wedatasphere/linkis:linkis-ujes-jdbc-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-jdbc-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 14008 - livenessProbe: - tcpSocket: - port: 14008 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "14008" - volumeMounts: - - name: linkis-ujes-jdbc-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-jdbc-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-jdbc-entrance-config - configMap: - name: linkis-ujes-jdbc-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-mlsql-entrance-configmap.yaml b/k8s/linkis-ujes-mlsql-entrance-configmap.yaml deleted file mode 100644 index f2fc29d62d..0000000000 --- a/k8s/linkis-ujes-mlsql-entrance-configmap.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=mlsqlEngine - wds.linkis.enginemanager.application.name=mlsql - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=20m - wds.linkis.server.version=v1 - # hadoop.config.dir= - wds.linkis.entrance.config.logPath=file:///tmp/linkis/ - - wds.linkis.resultSet.store.path=file:///tmp/linkis - - wds.linkis.server.socket.mode=true - # wds.linkis.test.mode=true - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-mlsql-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-mlsql-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-mlsql-entrance-deployment.yaml b/k8s/linkis-ujes-mlsql-entrance-deployment.yaml deleted file mode 100644 index f5fe63a703..0000000000 --- a/k8s/linkis-ujes-mlsql-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-mlsql-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-mlsql-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-mlsql-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-mlsql-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-mlsql-entrance - image: wedatasphere/linkis:linkis-ujes-mlsql-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-mlsql-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 17000 - livenessProbe: - tcpSocket: - port: 17000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "17000" - volumeMounts: - - name: linkis-ujes-mlsql-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-mlsql-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-mlsql-entrance-config - configMap: - name: linkis-ujes-mlsql-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-pipeline-enginemanager-configmap.yaml b/k8s/linkis-ujes-pipeline-enginemanager-configmap.yaml deleted file mode 100644 index 5c5c792426..0000000000 --- a/k8s/linkis-ujes-pipeline-enginemanager-configmap.yaml +++ /dev/null @@ -1,46 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=pipeLineEngine - wds.linkis.server.component.exclude.packages=com.webank.wedatasphere.linkis.engine.,com.webank.wedatasphere.linkis.udf. - - wds.linkis.console.config.application.name=cloud-publicservice - #hadoop.config.dir=/appcom/config/hadoop-config - #spark.config.dir=/appcom/config/spark-config - - #rootScript shell path - wds.linkis.enginemanager.sudo.script=/appcom/tmp/johnnwang/Install/linkis-ujes-spark-enginemanager/bin/rootScript.sh - wds.linkis.server.version=v1 - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-pipeline-enginemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-pipeline-enginemanager-config - namespace: default - diff --git a/k8s/linkis-ujes-pipeline-enginemanager-deployment.yaml b/k8s/linkis-ujes-pipeline-enginemanager-deployment.yaml deleted file mode 100644 index c2117d5282..0000000000 --- a/k8s/linkis-ujes-pipeline-enginemanager-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-pipeline-enginemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-pipeline-enginemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-pipeline-enginemanager - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-pipeline-enginemanager - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-mlsql-entrance - image: wedatasphere/linkis:linkis-ujes-pipeline-enginemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-pipeline-enginemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 18001 - livenessProbe: - tcpSocket: - port: 18001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "18001" - volumeMounts: - - name: linkis-ujes-pipeline-enginemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-pipeline-enginemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-pipeline-enginemanager-config - configMap: - name: linkis-ujes-pipeline-enginemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-pipeline-entrance-configmap.yaml b/k8s/linkis-ujes-pipeline-entrance-configmap.yaml deleted file mode 100644 index 9c36b03f70..0000000000 --- a/k8s/linkis-ujes-pipeline-entrance-configmap.yaml +++ /dev/null @@ -1,57 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=pipeLineEngine - wds.linkis.enginemanager.application.name=pipeLineEngineManager - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=20m - - - wds.linkis.resultSet.store.path=hdfs:/// - - wds.linkis.server.version=v1 - wds.linkis.server.socket.mode=true - - bdp.server.distinct.mode=true - - #hadoop.config.dir=/appcom/config/hadoop-config - #spark.config.dir=/appcom/config/spark-config - - - - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-pipeline-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-pipeline-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-pipeline-entrance-deployment.yaml b/k8s/linkis-ujes-pipeline-entrance-deployment.yaml deleted file mode 100644 index 9a57472b30..0000000000 --- a/k8s/linkis-ujes-pipeline-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-pipeline-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-pipeline-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-pipeline-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-pipeline-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-pipeline-entrance - image: wedatasphere/linkis:linkis-ujes-pipeline-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-pipeline-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 18000 - livenessProbe: - tcpSocket: - port: 18000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "18000" - volumeMounts: - - name: linkis-ujes-pipeline-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-pipeline-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-pipeline-entrance-config - configMap: - name: linkis-ujes-pipeline-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-python-enginemanager-configmap.yaml b/k8s/linkis-ujes-python-enginemanager-configmap.yaml deleted file mode 100644 index b6af7f0593..0000000000 --- a/k8s/linkis-ujes-python-enginemanager-configmap.yaml +++ /dev/null @@ -1,40 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=pythonEngine - wds.linkis.server.component.exclude.packages=com.webank.wedatasphere.linkis.engine.,com.webank.wedatasphere.linkis.udf. - wds.linkis.server.version=v1 - wds.linkis.enginemanager.sudo.script=rootScript.sh - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-python-enginemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-python-enginemanager-config - namespace: default - diff --git a/k8s/linkis-ujes-python-enginemanager-deployment.yaml b/k8s/linkis-ujes-python-enginemanager-deployment.yaml deleted file mode 100644 index 055e84950c..0000000000 --- a/k8s/linkis-ujes-python-enginemanager-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-python-enginemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-python-enginemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-python-enginemanager - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-python-enginemanager - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-python-enginemanager - image: wedatasphere/linkis:linkis-ujes-python-enginemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-python-enginemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 19001 - livenessProbe: - tcpSocket: - port: 19001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "19001" - volumeMounts: - - name: linkis-ujes-python-enginemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-python-enginemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-python-enginemanager-config - configMap: - name: linkis-ujes-python-enginemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-python-entrance-configmap.yaml b/k8s/linkis-ujes-python-entrance-configmap.yaml deleted file mode 100644 index c6f3e61a44..0000000000 --- a/k8s/linkis-ujes-python-entrance-configmap.yaml +++ /dev/null @@ -1,53 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=pythonEngine - wds.linkis.enginemanager.application.name=pythonEngineManager - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.configuration.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=2m - wds.linkis.server.version=v1 - - wds.linkis.entrance.config.logPath=file:///appcom/logs/dataworkcloud/dwc/ - - wds.linkis.server.socket.mode=true - - - #hadoop.config.dir=/appcom/config/hadoop-config - - wds.linkis.resultSet.store.path=hdfs:/// - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-python-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-python-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-python-entrance-deployment.yaml b/k8s/linkis-ujes-python-entrance-deployment.yaml deleted file mode 100644 index 75ad9b1860..0000000000 --- a/k8s/linkis-ujes-python-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-python-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-python-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-python-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-python-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node3 - containers: - - name: linkis-ujes-python-entrance - image: wedatasphere/linkis:linkis-ujes-python-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-python-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 19000 - livenessProbe: - tcpSocket: - port: 19000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "19000" - volumeMounts: - - name: linkis-ujes-python-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-python-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-python-entrance-config - configMap: - name: linkis-ujes-python-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-shell-enginemanager-configmap.yaml b/k8s/linkis-ujes-shell-enginemanager-configmap.yaml deleted file mode 100644 index c8cee63a48..0000000000 --- a/k8s/linkis-ujes-shell-enginemanager-configmap.yaml +++ /dev/null @@ -1,38 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=shellEngine - wds.linkis.server.component.exclude.packages=com.webank.wedatasphere.linkis.engine.,com.webank.wedatasphere.linkis.udf. - wds.linkis.server.version=v1 - #sudo script - wds.linkis.enginemanager.sudo.script=rootScript.sh - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-shell-enginemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-shell-enginemanager-config - namespace: default - diff --git a/k8s/linkis-ujes-shell-enginemanager-deployment.yaml b/k8s/linkis-ujes-shell-enginemanager-deployment.yaml deleted file mode 100644 index 24c7d14ea0..0000000000 --- a/k8s/linkis-ujes-shell-enginemanager-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-shell-enginemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-shell-enginemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-shell-enginemanager - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-shell-enginemanager - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node2 - containers: - - name: linkis-ujes-shell-enginemanager - image: wedatasphere/linkis:linkis-ujes-shell-enginemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-shell-enginemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 20001 - livenessProbe: - tcpSocket: - port: 20001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "20001" - volumeMounts: - - name: linkis-ujes-shell-enginemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-shell-enginemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-shell-enginemanager-config - configMap: - name: linkis-ujes-shell-enginemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-shell-entrance-configmap.yaml b/k8s/linkis-ujes-shell-entrance-configmap.yaml deleted file mode 100644 index 26f2801065..0000000000 --- a/k8s/linkis-ujes-shell-entrance-configmap.yaml +++ /dev/null @@ -1,42 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=shellEngine - wds.linkis.enginemanager.application.name=shellEngineManager - wds.linkis.query.application.name=cloud-publicservice - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=20m - wds.linkis.server.version=v1 - wds.linkis.entrance.config.logPath=file:///tmp/linkis/ - wds.linkis.resultSet.store.path=file:///tmp/linkis - wds.linkis.server.socket.mode=true - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-shell-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-shell-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-shell-entrance-deployment.yaml b/k8s/linkis-ujes-shell-entrance-deployment.yaml deleted file mode 100644 index 54d39694f0..0000000000 --- a/k8s/linkis-ujes-shell-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-shell-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-shell-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-shell-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-shell-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node2 - containers: - - name: linkis-ujes-shell-entrance - image: wedatasphere/linkis:linkis-ujes-shell-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-shell-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 20000 - livenessProbe: - tcpSocket: - port: 20000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "20000" - volumeMounts: - - name: linkis-ujes-shell-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-shell-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-shell-entrance-config - configMap: - name: linkis-ujes-shell-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-spark-enginemanager-configmap.yaml b/k8s/linkis-ujes-spark-enginemanager-configmap.yaml deleted file mode 100644 index 24971c3643..0000000000 --- a/k8s/linkis-ujes-spark-enginemanager-configmap.yaml +++ /dev/null @@ -1,43 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - wds.linkis.engine.application.name=sparkEngine - wds.linkis.server.component.exclude.packages=com.webank.wedatasphere.linkis.engine.,com.webank.wedatasphere.linkis.udf. - wds.linkis.server.version=v1 - wds.linkis.console.config.application.name=cloud-publicservice - wds.linkis.engine.udf.app.name=cloud-publicservice - wds.linkis.enginemanager.sudo.script=/appcom/tmp/johnnwang/Install/linkis-ujes-spark-enginemanager/bin/rootScript.sh - wds.linkis.spark.driver.conf.mainjar= - #spark.config.dir=/appcom/config/spark-config - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-spark-enginemanager.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-spark-enginemanager-config - namespace: default - diff --git a/k8s/linkis-ujes-spark-enginemanager-deployment.yaml b/k8s/linkis-ujes-spark-enginemanager-deployment.yaml deleted file mode 100644 index 2a22768acc..0000000000 --- a/k8s/linkis-ujes-spark-enginemanager-deployment.yaml +++ /dev/null @@ -1,124 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-spark-enginemanager-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-spark-enginemanager - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-spark-enginemanager - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-spark-enginemanager - - linkis-ujes-hive-enginemanager - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node2 - containers: - - name: linkis-ujes-spark-enginemanager - image: wedatasphere/linkis:linkis-ujes-spark-enginemanager-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-spark-enginemanager/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 21001 - livenessProbe: - tcpSocket: - port: 21001 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "21001" - volumeMounts: - - name: linkis-ujes-spark-enginemanager-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-spark-enginemanager/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-spark-enginemanager-config - configMap: - name: linkis-ujes-spark-enginemanager-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/linkis-ujes-spark-entrance-configmap.yaml b/k8s/linkis-ujes-spark-entrance-configmap.yaml deleted file mode 100644 index 408c7b2229..0000000000 --- a/k8s/linkis-ujes-spark-entrance-configmap.yaml +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: v1 -data: - linkis.properties: |+ - - - wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful - - wds.linkis.engine.application.name=sparkEngine - wds.linkis.enginemanager.application.name=sparkEngineManager - - wds.linkis.query.application.name=cloud-publicservice - - wds.linkis.console.configuration.application.name=cloud-publicservice - wds.linkis.engine.creation.wait.time.max=20m - wds.linkis.console.variable.application.name=cloud-publicservice - - wds.linkis.server.version=v1 - #hadoop.config.dir=/appcom/config/hadoop-config - #spark.config.dir=/appcom/config/spark-config - - wds.linkis.entrance.config.logPath=file:///appcom/logs/dataworkcloud/dwc/ - - wds.linkis.server.socket.mode=true - - wds.linkis.resultSet.store.path=hdfs:/// - -kind: ConfigMap -metadata: - managedFields: - - apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:data: - .: {} - f:linkis-ujes-spark-entrance.properties: {} - manager: kubectl - operation: Update - name: linkis-ujes-spark-entrance-config - namespace: default - diff --git a/k8s/linkis-ujes-spark-entrance-deployment.yaml b/k8s/linkis-ujes-spark-entrance-deployment.yaml deleted file mode 100644 index 61fafcd9b6..0000000000 --- a/k8s/linkis-ujes-spark-entrance-deployment.yaml +++ /dev/null @@ -1,123 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: linkis-ujes-spark-entrance-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: linkis-ujes-spark-entrance - # release: dev - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: linkis-ujes-spark-entrance - # release: dev - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - linkis-ujes-spark-entrance - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node2 - containers: - - name: linkis-ujes-spark-entrance - image: wedatasphere/linkis:linkis-ujes-spark-entrance-0.11.0 - lifecycle: - preStop: - exec: - command: ["sh","/opt/linkis/linkis-ujes-spark-entrance/bin/stop.sh"] - imagePullPolicy: Always - ports: - - name: http - containerPort: 21000 - livenessProbe: - tcpSocket: - port: 21000 - initialDelaySeconds: 15 - periodSeconds: 20 - env: - - name: eurekaurl - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: EUREKA_URL - valueFrom: - configMapKeyRef: - name: eureka-config - key: eurekaUrl - - name: SERVER_HEAP_SIZE - value: 1024M - - name: START_PORT - value: "21000" - volumeMounts: - - name: linkis-ujes-spark-entrance-config - mountPath: /opt/linkis/conf - # - name: resultset - # mountPath: /opt/linkis/data - - name: varlog - mountPath: /opt/linkis/linkis-ujes-spark-entrance/logs - - name: hadoop-config - mountPath: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - mountPath: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - mountPath: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf - imagePullSecrets: - - name: registry-key - volumes: - - name: linkis-ujes-spark-entrance-config - configMap: - name: linkis-ujes-spark-entrance-config - # - name: resultset - # nfs: - # path: /data/k8s - # server: 10.206.0.12 - - name: varlog - hostPath: - path: /var/log - - name: eureka-config - configMap: - name: eureka-config - - name: hadoop-config - hostPath: - path: /opt/hadoop/hadoop-2.7.7/etc/hadoop - - name: hive-config - hostPath: - path: /opt/hive/apache-hive-2.3.6-bin/conf - - name: spark-config - hostPath: - path: /opt/spark/spark-2.4.4-bin-hadoop2.7/conf diff --git a/k8s/package.sh b/k8s/package.sh deleted file mode 100644 index c58999817c..0000000000 --- a/k8s/package.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash - -mvn clean package -f bml/bmlserver/pom_k8s.xml - -mvn clean package -f datasource/datasourcemanager/server/pom_k8s.xml - -mvn clean package -f datasource/metadatamanager/server/pom_k8s.xml -mvn clean package -f datasource/metadatamanager/service/mysql/pom_k8s.xml -mvn clean package -f datasource/metadatamanager/service/elasticsearch/pom_k8s.xml -mvn clean package -f datasource/metadatamanager/service/hive/pom_k8s.xml - -mvn clean package -f gateway/gateway-ujes-support/pom_k8s.xml - -mvn clean package -f resourceManager/resourcemanagerserver/pom_k8s.xml - -mvn clean package -f contextservice/cs-server/pom_k8s.xml - -mvn clean package -f metadata/pom_k8s.xml - -mvn clean package -f publicService/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/spark/enginemanager/pom_k8s.xml -mvn clean package -f ujes/definedEngines/spark/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/hive/enginemanager/pom_k8s.xml -mvn clean package -f ujes/definedEngines/hive/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/python/enginemanager/pom_k8s.xml -mvn clean package -f ujes/definedEngines/python/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/pipeline/enginemanager/pom_k8s.xml -mvn clean package -f ujes/definedEngines/pipeline/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/jdbc/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/mlsql/entrance/pom_k8s.xml - -mvn clean package -f ujes/definedEngines/shell/entrance/pom_k8s.xml -mvn clean package -f ujes/definedEngines/shell/enginemanager/pom_k8s.xml - diff --git a/k8s/push.sh b/k8s/push.sh deleted file mode 100644 index 8602f4545b..0000000000 --- a/k8s/push.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -docker push $HARBOR_LINKIS/linkis:linkis-bml-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-dsm-server-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-mdm-server-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-mdm-service-mysql-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-mdm-service-es-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-mdm-service-hive-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-gateway-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-resourcemanager-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-cs-server-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-metadata-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-publicservice-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-spark-enginemanager-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-ujes-spark-entrance-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-hive-enginemanager-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-ujes-hive-entrance-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-python-enginemanager-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-ujes-python-entrance-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-pipeline-enginemanager-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-ujes-pipeline-entrance-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-jdbc-enginemanager-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-mlsql-entrance-0.11.0 - -docker push $HARBOR_LINKIS/linkis:linkis-ujes-shell-enginemanager-0.11.0 -docker push $HARBOR_LINKIS/linkis:linkis-ujes-shell-entrance-0.11.0 - - diff --git a/k8s/register.yaml b/k8s/register.yaml deleted file mode 100644 index c4e9abe022..0000000000 --- a/k8s/register.yaml +++ /dev/null @@ -1,5 +0,0 @@ -kubectl create secret docker-registry registry-key \ ---docker-server=https://wedatasphere/linkis \ ---docker-username=wedatasphere \ ---docker-password=***** \ ---docker-email=wedatasphere@webank.com \ No newline at end of file diff --git a/k8s/scriptis.yaml b/k8s/scriptis.yaml deleted file mode 100644 index c27089ad74..0000000000 --- a/k8s/scriptis.yaml +++ /dev/null @@ -1,81 +0,0 @@ -# -# Copyright 2019 WeBank -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -apiVersion: apps/v1 -kind: Deployment -metadata: - name: scriptis -spec: - replicas: 1 - selector: - matchLabels: - app: scriptis - strategy: - rollingUpdate: - maxSurge: 1 - maxUnavailable: 1 - type: RollingUpdate - template: - metadata: - labels: - app: scriptis - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: "app" - operator: In - values: - - scriptis - topologyKey: "kubernetes.io/hostname" - nodeAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 1 - preference: - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - node2 - containers: - - name: scriptis - image: wedatasphere/linkis:scriptis - imagePullPolicy: Always - ports: - - name: http - containerPort: 80 - livenessProbe: - tcpSocket: - port: 80 - initialDelaySeconds: 15 - periodSeconds: 20 - imagePullSecrets: - - name: registry-key ---- - -apiVersion: v1 -kind: Service -metadata: - name: scriptis-service -spec: - selector: - app: scriptis - ports: - - name: http - port: 80 - protocol: TCP - targetPort: 80 - clusterIP: None diff --git a/linkis-commons/linkis-common/pom.xml b/linkis-commons/linkis-common/pom.xml new file mode 100644 index 0000000000..f58dad3fb5 --- /dev/null +++ b/linkis-commons/linkis-common/pom.xml @@ -0,0 +1,141 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-common + jar + + + + + + org.scala-lang + scala-library + + + org.scala-lang + scala-compiler + + + org.scala-lang + scala-reflect + + + org.scala-lang + scalap + + + commons-lang + commons-lang + + + commons-io + commons-io + ${commons-io.version} + + + commons-collections + commons-collections + + + com.google.guava + guava + + + + com.fasterxml.jackson.core + jackson-databind + ${fasterxml.jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${fasterxml.jackson.version} + + + com.fasterxml.jackson.module + jackson-module-scala_${scala.binary.version} + ${fasterxml.jackson.version} + + + com.google.guava + guava + + + org.scala-lang + scala-library + + + org.scala-lang + scala-reflect + + + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + commons-net + commons-net + 3.1 + + + + commons-codec + commons-codec + 1.10 + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + + \ No newline at end of file diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCException.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCException.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRetryException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRetryException.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRetryException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRetryException.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java similarity index 93% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java index a1cae017a9..2910dcd870 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DWCRuntimeException.java @@ -25,9 +25,7 @@ import java.util.HashMap; import java.util.Map; -import static com.webank.wedatasphere.linkis.common.exception.DWCException.applicationName; -import static com.webank.wedatasphere.linkis.common.exception.DWCException.hostname; -import static com.webank.wedatasphere.linkis.common.exception.DWCException.hostPort; +import static com.webank.wedatasphere.linkis.common.exception.DWCException.*; public abstract class DWCRuntimeException extends RuntimeException{ diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DwcCommonErrorException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DwcCommonErrorException.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DwcCommonErrorException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/DwcCommonErrorException.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ErrorException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ErrorException.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ErrorException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ErrorException.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionLevel.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionLevel.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionLevel.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionLevel.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionManager.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionManager.java similarity index 100% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionManager.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/ExceptionManager.java diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java similarity index 98% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java index 4c66a525a0..9a49e722d1 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/FatalException.java @@ -22,8 +22,6 @@ */ package com.webank.wedatasphere.linkis.common.exception; -import java.util.Map; - public class FatalException extends DWCException{ private ExceptionLevel level = ExceptionLevel.FATAL; public FatalException(int errCode, String desc){ diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java similarity index 98% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java index 64aeb27e30..781b24d2fb 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/exception/WarnException.java @@ -22,8 +22,6 @@ */ package com.webank.wedatasphere.linkis.common.exception; -import java.util.Map; - public class WarnException extends DWCRuntimeException{ private ExceptionLevel level = ExceptionLevel.WARN; public WarnException(int errCode, String desc){ diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java similarity index 95% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java index 8f522d94d0..7e1d5c2b17 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/Fs.java @@ -16,6 +16,7 @@ package com.webank.wedatasphere.linkis.common.io; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -25,7 +26,7 @@ /** * Created by enjoyyin on 2017/2/4. */ -public interface Fs { +public interface Fs extends Closeable { public abstract void init(Map properties) throws IOException; @@ -53,6 +54,4 @@ public interface Fs { public abstract boolean renameTo(FsPath oldDest, FsPath newDest) throws IOException; - public abstract void close() throws IOException; - } diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java similarity index 99% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java index a25efb5632..dac533b5bb 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/io/FsPath.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,6 +32,7 @@ */ public class FsPath { + public static final String CUR_DIR = "."; public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows"); diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java similarity index 98% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java index 8486ec2fca..18f0a54ced 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/ByteTimeUtils.java @@ -235,16 +235,16 @@ public static String bytesToString(long size) { double value; String unit; - if (size >= 2*TB) { + if (size >= 2*TB || -2*TB >= size) { value = size * 1f / TB; unit = "TB"; - } else if (size >= 2*GB) { + } else if (size >= 2*GB || -2*GB >= size) { value = size * 1f / GB; unit = "GB"; - } else if (size >= 2*MB) { + } else if (size >= 2*MB || -2*MB >= size) { value = size * 1f / MB; unit = "MB"; - } else if (size >= 2*KB) { + } else if (size >= 2*KB || -2*KB >= size) { value = size * 1f / KB; unit = "KB"; } else { diff --git a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java similarity index 95% rename from core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java rename to linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java index ae8ba4ff5e..885ab4d3a3 100644 --- a/core/common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java +++ b/linkis-commons/linkis-common/src/main/java/com/webank/wedatasphere/linkis/common/utils/DESUtil.java @@ -17,14 +17,14 @@ package com.webank.wedatasphere.linkis.common.utils; import org.apache.commons.lang.StringUtils; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; -import java.io.IOException; import java.security.SecureRandom; -import java.util.Base64; public class DESUtil { private final static String DES = "DES"; @@ -45,7 +45,7 @@ public static String encrypt(String data, String key) throws Exception { } } byte[] bt = encrypt(data.getBytes(), key.getBytes()); - String strs = Base64.getEncoder().encodeToString(bt); + String strs = new BASE64Encoder().encode(bt); return strs; } @@ -67,7 +67,8 @@ public static String decrypt(String data, String key) throws Exception { i++; } } - byte[] buf = Base64.getDecoder().decode(data); + BASE64Decoder decoder = new BASE64Decoder(); + byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf, key.getBytes()); return new String(bt); } diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/ServiceInstance.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/ServiceInstance.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/ServiceInstance.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/ServiceInstance.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/collection/LoopArray.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/collection/LoopArray.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/collection/LoopArray.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/collection/LoopArray.scala diff --git a/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala new file mode 100644 index 0000000000..5b04946b4b --- /dev/null +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/BDPConfiguration.scala @@ -0,0 +1,153 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.common.conf + +import java.io.{File, FileInputStream, IOException, InputStream} +import java.util.Properties + +import com.webank.wedatasphere.linkis.common.utils.Logging +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +private[conf] object BDPConfiguration extends Logging { + + val DEFAULT_PROPERTY_FILE_NAME = "linkis.properties" + + val DEFAULT_SERVER_CONF_FILE_NAME = "linkis-server.properties" + + private val config = new Properties + private val sysProps = sys.props + private val extractConfig = new Properties + + private val env = sys.env + + + private def init: Unit = { + + // load pub linkis conf + val propertyFile = sysProps.getOrElse("wds.linkis.configuration", DEFAULT_PROPERTY_FILE_NAME) + val configFileURL = getClass.getClassLoader.getResource(propertyFile) + if (configFileURL != null && new File(configFileURL.getPath).exists) initConfig(config, configFileURL.getPath) + else warn(s"******************************** Notice: The Linkis configuration file $propertyFile is not exists! ***************************") + + // load pub linkis conf + val serverConf = sysProps.getOrElse("wds.linkis.server.conf", DEFAULT_SERVER_CONF_FILE_NAME) + val serverConfFileURL = getClass.getClassLoader.getResource(serverConf) + if (serverConfFileURL != null && new File(serverConfFileURL.getPath).exists) initConfig(config, serverConfFileURL.getPath) + else warn(s"******************************** Notice: The Linkis serverConf file $serverConfFileURL is not exists! ***************************") + + // load server confs + val propertyFileOptions = sysProps.get("wds.linkis.server.confs") + if (propertyFileOptions.isDefined) { + val propertyFiles = propertyFileOptions.get.split(",") + propertyFiles.foreach { propertyF => + val configFileURL = getClass.getClassLoader.getResource(propertyF) + if (configFileURL != null && new File(configFileURL.getPath).exists) initConfig(config, configFileURL.getPath) + else warn(s"******************************** Notice: The Linkis configuration file $propertyF is not exists! ***************************") + } + } + + } + + try { + init + } catch { + case e: Throwable => + warn("Failed to init conf", e) + } + + private def initConfig(config: Properties, filePath: String) { + var inputStream: InputStream = null + try { + inputStream = new FileInputStream(filePath) + config.load(inputStream) + } catch { + case e: IOException => + error("Can't load " + filePath, e) + } finally IOUtils.closeQuietly(inputStream) + } + + def getOption(key: String): Option[String] = { + if(extractConfig.containsKey(key)) + return Some(extractConfig.getProperty(key)) + val value = config.getProperty(key) + if(StringUtils.isNotEmpty(value)) { + return Some(value) + } + val propsValue = sysProps.get(key).orElse(sys.props.get(key)) + if(propsValue.isDefined){ + return propsValue + } + env.get(key) + } + + def properties = { + val props = new Properties + props.putAll(sysProps) + props.putAll(config) + props.putAll(extractConfig) + props.putAll(env) + props + } + + def getOption[T](commonVars: CommonVars[T]): Option[T] = if(commonVars.value != null) Option(commonVars.value) + else { + val value = BDPConfiguration.getOption(commonVars.key) + if (value.isEmpty) Option(commonVars.defaultValue) + else formatValue(commonVars.defaultValue, value) + } + + private[common] def formatValue[T](defaultValue: T, value: Option[String]): Option[T] = { + if(value.isEmpty || value.exists(StringUtils.isEmpty)) return Option(defaultValue) + val formattedValue = defaultValue match { + case _: String => value + case _: Byte => value.map(_.toByte) + case _: Short => value.map(_.toShort) + case _: Char => value.map(_.toCharArray.apply(0)) + case _: Int => value.map(_.toInt) + case _: Long => value.map(_.toLong) + case _: Float => value.map(_.toFloat) + case _: Double => value.map(_.toDouble) + case _: Boolean => value.map(_.toBoolean) + case _: TimeType => value.map(new TimeType(_)) + case _: ByteType => value.map(new ByteType(_)) + case null => value + } + formattedValue.asInstanceOf[Option[T]] + } + + def set(key: String, value: String) = extractConfig.setProperty(key, value) + + def setIfNotExists(key: String, value: String) = if(!config.containsKey(key)) set(key, value) + + def getBoolean(key: String, default: Boolean):Boolean = getOption(key).map(_.toBoolean).getOrElse(default) + def getBoolean(commonVars: CommonVars[Boolean]): Option[Boolean] = getOption(commonVars) + + def get(key: String, default: String): String = getOption(key).getOrElse(default) + def get(commonVars: CommonVars[String]): Option[String] = getOption(commonVars) + + def get(key: String): String = getOption(key).getOrElse(throw new NoSuchElementException(key)) + + def getInt(key: String, default: Int):Int = getOption(key).map(_.toInt).getOrElse(default) + def getInt(commonVars: CommonVars[Int]): Option[Int] = getOption(commonVars) + + def contains(key: String): Boolean = getOption(key).isDefined + +} diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/ByteType.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/ByteType.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/ByteType.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/ByteType.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala similarity index 99% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala index b93932301c..dd7f80c937 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/CommonVars.scala @@ -27,7 +27,6 @@ case class CommonVars[T](key: String, defaultValue: T, value: T, description: St if(properties == null || !properties.containsKey(key) || properties.get(key) == null) getValue else BDPConfiguration.formatValue(defaultValue, Option(properties.get(key))).get } - def getValue(properties: Map[String, String]): T = getValue(mapAsJavaMap(properties)) def acquireNew: T = BDPConfiguration.getOption(this).getOrElse(defaultValue) } diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala similarity index 89% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala index 9b9efbda2b..4e094327ed 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/Configuration.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,9 +28,9 @@ object Configuration extends Logging { val IS_TEST_MODE = CommonVars("wds.linkis.test.mode", false) - val hadoopConfDir = CommonVars("hadoop.config.dir", CommonVars("HADOOP_CONF_DIR", "").getValue).getValue + val LINKIS_HOME = CommonVars("wds.linkis.home", CommonVars("LINKIS_HOME", "/appcom/Install/LinkisInstall")) - val GATEWAY_URL: CommonVars[String] = CommonVars[String]("wds.linkis.gateway.url", "http://localhost:9001/") + val GATEWAY_URL: CommonVars[String] = CommonVars[String]("wds.linkis.gateway.url", "http://127.0.0.1:9001/") def getGateWayURL(): String = { val url = GATEWAY_URL.getValue.trim diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala similarity index 98% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala index edc3847286..a6d691d216 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/DWCArgumentsParser.scala @@ -18,14 +18,14 @@ package com.webank.wedatasphere.linkis.common.conf import org.apache.commons.lang.StringUtils -import scala.collection.{JavaConversions, mutable} import scala.collection.mutable.ArrayBuffer +import scala.collection.{JavaConversions, mutable} /** * Created by enjoyyin on 2018/9/26. */ object DWCArgumentsParser { - protected val DWC_CONF = "--dwc-conf" + protected val DWC_CONF = "--engineconn-conf" protected val SPRING_CONF = "--spring-conf" private var dwcOptionMap = Map.empty[String, String] diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/TimeType.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/TimeType.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/TimeType.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/conf/TimeType.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsReader.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsReader.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsReader.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsReader.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsWriter.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsWriter.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsWriter.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/FsWriter.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/MetaData.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/MetaData.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/MetaData.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/MetaData.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/Record.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/Record.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/Record.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/Record.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultDeserializer.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultDeserializer.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultDeserializer.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultDeserializer.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSerializer.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSerializer.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSerializer.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSerializer.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSet.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSet.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSet.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSet.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetReader.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetReader.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetReader.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetReader.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetWriter.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetWriter.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetWriter.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/io/resultset/ResultSetWriter.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/Event.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/Event.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/Event.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/Event.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/EventListener.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/EventListener.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/EventListener.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/EventListener.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala similarity index 98% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala index 035fd66541..6919e700e6 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/ListenerEventBus.scala @@ -17,9 +17,8 @@ package com.webank.wedatasphere.linkis.common.listener import java.util.concurrent.atomic.{AtomicBoolean, AtomicLong} -import java.util.concurrent.{ArrayBlockingQueue, CopyOnWriteArrayList, Future, LinkedBlockingQueue, TimeoutException} +import java.util.concurrent.{ArrayBlockingQueue, CopyOnWriteArrayList, Future, TimeoutException} -import com.webank.wedatasphere.linkis.common.collection.BlockingLoopArray import com.webank.wedatasphere.linkis.common.utils.{ByteTimeUtils, Logging, Utils} import org.apache.commons.lang.time.DateFormatUtils diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/SingleThreadListenerBus.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/SingleThreadListenerBus.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/SingleThreadListenerBus.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/listener/SingleThreadListenerBus.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/log/LogUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/log/LogUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/log/LogUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/log/LogUtils.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ClassUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ClassUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ClassUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ClassUtils.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/FileService.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/FileService.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/FileService.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/FileService.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JavaLog.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JavaLog.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JavaLog.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JavaLog.scala diff --git a/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JsonUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JsonUtils.scala new file mode 100644 index 0000000000..ee2f55bb7d --- /dev/null +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/JsonUtils.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.common.utils + +import java.text.SimpleDateFormat + +import com.fasterxml.jackson.databind.ObjectMapper + + +object JsonUtils { + + //TODO add gson + + implicit val jackson = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")) + +} diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/LDAPUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/LDAPUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/LDAPUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/LDAPUtils.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Logging.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Logging.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Logging.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Logging.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala similarity index 80% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala index 78624b5952..6cc384fec1 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/OverloadUtils.scala @@ -18,12 +18,18 @@ package com.webank.wedatasphere.linkis.common.utils import java.lang.management.ManagementFactory +import com.sun.management.OperatingSystemMXBean + object OverloadUtils { + def getOSBean: OperatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean.asInstanceOf[OperatingSystemMXBean] + def getProcessMaxMemory: Long = ManagementFactory.getMemoryMXBean.getHeapMemoryUsage.getMax def getProcessUsedMemory: Long = ManagementFactory.getMemoryMXBean.getHeapMemoryUsage.getUsed def getSystemCPUUsed: Float = ManagementFactory.getOperatingSystemMXBean.getSystemLoadAverage.toFloat + def getSystemFreeMemory: Long = getOSBean.getFreePhysicalMemorySize + } diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala similarity index 90% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala index 8ffcf1433c..5598ca33d0 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RSAUtils.scala @@ -16,9 +16,10 @@ package com.webank.wedatasphere.linkis.common.utils +import java.nio.charset.StandardCharsets import java.security.{KeyPair, KeyPairGenerator, PrivateKey, PublicKey} -import javax.crypto.Cipher +import javax.crypto.Cipher import org.apache.commons.codec.binary.Hex import org.apache.commons.net.util.Base64 @@ -33,7 +34,10 @@ object RSAUtils { keyPair.generateKeyPair() } def getDefaultPublicKey(): String = { - new String(Base64.encodeBase64(keyPair.getPublic.getEncoded)) + new String(Base64.encodeBase64(keyPair.getPublic.getEncoded), StandardCharsets.UTF_8) + } + def getDefaultPrivateKey(): String = { + new String(Base64.encodeBase64(keyPair.getPrivate.getEncoded), StandardCharsets.UTF_8) } def encrypt(data: Array[Byte], publicKey: PublicKey): Array[Byte] = { val cipher = Cipher.getInstance("RSA") diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RefreshUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RefreshUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RefreshUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RefreshUtils.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala similarity index 96% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala index d3f1153e2d..7342b9e87b 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/RetryHandler.scala @@ -16,7 +16,7 @@ package com.webank.wedatasphere.linkis.common.utils -import com.webank.wedatasphere.linkis.common.exception.{DWCRetryException, FatalException} +import com.webank.wedatasphere.linkis.common.exception.FatalException import org.apache.commons.lang.{ClassUtils => CommonClassUtils} import scala.collection.mutable.ArrayBuffer diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ShutdownUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ShutdownUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ShutdownUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ShutdownUtils.scala diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala similarity index 99% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala index 61438c2749..da6e701655 100644 --- a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala +++ b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/Utils.scala @@ -284,5 +284,6 @@ object Utils extends Logging { } } + def getJvmUser: String = System.getProperty("user.name") } diff --git a/core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ZipUtils.scala b/linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ZipUtils.scala similarity index 100% rename from core/common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ZipUtils.scala rename to linkis-commons/linkis-common/src/main/scala/com/webank/wedatasphere/linkis/common/utils/ZipUtils.scala diff --git a/linkis-commons/linkis-hadoop-common/pom.xml b/linkis-commons/linkis-hadoop-common/pom.xml new file mode 100644 index 0000000000..51a74138fc --- /dev/null +++ b/linkis-commons/linkis-hadoop-common/pom.xml @@ -0,0 +1,221 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-hadoop-common + jar + + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + org.apache.hadoop + hadoop-common + ${hadoop.version} + + + log4j + log4j + + + org.mortbay.jetty + jetty + + + org.mortbay.jetty + jetty-util + + + com.sun.jersey + jersey-core + + + com.sun.jersey + jersey-server + + + com.sun.jersey + jersey-json + + + jsr311-api + javax.ws.rs + + + net.java.dev.jets3t + jets3t + + + com.jcraft + jsch + + + com.google.code.findbugs + jsr305 + + + xmlenc + xmlenc + + + net.java.dev.jets3t + jets3t + + + org.apache.avro + avro + + + org.apache.hadoop + hadoop-auth + + + com.jcraft + jsch + + + com.google.code.findbugs + jsr305 + + + servlet-api + javax.servlet + + + org.slf4j + slf4j-log4j12 + + + com.sun.jersey + * + + + org.codehaus.jackson + * + + + + org.eclipse.jetty + * + + + + + + org.apache.hadoop + hadoop-hdfs + ${hadoop.version} + + + io.netty + netty + + + servlet-api + javax.servlet + + + com.google.guava + guava + + + com.sun.jersey + jersey-core + + + com.sun.jersey + jersey-server + + + org.slf4j + slf4j-log4j12 + + + com.sun.jersey + * + + + org.codehaus.jackson + * + + + org.eclipse.jetty + * + + + + + org.apache.hadoop + hadoop-auth + ${hadoop.version} + + + org.slf4j + slf4j-log4j12 + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + * + + + org.eclipse.jetty + * + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + \ No newline at end of file diff --git a/core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala b/linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala similarity index 81% rename from core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala rename to linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala index 24e10df6ca..2cd9154365 100644 --- a/core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala +++ b/linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/conf/HadoopConf.scala @@ -15,9 +15,7 @@ package com.webank.wedatasphere.linkis.hadoop.common.conf import com.webank.wedatasphere.linkis.common.conf.CommonVars -/** - * Created by johnnwang on 2019/12/11. - */ + object HadoopConf { val HADOOP_ROOT_USER = CommonVars("wds.linkis.hadoop.root.user", "hadoop") @@ -30,4 +28,8 @@ object HadoopConf { val KEYTAB_HOST_ENABLED = CommonVars("wds.linkis.keytab.host.enabled", false) + val hadoopConfDir = CommonVars("hadoop.config.dir", CommonVars("HADOOP_CONF_DIR", "").getValue).getValue + + val HADOOP_EXTERNAL_CONF_DIR_PREFIX = CommonVars("wds.linkis.hadoop.external.conf.dir.prefix", "/appcom/config/external-conf/hadoop") + } diff --git a/core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala b/linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala similarity index 78% rename from core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala rename to linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala index 3982b1af04..f365adb344 100644 --- a/core/hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala +++ b/linkis-commons/linkis-hadoop-common/src/main/scala/com/webank/wedatasphere/linkis/hadoop/common/utils/HDFSUtils.scala @@ -10,35 +10,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.webank.wedatasphere.linkis.hadoop.common.utils import java.io.File import java.nio.file.Paths import java.security.PrivilegedExceptionAction -import com.webank.wedatasphere.linkis.common.conf.Configuration.hadoopConfDir -import com.webank.wedatasphere.linkis.hadoop.common.conf.HadoopConf._ +import com.webank.wedatasphere.linkis.hadoop.common.conf.HadoopConf +import com.webank.wedatasphere.linkis.hadoop.common.conf.HadoopConf.{hadoopConfDir, _} +import org.apache.commons.lang.StringUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.hadoop.security.UserGroupInformation + /** * Created by enjoyyin on 2019/5/27. */ object HDFSUtils { - def getConfiguration(user: String): Configuration = getConfiguration(user, hadoopConfDir) + def getConfigurationByLabel(user: String, label: String): Configuration = { + getConfiguration(user, getHadoopConDirByLabel(label)) + } + + private def getHadoopConDirByLabel(label: String): String = { + if (StringUtils.isBlank(label)) { + hadoopConfDir + } else { + val prefix = if (HadoopConf.HADOOP_EXTERNAL_CONF_DIR_PREFIX.getValue.endsWith("/")) { + HadoopConf.HADOOP_EXTERNAL_CONF_DIR_PREFIX.getValue + } else { + HadoopConf.HADOOP_EXTERNAL_CONF_DIR_PREFIX.getValue + "/" + } + prefix + label + } + } + def getConfiguration(user: String, hadoopConfDir: String): Configuration = { val confPath = new File(hadoopConfDir) - if(!confPath.exists() || confPath.isFile) { + if (!confPath.exists() || confPath.isFile) { throw new RuntimeException(s"Create hadoop configuration failed, path $hadoopConfDir not exists.") } val conf = new Configuration() conf.addResource(new Path(Paths.get(hadoopConfDir, "core-site.xml").toAbsolutePath.toFile.getAbsolutePath)) conf.addResource(new Path(Paths.get(hadoopConfDir, "hdfs-site.xml").toAbsolutePath.toFile.getAbsolutePath)) - conf.addResource(new Path(Paths.get(hadoopConfDir, "yarn-site.xml").toAbsolutePath.toFile.getAbsolutePath)) conf } @@ -68,7 +86,7 @@ object HDFSUtils { def getKerberosUser(userName: String): String = { var user = userName if(KEYTAB_HOST_ENABLED.getValue){ - user = user+ "/" + KEYTAB_HOST.getValue + user = user + "/" + KEYTAB_HOST.getValue } user } diff --git a/linkis-commons/linkis-httpclient/pom.xml b/linkis-commons/linkis-httpclient/pom.xml new file mode 100644 index 0000000000..038ae0591c --- /dev/null +++ b/linkis-commons/linkis-httpclient/pom.xml @@ -0,0 +1,94 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-httpclient + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + org.apache.httpcomponents + httpmime + ${httpmime.version} + + + + org.json4s + json4s-jackson_${scala.binary.version} + ${json4s.version} + + + org.scala-lang + scala-library + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-core + + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala new file mode 100644 index 0000000000..0f920aaa4c --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/AbstractHttpClient.scala @@ -0,0 +1,392 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient + +import java.util + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, Configuration} +import com.webank.wedatasphere.linkis.common.io.{Fs, FsPath} +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.httpclient.authentication.{AbstractAuthenticationStrategy, AuthenticationAction, HttpAuthentication} +import com.webank.wedatasphere.linkis.httpclient.config.ClientConfig +import com.webank.wedatasphere.linkis.httpclient.discovery.{AbstractDiscovery, Discovery, HeartbeatAction} +import com.webank.wedatasphere.linkis.httpclient.exception.{HttpClientResultException, HttpMessageParseException} +import com.webank.wedatasphere.linkis.httpclient.loadbalancer.{AbstractLoadBalancer, DefaultLoadbalancerStrategy, LoadBalancer} +import com.webank.wedatasphere.linkis.httpclient.request._ +import com.webank.wedatasphere.linkis.httpclient.response._ +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.StringUtils +import org.apache.http.client.CookieStore +import org.apache.http.client.config.RequestConfig +import org.apache.http.client.entity.{DeflateDecompressingEntity, GzipDecompressingEntity, UrlEncodedFormEntity} +import org.apache.http.client.methods._ +import org.apache.http.client.utils.URIBuilder +import org.apache.http.entity.mime.MultipartEntityBuilder +import org.apache.http.entity.{ContentType, StringEntity} +import org.apache.http.impl.client.{BasicCookieStore, HttpClients} +import org.apache.http.message.BasicNameValuePair +import org.apache.http.util.EntityUtils +import org.apache.http.{HttpException, HttpResponse, _} +import org.json4s.jackson.Serialization.read +import org.json4s.{DefaultFormats, Formats} + +import scala.collection.Iterable +import scala.collection.JavaConversions._ +import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService} + + +/** + * Created by enjoyyin on 2019/5/20. + */ +abstract class AbstractHttpClient(clientConfig: ClientConfig, clientName: String) extends Client { + + protected implicit val formats: Formats = DefaultFormats + protected implicit val executors: ExecutionContext = Utils.newCachedExecutionContext(clientConfig.getMaxConnection, clientName, false) + + protected val CONNECT_TIME_OUT = CommonVars("wds.linkis.httpclient.default.connect.timeOut", 50000).getValue + + protected val httpClient = HttpClients.createDefault() + + if (clientConfig.getAuthenticationStrategy != null) clientConfig.getAuthenticationStrategy match { + case auth: AbstractAuthenticationStrategy => auth.setClient(this) + case _ => + } + protected val (discovery, loadBalancer): (Option[Discovery], Option[LoadBalancer]) = + if (this.clientConfig.isDiscoveryEnabled) { + val discovery = Some(createDiscovery()) + discovery.foreach { + case d: AbstractDiscovery => + d.setServerUrl(clientConfig.getServerUrl) + d.setClient(this) + d.setSchedule(clientConfig.getDiscoveryPeriod, clientConfig.getDiscoveryTimeUnit) + case d => d.setServerUrl(clientConfig.getServerUrl) + } + //如果discovery没有启用,那么启用loadBalancer是没有意义的 + val loadBalancer = if (clientConfig.isLoadbalancerEnabled && this.clientConfig.getLoadbalancerStrategy != null) + Some(this.clientConfig.getLoadbalancerStrategy.createLoadBalancer()) + else if (clientConfig.isLoadbalancerEnabled) Some(DefaultLoadbalancerStrategy.createLoadBalancer()) + else None + loadBalancer match { + case Some(lb: AbstractLoadBalancer) => + discovery.foreach(_.addDiscoveryListener(lb)) + case _ => + } + (discovery, loadBalancer) + } else (None, None) + + discovery.foreach(_.start()) + + protected def createDiscovery(): Discovery + + override def execute(requestAction: Action): Result = execute(requestAction, -1) + + override def execute(requestAction: Action, waitTime: Long): Result = { + if (!requestAction.isInstanceOf[HttpAction]) + throw new UnsupportedOperationException("only HttpAction supported, but the fact is " + requestAction.getClass) + val action = prepareAction(requestAction.asInstanceOf[HttpAction]) + val startTime = System.currentTimeMillis + val req = prepareReq(action) + val prepareReqTime = System.currentTimeMillis - startTime + val cookieStore = prepareCookie(action) + val attempts = new util.ArrayList[Long]() + def addAttempt(): CloseableHttpResponse = { + val startTime = System.currentTimeMillis + val response = executeRequest(req, Some(waitTime).filter(_ > 0), cookieStore) + attempts.add(System.currentTimeMillis - startTime) + response + } + val response = if (!clientConfig.isRetryEnabled) addAttempt() + else clientConfig.getRetryHandler.retry(addAttempt(), action.getClass.getSimpleName + "HttpRequest") + val beforeDeserializeTime = System.currentTimeMillis + responseToResult(response, action) match { + case metricResult: MetricResult => + if(metricResult.getMetric == null) metricResult.setMetric(new HttpMetric) + metricResult.getMetric.setPrepareReqTime(prepareReqTime) + metricResult.getMetric.addRetries(attempts) + metricResult.getMetric.setDeserializeTime(System.currentTimeMillis - beforeDeserializeTime) + metricResult.getMetric.setExecuteTotalTime(System.currentTimeMillis - startTime) + metricResult + case result: Result => result + } + } + + + override def execute(requestAction: Action, resultListener: ResultListener): Unit = { + if (!requestAction.isInstanceOf[HttpAction]) { + throw new UnsupportedOperationException("only HttpAction supported, but the fact is " + requestAction.getClass) + } + val action = prepareAction(requestAction.asInstanceOf[HttpAction]) + val req = prepareReq(action) + val cookieStore = prepareCookie(action) + val response: CloseableHttpResponse = executeAsyncRequest(req) + //response.onSuccess{case r => resultListener.onSuccess(responseToResult(r, action))} + //response.onFailure{case t => resultListener.onFailure(t)} + } + + protected def getRequestUrl(suffixUrl: String, requestBody: String): String = { + val urlPrefix = loadBalancer.map(_.chooseServerUrl(requestBody)).getOrElse(clientConfig.getServerUrl) + if(suffixUrl.contains(urlPrefix)) suffixUrl else connectUrl(urlPrefix, suffixUrl) + } + + protected def connectUrl(prefix: String, suffix: String): String = { + val prefixEnd = prefix.endsWith("/") + val suffixStart = suffix.startsWith("/") + if (prefixEnd && suffixStart) prefix.substring(0, prefix.length - 1) + suffix + else if (!prefixEnd && !suffixStart) prefix + "/" + suffix + else prefix + suffix + } + + protected def prepareAction(requestAction: HttpAction): HttpAction = requestAction + + protected def prepareCookie(requestAction:HttpAction):CookieStore = { + val cookieStore = new BasicCookieStore() + if (requestAction.getCookies.nonEmpty) requestAction.getCookies.foreach(cookieStore.addCookie) + cookieStore + } + + + protected def prepareReq(requestAction: HttpAction): HttpRequestBase = { + var realURL = "" + requestAction match { + case serverUrlAction: ServerUrlAction => + realURL = connectUrl(serverUrlAction.serverUrl, requestAction.getURL) + case _ => + realURL = getRequestUrl(requestAction.getURL, requestAction.getRequestBody) + } + + if (clientConfig.getAuthenticationStrategy != null) clientConfig.getAuthenticationStrategy.login(requestAction, realURL.replaceAll(requestAction.getURL, "")) match { + case authAction: HttpAuthentication => + val cookies = authAction.authToCookies + if (cookies != null && cookies.nonEmpty) cookies.foreach(requestAction.addCookie) + val headers = authAction.authToHeaders + if (headers != null && !headers.isEmpty()) { + headers.foreach { case (k, v) => requestAction.addHeader(k.toString(), v.toString()) } + } + case _ => + } + + val request = requestAction match { + case delete: DeleteAction => + val builder = new URIBuilder(realURL) + if (!delete.getParameters.isEmpty) { + delete.getParameters.foreach { case (k, v) => builder.addParameter(k.toString(), v.toString()) } + } + val httpDelete = new HttpDelete(builder.build()) + if (requestAction.getHeaders.nonEmpty) { + requestAction.getHeaders.foreach { case (k, v) => httpDelete.addHeader(k.toString(), v.toString()) } + } + httpDelete + case put: PutAction => + val httpPut = new HttpPut(realURL) + if (put.getParameters.nonEmpty || put.getFormParams.nonEmpty) { + val nvps = new util.ArrayList[NameValuePair] + if (put.getParameters.nonEmpty) { + put.getParameters.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } + } + if (put.getFormParams.nonEmpty) { + put.getFormParams.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } + } + httpPut.setEntity(new UrlEncodedFormEntity(nvps)) + } + + if (StringUtils.isNotBlank(put.getRequestPayload)) { + val stringEntity = new StringEntity(put.getRequestPayload, "UTF-8") + stringEntity.setContentEncoding(Configuration.BDP_ENCODING.getValue) + stringEntity.setContentType("application/json") + httpPut.setEntity(stringEntity) + } + + if (requestAction.getHeaders.nonEmpty) { + requestAction.getHeaders.foreach { case (k, v) => httpPut.addHeader(k.toString(), v.toString()) } + } + httpPut + case upload: UploadAction => + val httpPost = new HttpPost(realURL) + val builder = MultipartEntityBuilder.create() + if (upload.inputStreams != null) + upload.inputStreams.foreach { case (k, v) => + builder.addBinaryBody(k, v, ContentType.create("multipart/form-data"), k) + } + upload match { + case get: GetAction => get.getParameters. + retain((k, v) => v != null && k != null). + foreach { case (k, v) => builder.addTextBody(k.toString, v.toString) } + case _ => + } + upload match { + case get: GetAction => get.getHeaders. + retain((k, v) => v != null && k != null). + foreach { case (k, v) => httpPost.addHeader(k.toString, v.toString) } + case _ => + } + val httpEntity = builder.build() + httpPost.setEntity(httpEntity) + httpPost + case post: POSTAction => + val httpPost = new HttpPost(realURL) + if (post.getParameters.nonEmpty || post.getFormParams.nonEmpty) { + val nvps = new util.ArrayList[NameValuePair] + if (post.getParameters.nonEmpty) { + post.getParameters.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } + } + if (post.getFormParams.nonEmpty) { + post.getFormParams.foreach { case (k, v) => nvps.add(new BasicNameValuePair(k, v.toString())) } + } + httpPost.setEntity(new UrlEncodedFormEntity(nvps)) + } + + if (StringUtils.isNotBlank(post.getRequestPayload)) { + val stringEntity = new StringEntity(post.getRequestPayload, "UTF-8") + stringEntity.setContentEncoding(Configuration.BDP_ENCODING.getValue) + stringEntity.setContentType("application/json") + httpPost.setEntity(stringEntity) + } + + if (requestAction.getHeaders.nonEmpty) { + requestAction.getHeaders.foreach { case (k, v) => httpPost.addHeader(k.toString(), v.toString()) } + } + httpPost + case get: GetAction => + val builder = new URIBuilder(realURL) + if (!get.getParameters.isEmpty) { + get.getParameters.foreach { case (k, v) => builder.addParameter(k.toString(), v.toString()) } + } + val httpGet = new HttpGet(builder.build()) + if (requestAction.getHeaders.nonEmpty) { + requestAction.getHeaders.foreach { case (k, v) => httpGet.addHeader(k.toString(), v.toString()) } + } + httpGet + case _ => + val httpost = new HttpPost(realURL) + val stringEntity = new StringEntity(requestAction.getRequestBody, "UTF-8") + stringEntity.setContentEncoding(Configuration.BDP_ENCODING.getValue) + stringEntity.setContentType("application/json") + httpost.setEntity(stringEntity) + if (requestAction.getHeaders.nonEmpty) { + requestAction.getHeaders.foreach { case (k, v) => httpost.addHeader(k.toString(), v.toString()) } + } + httpost + } + request + } + + protected def getFsByUser(user: String, path: FsPath): Fs + + + protected def executeRequest(req: HttpRequestBase, waitTime: Option[Long]): CloseableHttpResponse = { + val readTimeOut = waitTime.getOrElse(clientConfig.getReadTimeout) + val connectTimeOut = if (clientConfig.getConnectTimeout > 1000 || clientConfig.getConnectTimeout < 0) clientConfig.getConnectTimeout else CONNECT_TIME_OUT + val requestConfig = RequestConfig.custom + .setConnectTimeout(connectTimeOut.toInt) + .setConnectionRequestTimeout(connectTimeOut.toInt) + .setSocketTimeout(readTimeOut.toInt).build + req.setConfig(requestConfig) +// httpClient = HttpClients.createDefault() // todo check + val response = httpClient.execute(req) + response + } + + protected def executeRequest(req: HttpRequestBase, waitTime: Option[Long], cookieStore: CookieStore): CloseableHttpResponse = { + val readTimeOut = waitTime.getOrElse(clientConfig.getReadTimeout) + val connectTimeOut = if (clientConfig.getConnectTimeout > 1000 || clientConfig.getConnectTimeout < 0) clientConfig.getConnectTimeout else CONNECT_TIME_OUT + val requestConfig = RequestConfig.custom + .setConnectTimeout(connectTimeOut.toInt) + .setConnectionRequestTimeout(connectTimeOut.toInt) + .setSocketTimeout(readTimeOut.toInt).build + req.setConfig(requestConfig) + val response = httpClient.execute(req) + response + } + + + + //TODO 20200618 Modify to asynchronous request + protected def executeAsyncRequest(req: HttpRequestBase): CloseableHttpResponse = { + val response = httpClient.execute(req) + response + } + + protected def responseToResult(response: HttpResponse, requestAction: Action): Result = { + val entity = response.getEntity + val result = requestAction match { + case download: DownloadAction => + val statusCode = response.getStatusLine.getStatusCode + if (statusCode != 200) { + var responseBody: String = null + if (entity != null) { + responseBody = EntityUtils.toString(entity, "UTF-8") + } + throw new HttpClientResultException(s"request failed! ResponseBody is $responseBody.") + } + val inputStream = if(entity.getContentEncoding != null && StringUtils.isNotBlank(entity.getContentEncoding.getValue)) + entity.getContentEncoding.getValue.toLowerCase match { + case "gzip" => new GzipDecompressingEntity(entity).getContent + case "deflate" => new DeflateDecompressingEntity(entity).getContent + case str => throw new HttpClientResultException(s"request failed! Reason: not support decompress type $str.") + } else entity.getContent + download.write(inputStream) + Result() + case heartbeat: HeartbeatAction => + discovery.map { + case d: AbstractDiscovery => d.getHeartbeatResult(response, heartbeat) + }.getOrElse(throw new HttpMessageParseException("Discovery is not enable, HeartbeatAction is not needed!")) + case auth: AuthenticationAction => + clientConfig.getAuthenticationStrategy match { + case a: AbstractAuthenticationStrategy => a.getAuthenticationResult(response, auth) + case _ => throw new HttpMessageParseException("AuthenticationStrategy is not enable, login is not needed!") + } + case httpAction: HttpAction => + var responseBody: String = null + if (entity != null) { + responseBody = EntityUtils.toString(entity, "UTF-8") + } + httpResponseToResult(response, httpAction, responseBody) + .getOrElse(throw new HttpMessageParseException("cannot parse message: " + responseBody)) + } + result match { + case userAction: UserAction => requestAction match { + case _userAction: UserAction => userAction.setUser(_userAction.getUser) + case _ => + } + case _ => + } + result + } + + protected def httpResponseToResult(response: HttpResponse, requestAction: HttpAction, responseBody: String): Option[Result] + + protected def deserializeResponseBody(response: HttpResponse): Iterable[_] = { + var entity = response.getEntity + var responseBody: String = null + if (entity != null) { + responseBody = EntityUtils.toString(entity, "UTF-8") + } + if (responseBody.startsWith("{") && responseBody.endsWith("}")) + read[Map[String, Object]](responseBody) + else if (responseBody.startsWith("[") && responseBody.endsWith("}")) + read[List[Map[String, Object]]](responseBody) + else if (StringUtils.isEmpty(responseBody)) Map.empty[String, Object] + else if (responseBody.length > 200) throw new HttpException(responseBody.substring(0, 200)) + else throw new HttpException(responseBody) + } + + override def close(): Unit = { + discovery.foreach { + case d: AbstractDiscovery => IOUtils.closeQuietly(d) + case _ => + } + httpClient.close() + executors.asInstanceOf[ExecutionContextExecutorService].shutdown() + } +} \ No newline at end of file diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/Client.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/Client.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/Client.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/Client.scala diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/GenericHttpClient.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/GenericHttpClient.scala new file mode 100644 index 0000000000..9d8caf22cc --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/GenericHttpClient.scala @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient + +import com.webank.wedatasphere.linkis.common.io.{Fs, FsPath} +import com.webank.wedatasphere.linkis.httpclient.config.ClientConfig +import com.webank.wedatasphere.linkis.httpclient.discovery.Discovery +import com.webank.wedatasphere.linkis.httpclient.exception.HttpMethodNotSupportException +import com.webank.wedatasphere.linkis.httpclient.request.HttpAction +import com.webank.wedatasphere.linkis.httpclient.response.{HashMapHttpResult, Result} +import org.apache.http.HttpResponse + + +class GenericHttpClient(clientConfig: ClientConfig, clientName: String) extends AbstractHttpClient(clientConfig, clientName) { + + override protected def createDiscovery(): Discovery = throw new HttpMethodNotSupportException("GenericHttpClient not support discovery.") + + override protected def httpResponseToResult(response: HttpResponse, requestAction: HttpAction, responseBody: String): Option[Result] = { + val result = new HashMapHttpResult + result.set(responseBody, response.getStatusLine.getStatusCode, requestAction.getURL, response.getEntity.getContentType.getValue) + Some(result) + } + + override protected def getFsByUser(user: String, path: FsPath): Fs = { + null + } +} diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/ResultListener.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/ResultListener.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/ResultListener.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/ResultListener.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AbstractAuthenticationStrategy.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AbstractAuthenticationStrategy.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AbstractAuthenticationStrategy.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AbstractAuthenticationStrategy.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/Authentication.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/Authentication.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/Authentication.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/Authentication.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationStrategy.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationStrategy.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationStrategy.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/AuthenticationStrategy.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/HttpAuthentication.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/HttpAuthentication.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/HttpAuthentication.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/authentication/HttpAuthentication.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfig.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfig.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfig.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfig.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala similarity index 98% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala index a49c9ac6dc..a3f9a99351 100644 --- a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/config/ClientConfigBuilder.scala @@ -42,7 +42,7 @@ class ClientConfigBuilder protected() { protected var retryEnabled: Boolean = _ protected var retryHandler: RetryHandler = _ - def addUJESServerUrl(serverUrl: String): this.type = { + def addServerUrl(serverUrl: String): this.type = { this.serverUrl = serverUrl this } diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/AbstractDiscovery.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/AbstractDiscovery.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/AbstractDiscovery.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/AbstractDiscovery.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/Discovery.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/Discovery.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/Discovery.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/Discovery.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/DiscoveryListener.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/DiscoveryListener.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/DiscoveryListener.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/DiscoveryListener.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/HeartbeatAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/HeartbeatAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/HeartbeatAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/discovery/HeartbeatAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/DiscoveryException.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/DiscoveryException.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/DiscoveryException.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/DiscoveryException.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpClientResultException.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpClientResultException.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpClientResultException.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpClientResultException.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala similarity index 87% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala index b50629c9bf..a6b724d7b0 100644 --- a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/exception/HttpMessageParseException.scala @@ -25,4 +25,5 @@ import com.webank.wedatasphere.linkis.common.exception.ErrorException /** * Created by enjoyyin on 2019/5/21. */ -class HttpMessageParseException(errorDesc: String) extends ErrorException(10900, errorDesc) \ No newline at end of file +class HttpMessageParseException(errorDesc: String) extends ErrorException(10900, errorDesc) +class HttpMethodNotSupportException(errorDesc: String) extends ErrorException(10902, errorDesc) \ No newline at end of file diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/AbstractLoadBalancer.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/AbstractLoadBalancer.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/AbstractLoadBalancer.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/AbstractLoadBalancer.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/DefaultLoadbalancerStrategy.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/DefaultLoadbalancerStrategy.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/DefaultLoadbalancerStrategy.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/DefaultLoadbalancerStrategy.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancer.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancer.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancer.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancer.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancerStrategy.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancerStrategy.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancerStrategy.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/loadbalancer/LoadBalancerStrategy.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/Action.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/Action.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/Action.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/Action.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/DownloadAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/DownloadAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/DownloadAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/DownloadAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/GetAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/GetAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/GetAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/GetAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/HttpAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/HttpAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/HttpAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/HttpAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/POSTAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/POSTAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/POSTAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/POSTAction.scala diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/PutAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/PutAction.scala new file mode 100644 index 0000000000..d9113d201e --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/PutAction.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient.request + + +abstract class PutAction extends POSTAction + +abstract class DeleteAction extends GetAction + +abstract class HeadAction extends GetAction + +abstract class OptionsAction extends GetAction \ No newline at end of file diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/ServerUrlAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/ServerUrlAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/ServerUrlAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/ServerUrlAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala index 821bd2dd92..64ca310811 100644 --- a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UploadAction.scala @@ -16,10 +16,10 @@ package com.webank.wedatasphere.linkis.httpclient.request -import scala.tools.nsc.interpreter.InputStream - import java.util +import scala.tools.nsc.interpreter.InputStream + /** * Created by enjoyyin on 2019/5/20. */ diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserAction.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserPwdAction.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserPwdAction.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserPwdAction.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/request/UserPwdAction.scala diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HashMapHttpResult.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HashMapHttpResult.scala new file mode 100644 index 0000000000..b10b048764 --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HashMapHttpResult.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient.response + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.JsonUtils +import com.webank.wedatasphere.linkis.httpclient.exception.HttpClientResultException + + +class HashMapHttpResult extends HttpResult { + + private var resultMap: util.Map[String, Object] = _ + private var responseBody: String = _ + private var statusCode: Int = _ + private var url: String = _ + private var contentType: String = _ + + override def getContentType: String = contentType + + override def getUri: String = url + + override def getStatusCode: Int = statusCode + + def getResultMap: util.Map[String, Object] = resultMap + + override def set(responseBody: String, statusCode: Int, url: String, contentType: String): Unit = { + if(statusCode != 200) throw new HttpClientResultException(s"URL $url request failed! ResponseBody is $responseBody." ) + resultMap = JsonUtils.jackson.readValue(responseBody, classOf[util.Map[String, Object]]) + this.responseBody = responseBody + this.statusCode = statusCode + this.url = url + this.contentType = contentType + } + + override def getResponseBody: String = responseBody +} diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HttpResult.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HttpResult.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HttpResult.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/HttpResult.scala diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/ListResult.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/ListResult.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/ListResult.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/ListResult.scala diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/MetricResult.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/MetricResult.scala new file mode 100644 index 0000000000..5e1d4619ae --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/MetricResult.scala @@ -0,0 +1,60 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient.response + +import java.util + + +trait MetricResult { + + def getMetric: HttpMetric + + def setMetric(metric: HttpMetric): Unit + +} + +trait AbstractMetricResult extends MetricResult { + + private var metric: HttpMetric = _ + + override def getMetric: HttpMetric = metric + + override def setMetric(metric: HttpMetric): Unit = this.metric = metric +} + +class HttpMetric { + + private var prepareReqTime: Long = 0 + private var executeTotalTime: Long = 0 + private var deserializeTime: Long = 0 + private val attempts = new util.ArrayList[Long] + + def setPrepareReqTime(prepareReqTime: Long): Unit = this.prepareReqTime = prepareReqTime + def getPrepareReqTime: Long = prepareReqTime + def setExecuteTotalTime(executeTotalTime: Long): Unit = this.executeTotalTime = executeTotalTime + def getExecuteTotalTime: Long = executeTotalTime + def setDeserializeTime(deserializeTime: Long): Unit = this.deserializeTime = deserializeTime + def getDeserializeTime: Long = deserializeTime + + def addRetry(attemptTime: Long): Unit = attempts.add(attemptTime) + def addRetries(attempts: java.util.List[Long]): Unit = this.attempts.addAll(attempts) + def getAttemptTimes: util.List[Long] = attempts + + def getMetricMap: Map[String, Any] = Map("prepareReqTime" -> prepareReqTime, "executeTotalTime" -> executeTotalTime, "deserializeTime" -> deserializeTime, + "retriedNum" -> attempts.size, "attempts" -> attempts) + +} \ No newline at end of file diff --git a/core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/Result.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/Result.scala similarity index 100% rename from core/httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/Result.scala rename to linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/Result.scala diff --git a/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/impl/DefaultHttpResult.scala b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/impl/DefaultHttpResult.scala new file mode 100644 index 0000000000..6ea135b07d --- /dev/null +++ b/linkis-commons/linkis-httpclient/src/main/scala/com/webank/wedatasphere/linkis/httpclient/response/impl/DefaultHttpResult.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.httpclient.response.impl + +import com.webank.wedatasphere.linkis.httpclient.response.HttpResult + +class DefaultHttpResult extends HttpResult { + + var responseBody: String = _ + var statusCode: Int = _ + var uri: String = _ + var contentType: String = _ + + override def getContentType: String = contentType + + override def getUri: String = uri + + override def getStatusCode: Int = statusCode + + override def set(responseBody: String, statusCode: Int, url: String, contentType: String): Unit = { + this.responseBody = responseBody + this.statusCode = statusCode + this.uri = url + this.contentType = contentType + } + + override def getResponseBody: String = responseBody +} diff --git a/linkis-commons/linkis-message-scheduler/pom.xml b/linkis-commons/linkis-message-scheduler/pom.xml new file mode 100644 index 0000000000..117dcc27a3 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/pom.xml @@ -0,0 +1,86 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-message-scheduler + + + + com.webank.wedatasphere.linkis + linkis-rpc + ${linkis.version} + + + org.springframework + spring-tx + ${spring.version} + + + com.webank.wedatasphere.linkis + linkis-scheduler + ${linkis.version} + + + junit + junit + 4.12 + test + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + src/main/resources + + **/*.properties + **/application.yml + **/bootstrap.yml + **/log4j2.xml + + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Chain.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Chain.java new file mode 100644 index 0000000000..df766e1329 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Chain.java @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/8/4 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Chain { + + String value() default "default"; +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Implicit.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Implicit.java new file mode 100644 index 0000000000..a6ab53f33b --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Implicit.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/7/28 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Implicit { +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Method.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Method.java new file mode 100644 index 0000000000..9714ad1d37 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Method.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/7/14 + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Method { + String value() default ""; +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/NotImplicit.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/NotImplicit.java new file mode 100644 index 0000000000..28f4356eff --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/NotImplicit.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/8/4 + */ +@Target({ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +public @interface NotImplicit { +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Order.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Order.java new file mode 100644 index 0000000000..39a523cb75 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Order.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/7/14 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Order { + int value() default 2147483647; +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Receiver.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Receiver.java new file mode 100644 index 0000000000..0d7c39b1d9 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/annotation/Receiver.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @date 2020/7/14 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Receiver { +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJob.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJob.java new file mode 100644 index 0000000000..494f16b7d4 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJob.java @@ -0,0 +1,185 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; +import com.webank.wedatasphere.linkis.scheduler.queue.JobInfo; +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.LockSupport; + +/** + * @date 2020/7/17 + */ +public class DefaultMessageJob extends Job implements MessageJob { + + private RequestProtocol requestProtocol; + + private Map> methodExecuteWrappers; + + private ServiceMethodContext smc; + + private AbstractMessageSchedulerContext context; + + //implements of MessageJob + + @Override + public RequestProtocol getRequestProtocol() { + return this.requestProtocol; + } + + @Override + public void setRequestProtocol(RequestProtocol requestProtocol) { + this.requestProtocol = requestProtocol; + } + + @Override + public Map> getMethodExecuteWrappers() { + return this.methodExecuteWrappers; + } + + @Override + public void setMethodExecuteWrappers(Map> methodExecuteWrappers) { + this.methodExecuteWrappers = methodExecuteWrappers; + } + + @Override + public ServiceMethodContext getMethodContext() { + return this.smc; + } + + @Override + public void setMethodContext(ServiceMethodContext smc) { + this.smc = smc; + } + + @Override + public AbstractMessageSchedulerContext getContext() { + return this.context; + } + + @Override + public void setContext(AbstractMessageSchedulerContext context) { + this.context = context; + } + + //implements of Job + + @Override + public void init() { + } + + @Override + public ExecuteRequest jobToExecuteRequest() { + return () -> null; + } + + @Override + public String getName() { + return getId(); + } + + @Override + public JobInfo getJobInfo() { + return null; + } + + @Override + public void close() throws IOException { + } + + // implements of Future + + // TODO: 2020/8/3 state 和blockThread的cas化 + + Thread blockThread = null; + + + public Thread getBlockThread() { + return this.blockThread; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + if (mayInterruptIfRunning) { + cancel(); + } + return true; + } + + @Override + public Object get() throws ExecutionException, InterruptedException { + if (!this.isCompleted()) { + waitComplete(false, -1L); + } + return handleResult(); + } + + @Override + public Object getPartial() { + return this.getMethodContext().getResult(); + } + + public Object handleResult() throws ExecutionException { + if (this.isSucceed()) { + return this.getMethodContext().getResult(); + } + // TODO: 2020/8/3 cancel逻辑加入 + throw new ExecutionException(this.getErrorResponse().t()); + } + + @Override + public Object get(long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { + if (unit == null) unit = TimeUnit.NANOSECONDS; + if (!this.isCompleted() + && !SchedulerEventState.isCompleted(SchedulerEventState.apply(waitComplete(true, unit.toNanos(timeout))))) { + throw new TimeoutException(); + } + return handleResult(); + } + + private int waitComplete(boolean timed, long nanos) throws InterruptedException { + long endTime = timed ? System.nanoTime() + nanos : -1L; + for (; ; ) { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + if (this.isCompleted()) { + return this.getState().id(); + } else if (blockThread == null) + blockThread = Thread.currentThread(); + else if (timed) { + nanos = endTime - System.nanoTime(); + if (nanos <= 0) { + return this.getState().id(); + } + LockSupport.parkNanos(this, nanos); + } else + LockSupport.park(this); + } + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJobBuilder.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJobBuilder.java new file mode 100644 index 0000000000..d587a989f7 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultMessageJobBuilder.java @@ -0,0 +1,78 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.util.List; +import java.util.Map; + +/** + * @date 2020/7/17 + */ +public class DefaultMessageJobBuilder implements MessageJobBuilder { + + private RequestProtocol requestProtocol; + + private Map> methodExecuteWrappers; + + private ServiceMethodContext smc; + + private AbstractMessageSchedulerContext context; + + @Override + public MessageJobBuilder of() { + return new DefaultMessageJobBuilder(); + } + + @Override + public MessageJobBuilder with(RequestProtocol requestProtocol) { + this.requestProtocol = requestProtocol; + return this; + } + + @Override + public MessageJobBuilder with(Map> methodExecuteWrappers) { + this.methodExecuteWrappers = methodExecuteWrappers; + return this; + } + + + @Override + public MessageJobBuilder with(ServiceMethodContext smc) { + this.smc = smc; + return this; + } + + @Override + public MessageJobBuilder with(AbstractMessageSchedulerContext context) { + this.context = context; + return this; + } + + @Override + public MessageJob build() { + DefaultMessageJob messageJob = new DefaultMessageJob(); + messageJob.setMethodExecuteWrappers(this.methodExecuteWrappers); + messageJob.setRequestProtocol(this.requestProtocol); + messageJob.setMethodContext(this.smc); + messageJob.setContext(context); + return messageJob; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultServiceMethodContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultServiceMethodContext.java new file mode 100644 index 0000000000..ccefa6a7be --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/DefaultServiceMethodContext.java @@ -0,0 +1,167 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.message.context.MessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.exception.MessageWarnException; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; +import com.webank.wedatasphere.linkis.rpc.Sender; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState; +import scala.concurrent.duration.Duration; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import static com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.*; + +/** + * @date 2020/7/14 + */ +public class DefaultServiceMethodContext implements ServiceMethodContext { + + private final Map attributes = new ConcurrentHashMap<>(); + + private final ThreadLocal> skips = new ThreadLocal<>(); + + private final ThreadLocal job = new ThreadLocal<>(); + + @Override + public void putAttribute(String key, Object value) { + this.attributes.put(key, value); + } + + @Override + public void putIfAbsent(String key, Object value) { + if (!notNull(key)) { + putAttribute(key, value); + } + } + + @SuppressWarnings("unchecked") + public T getAttribute(String key) { + return (T) this.attributes.get(key); + } + + @SuppressWarnings("unchecked") + public T getAttributeOrDefault(String key, T defaultValue) { + return (T) this.attributes.getOrDefault(key, defaultValue); + } + + @Override + public String getUser() { + return getAttribute(USER_KEY); + } + + @Override + public HttpServletRequest getRequest() { + return getAttribute(REQUEST_KEY); + } + + @Override + public boolean notNull(String key) { + return this.attributes.get(key) != null; + } + + @Override + public MessageJob publish(RequestProtocol requestProtocol) throws MessageWarnException { + MessageSchedulerContext context = getAttribute(CONTEXT_KEY); + return context.getPublisher().publish(requestProtocol, this); + } + + @Override + public void send(Object message) { + Sender sender = getAttribute(SENDER_KEY); + sender.send(message); + } + + @Override + public Object ask(Object message) { + Sender sender = getAttribute(SENDER_KEY); + return sender.ask(message); + } + + @Override + public Object ask(Object message, Duration timeout) { + Sender sender = getAttribute(SENDER_KEY); + return sender.ask(message, timeout); + } + + @Override + public Sender getSender() { + return getAttribute(SENDER_KEY); + } + + @Override + public void setTimeoutPolicy(MessageJobTimeoutPolicy policy) { + putAttribute(TIMEOUT_POLICY, policy); + } + + @Override + public void setResult(Object result) { + putAttribute(RESULT_KEY, result); + } + + @Override + public T getResult() { + return getAttribute(RESULT_KEY); + } + + @Override + public boolean isInterrupted() { + //linkis-shceduler 没有isInterrupted状态 + return SchedulerEventState.Cancelled() == this.job.get().getState(); + } + + @Override + public boolean isCancel() { + //linkis-shceduler只有cancel + return SchedulerEventState.Cancelled() == this.job.get().getState(); + } + + @Override + public boolean isSuccess() { + return SchedulerEventState.Succeed() == this.job.get().getState(); + } + + public void setJob(Job job) { + this.job.set(job); + } + + public void removeJob() { + this.job.remove(); + } + + public void setSkips(Integer... orders) { + Set oldOrders = skips.get(); + if (oldOrders == null) { + Set newOrders = new HashSet(Arrays.asList(orders)); + skips.set(newOrders); + } else { + oldOrders.addAll(Arrays.asList(orders)); + } + } + + public void removeSkips() { + this.skips.remove(); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/Future.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/Future.java new file mode 100644 index 0000000000..d21be8eae7 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/Future.java @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * @date 2020/8/4 + */ +public interface Future { + + boolean cancel(boolean mayInterruptIfRunning); + + V get() throws InterruptedException, ExecutionException; + + V getPartial(); + + V get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException; +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJob.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJob.java new file mode 100644 index 0000000000..7afe7f168e --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJob.java @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.util.List; +import java.util.Map; + + +/** + * @date 2020/7/14 + */ +public interface MessageJob extends Runnable, Future { + + RequestProtocol getRequestProtocol(); + + void setRequestProtocol(RequestProtocol requestProtocol); + + Map> getMethodExecuteWrappers(); + + void setMethodExecuteWrappers(Map> methodExecuteWrappers); + + ServiceMethodContext getMethodContext(); + + void setMethodContext(ServiceMethodContext smc); + + AbstractMessageSchedulerContext getContext(); + + void setContext(AbstractMessageSchedulerContext context); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobBuilder.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobBuilder.java new file mode 100644 index 0000000000..8ca452555f --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobBuilder.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.util.List; +import java.util.Map; + +/** + * @date 2020/7/17 + */ +public interface MessageJobBuilder { + + MessageJobBuilder of(); + + MessageJobBuilder with(RequestProtocol requestProtocol); + + MessageJobBuilder with(Map> methodExecuteWrappers); + + MessageJobBuilder with(ServiceMethodContext smc); + + MessageJobBuilder with(AbstractMessageSchedulerContext context); + + MessageJob build(); +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobListener.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobListener.java new file mode 100644 index 0000000000..5ad6f394ba --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobListener.java @@ -0,0 +1,57 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.scheduler.listener.JobListener; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; + +import java.util.concurrent.locks.LockSupport; + +/** + * @date 2020/7/17 + */ +public class MessageJobListener extends JavaLog implements JobListener { + + @Override + public void onJobScheduled(Job job) { + + } + + @Override + public void onJobInited(Job job) { + + } + + @Override + public void onJobWaitForRetry(Job job) { + + } + + @Override + public void onJobRunning(Job job) { + + } + + @Override + public void onJobCompleted(Job job) { + if (job instanceof DefaultMessageJob) { + LockSupport.unpark(((DefaultMessageJob) job).getBlockThread()); + } + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobTimeoutPolicy.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobTimeoutPolicy.java new file mode 100644 index 0000000000..f23a46e5b1 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/MessageJobTimeoutPolicy.java @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + +/** + * @date 2020/7/27 + */ +public enum MessageJobTimeoutPolicy { + /** + * 取消,但是不打断 + */ + CANCEL, + /** + * 打断 + */ + INTERRUPT, + /** + * 部分返回 + */ + PARTIAL +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/ServiceMethodContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/ServiceMethodContext.java new file mode 100644 index 0000000000..17329f6c19 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/builder/ServiceMethodContext.java @@ -0,0 +1,73 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.builder; + + +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; +import com.webank.wedatasphere.linkis.rpc.Sender; +import scala.concurrent.duration.Duration; + +import javax.servlet.http.HttpServletRequest; + +/** + * @date 2020/7/14 + */ +public interface ServiceMethodContext { + + void putAttribute(String key, Object value); + + void putIfAbsent(String key, Object value); + + T getAttribute(String key); + + T getAttributeOrDefault(String key, T defaultValue); + + String getUser(); + + HttpServletRequest getRequest(); + + boolean notNull(String key); + + MessageJob publish(RequestProtocol requestProtocol); + + void send(Object message); + + Object ask(Object message); + + Object ask(Object message, Duration timeout); + + Sender getSender(); + + void setTimeoutPolicy(MessageJobTimeoutPolicy policy); + + void setResult(Object result); + + T getResult(); + + /** + * interrupted 状态 + * messageJob执行失败,messageJob 被cancel,并且mayInterruptIfRunning 为true的情况 + * + * @return + */ + boolean isInterrupted(); + + boolean isCancel(); + + boolean isSuccess(); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/conf/MessageSchedulerConf.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/conf/MessageSchedulerConf.java new file mode 100644 index 0000000000..4cc4177347 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/conf/MessageSchedulerConf.java @@ -0,0 +1,43 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.conf; + + +import com.webank.wedatasphere.linkis.common.conf.CommonVars; +import org.reflections.Reflections; +import org.reflections.scanners.MethodAnnotationsScanner; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; + +/** + * @date 2020/7/14 + */ +public class MessageSchedulerConf { + + public final static String SERVICE_SCAN_PACKAGE = CommonVars.apply("wds.linkis.ms.service.scan.package", "com.webank.wedatasphere").getValue(); + + public final static Reflections REFLECTIONS = new Reflections(SERVICE_SCAN_PACKAGE, new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()); + + public final static String USER_KEY = "_username_"; + public final static String REQUEST_KEY = "_req_"; + public final static String RESULT_KEY = "_result_"; + public final static String CONTEXT_KEY = "_context_"; + public final static String SENDER_KEY = "_sender_"; + public final static String TIMEOUT_POLICY = "_timeout_policy_"; + public final static String DURATION_KEY = "_duration_"; + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/AbstractMessageSchedulerContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/AbstractMessageSchedulerContext.java new file mode 100644 index 0000000000..4e3fbfa184 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/AbstractMessageSchedulerContext.java @@ -0,0 +1,115 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.context; + +import com.webank.wedatasphere.linkis.message.builder.MessageJobBuilder; +import com.webank.wedatasphere.linkis.message.parser.ImplicitParser; +import com.webank.wedatasphere.linkis.message.parser.ServiceParser; +import com.webank.wedatasphere.linkis.message.publisher.MessagePublisher; +import com.webank.wedatasphere.linkis.message.registry.AbstractImplicitRegistry; +import com.webank.wedatasphere.linkis.message.registry.AbstractServiceRegistry; +import com.webank.wedatasphere.linkis.message.scheduler.MessageScheduler; +import com.webank.wedatasphere.linkis.message.tx.TransactionManager; + +/** + * @date 2020/7/15 + */ +public abstract class AbstractMessageSchedulerContext implements MessageSchedulerContext { + + private AbstractServiceRegistry serviceRegistry; + + private MessagePublisher messagePublisher; + + private ServiceParser serviceParser; + + private MessageScheduler messageScheduler; + + private MessageJobBuilder messageJobBuilder; + + private TransactionManager txManager; + + private AbstractImplicitRegistry implicitRegistry; + + private ImplicitParser implicitParser; + + @Override + public MessagePublisher getPublisher() { + return this.messagePublisher; + } + + public void setPublisher(MessagePublisher messagePublisher) { + this.messagePublisher = messagePublisher; + } + + @Override + public AbstractServiceRegistry getServiceRegistry() { + return this.serviceRegistry; + } + + public void setServiceRegistry(AbstractServiceRegistry serviceRegistry) { + this.serviceRegistry = serviceRegistry; + } + + public void setserviceParser(ServiceParser serviceParser) { + this.serviceParser = serviceParser; + } + + public void setImplicitRegistry(AbstractImplicitRegistry implicitRegistry) { + this.implicitRegistry = implicitRegistry; + } + + public ImplicitParser getImplicitParser() { + return implicitParser; + } + + public void setImplicitParser(ImplicitParser implicitParser) { + this.implicitParser = implicitParser; + } + + public AbstractImplicitRegistry getImplicitRegistry() { + return this.implicitRegistry; + } + + public ServiceParser getservieParser() { + return this.serviceParser; + } + + public void setScheduler(MessageScheduler messageScheduler) { + this.messageScheduler = messageScheduler; + } + + public MessageScheduler getScheduler() { + return this.messageScheduler; + } + + public void setJobBuilder(MessageJobBuilder messageJobBuilder) { + this.messageJobBuilder = messageJobBuilder; + } + + public MessageJobBuilder getJobBuilder() { + return this.messageJobBuilder; + } + + public TransactionManager getTxManager() { + return this.txManager; + } + + public void setTxManager(TransactionManager txManager) { + this.txManager = txManager; + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/DefaultMessageSchedulerContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/DefaultMessageSchedulerContext.java new file mode 100644 index 0000000000..119c43d181 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/DefaultMessageSchedulerContext.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.context; + +import com.webank.wedatasphere.linkis.message.builder.DefaultMessageJobBuilder; +import com.webank.wedatasphere.linkis.message.parser.DefaultImplicitParser; +import com.webank.wedatasphere.linkis.message.parser.DefaultServiceParser; +import com.webank.wedatasphere.linkis.message.publisher.DefaultMessagePublisher; +import com.webank.wedatasphere.linkis.message.registry.AbstractImplicitRegistry; +import com.webank.wedatasphere.linkis.message.registry.AbstractServiceRegistry; +import com.webank.wedatasphere.linkis.message.scheduler.DefaultMessageScheduler; +import com.webank.wedatasphere.linkis.message.tx.TransactionManager; + +/** + * @date 2020/7/15 + */ +public class DefaultMessageSchedulerContext extends AbstractMessageSchedulerContext { + + { + setImplicitParser(new DefaultImplicitParser()); + setImplicitRegistry(new AbstractImplicitRegistry(this){}); + setserviceParser(new DefaultServiceParser()); + setPublisher(new DefaultMessagePublisher(this)); + setServiceRegistry(new AbstractServiceRegistry(this) { + }); + setScheduler(new DefaultMessageScheduler()); + setJobBuilder(new DefaultMessageJobBuilder()); + setTxManager(new TransactionManager() { + }); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MSContextInstance.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MSContextInstance.java new file mode 100644 index 0000000000..2b5be0b67e --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MSContextInstance.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.context; + +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @date 2020/9/17 + */ +public class MSContextInstance { + + private static final Logger LOGGER = LoggerFactory.getLogger(MSContextInstance.class); + + private static volatile MessageSchedulerContext context = null; + + public static MessageSchedulerContext get() { + if (context == null) { + synchronized (MSContextInstance.class) { + if (context != null) { + try { + MessageSchedulerContext bean = MessageUtils.getBean(MessageSchedulerContext.class); + if (bean != null) + context = bean; + else + context = new DefaultMessageSchedulerContext(); + } catch (Throwable e) { + LOGGER.warn("can not load message context from ioc container"); + context = new DefaultMessageSchedulerContext(); + } + } + + } + } + return context; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MessageSchedulerContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MessageSchedulerContext.java new file mode 100644 index 0000000000..15aea42fb2 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/MessageSchedulerContext.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.context; + +import com.webank.wedatasphere.linkis.message.publisher.MessagePublisher; +import com.webank.wedatasphere.linkis.message.registry.ImplicitRegistry; +import com.webank.wedatasphere.linkis.message.registry.ServiceRegistry; + +/** + * @date 2020/7/14 + */ +public interface MessageSchedulerContext { + + MessagePublisher getPublisher(); + + ServiceRegistry getServiceRegistry(); + + ImplicitRegistry getImplicitRegistry(); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/SpringMessageSchedulerContext.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/SpringMessageSchedulerContext.java new file mode 100644 index 0000000000..f087b988dc --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/context/SpringMessageSchedulerContext.java @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.context; + +import com.webank.wedatasphere.linkis.message.builder.DefaultMessageJobBuilder; +import com.webank.wedatasphere.linkis.message.parser.DefaultImplicitParser; +import com.webank.wedatasphere.linkis.message.parser.DefaultServiceParser; +import com.webank.wedatasphere.linkis.message.publisher.DefaultMessagePublisher; +import com.webank.wedatasphere.linkis.message.registry.SpringImplicitRegistry; +import com.webank.wedatasphere.linkis.message.registry.SpringServiceRegistry; +import com.webank.wedatasphere.linkis.message.scheduler.DefaultMessageScheduler; +import com.webank.wedatasphere.linkis.message.tx.SpringTransactionManager; + +/** + * @date 2020/9/11 + */ +public class SpringMessageSchedulerContext extends AbstractMessageSchedulerContext { + + { + setImplicitParser(new DefaultImplicitParser()); + setImplicitRegistry(new SpringImplicitRegistry(this)); + setserviceParser(new DefaultServiceParser()); + setPublisher(new DefaultMessagePublisher(this)); + setServiceRegistry(new SpringServiceRegistry(this)); + setScheduler(new DefaultMessageScheduler()); + setJobBuilder(new DefaultMessageJobBuilder()); + setTxManager(new SpringTransactionManager()); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageErrorException.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageErrorException.java new file mode 100644 index 0000000000..b072b42ec6 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageErrorException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.exception; + +import com.webank.wedatasphere.linkis.common.exception.ErrorException; + +/** + * @date 2020/7/15 + */ +public class MessageErrorException extends ErrorException { + + public MessageErrorException(int errCode, String desc) { + super(errCode, desc); + } + + public MessageErrorException(int errCode, String desc, Throwable t) { + super(errCode, desc); + initCause(t); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageWarnException.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageWarnException.java new file mode 100644 index 0000000000..039c97c531 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/exception/MessageWarnException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.exception; + +import com.webank.wedatasphere.linkis.common.exception.WarnException; + +/** + * @date 2020/6/10 17:43 + */ +public class MessageWarnException extends WarnException { + + public MessageWarnException(int errCode, String desc) { + super(errCode, desc); + } + + public MessageWarnException(int errCode, String desc, Throwable t) { + super(errCode, desc); + initCause(t); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultImplicitParser.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultImplicitParser.java new file mode 100644 index 0000000000..91e27ea253 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultImplicitParser.java @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import com.webank.wedatasphere.linkis.message.annotation.Implicit; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @date 2020/7/28 + */ +public class DefaultImplicitParser implements ImplicitParser { + @Override + public Map> parse(Object implicitObject) { + Method[] methods = implicitObject.getClass().getMethods(); + return Arrays.stream(methods) + .filter(this::methodFilterPredicate) + .map(m -> this.getImplicitMethod(m, implicitObject)) + .collect(Collectors.groupingBy(ImplicitMethod::getOutput)); + } + + private ImplicitMethod getImplicitMethod(Method method, Object implicitObject) { + ImplicitMethod implicitMethod = new ImplicitMethod(); + implicitMethod.setMethod(method); + implicitMethod.setImplicitObject(implicitObject); + implicitMethod.setInput(method.getParameterTypes()[0].getName()); + implicitMethod.setOutput(method.getReturnType().getName()); + return implicitMethod; + } + + /** + * 标注了@implicit注解 + * 入参数量只有一个,返回值不为void + * 入参需要是RequestProtocol 的子类 + * 排除出参是入参的父类的情况 + * + * @param method + * @return + */ + private boolean methodFilterPredicate(Method method) { + if (method.getAnnotation(Implicit.class) != null + && method.getParameterCount() == 1 + && !void.class.equals(method.getReturnType())) { + // TODO: 2020/8/4 返回值支持集合 ,参数也可以不用是RequestProtocol的子类 + Class> input = method.getParameterTypes()[0]; + return RequestProtocol.class.isAssignableFrom(input) && !method.getReturnType().isAssignableFrom(input); + } + return false; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultServiceParser.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultServiceParser.java new file mode 100644 index 0000000000..e9f2e10db1 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/DefaultServiceParser.java @@ -0,0 +1,95 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import com.webank.wedatasphere.linkis.message.annotation.Chain; +import com.webank.wedatasphere.linkis.message.annotation.NotImplicit; +import com.webank.wedatasphere.linkis.message.annotation.Order; +import com.webank.wedatasphere.linkis.message.annotation.Receiver; +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @date 2020/7/15 + */ +public class DefaultServiceParser implements ServiceParser { + + @Override + public Map> parse(Object service) { + // TODO: 2020/7/15 more analysis + Method[] methods = service.getClass().getMethods(); + return Arrays.stream(methods) + .filter(this::methodFilterPredicate) + .map(m -> getServiceMethod(m, service)) + .collect(Collectors.groupingBy(ServiceMethod::getProtocolName)); + } + + private ServiceMethod getServiceMethod(Method method, Object service) { + ServiceMethod serviceMethod = new ServiceMethod(); + serviceMethod.setMethod(method); + serviceMethod.setService(service); + serviceMethod.setAlias(String.format("%s.%s", service.getClass().getName(), method.getName())); + Order order = method.getAnnotation(Order.class); + if (order != null) { + serviceMethod.setOrder(order.value()); + } + Chain chain = method.getAnnotation(Chain.class); + if (chain != null) serviceMethod.setChainName(chain.value()); + Parameter[] parameters = method.getParameters(); + if (parameters.length == 2) { + serviceMethod.setHasMethodContext(true); + if (ServiceMethodContext.class.isAssignableFrom(parameters[0].getType())) + serviceMethod.setMethodContextOnLeft(true); + } + @SuppressWarnings("all") + Parameter parameter = Arrays.stream(parameters) + .filter(p -> !ServiceMethodContext.class.isAssignableFrom(p.getType())).findFirst().get(); + NotImplicit annotation = parameter.getAnnotation(NotImplicit.class); + if (annotation != null) serviceMethod.setAllowImplicit(false); + serviceMethod.setProtocolName(parameter.getType().getName()); + return serviceMethod; + } + + /** + * 标注了@Receiver注解,方法至少一个参数 + * 1个参数:非ServiceMethodContext 子类即可 + * 2个参数 其中一个需要是ServiceMethodContext 的子类 && 2个参数都非ServiceMethodContext 子类即可 + * + * @param method + * @return + */ + private boolean methodFilterPredicate(Method method) { + if (method.getAnnotation(Receiver.class) != null) { + Class>[] parameterTypes = method.getParameterTypes(); + if (method.getParameterCount() == 1) { + return !ServiceMethodContext.class.isAssignableFrom(parameterTypes[0]); + } else if (method.getParameterCount() == 2) { + boolean hasContext = Arrays.stream(parameterTypes).anyMatch(ServiceMethodContext.class::isAssignableFrom); + boolean allContext = Arrays.stream(parameterTypes).allMatch(ServiceMethodContext.class::isAssignableFrom); + return hasContext && !allContext; + } + } + return false; + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitMethod.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitMethod.java new file mode 100644 index 0000000000..0c2e05ed7e --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitMethod.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import java.lang.reflect.Method; + +/** + * @date 2020/7/28 + */ +public class ImplicitMethod { + + private Object implicitObject; + + private Method method; + + private String input; + + private String output; + + public Object getImplicitObject() { + return implicitObject; + } + + public void setImplicitObject(Object implicitObject) { + this.implicitObject = implicitObject; + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public String getOutput() { + return output; + } + + public void setOutput(String output) { + this.output = output; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitParser.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitParser.java new file mode 100644 index 0000000000..766ea39a68 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ImplicitParser.java @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import java.util.List; +import java.util.Map; + +/** + * @date 2020/7/28 + */ +public interface ImplicitParser { + + Map> parse(Object implicitObject); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceMethod.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceMethod.java new file mode 100644 index 0000000000..14be8e0a48 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceMethod.java @@ -0,0 +1,125 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import java.lang.reflect.Method; + +/** + * @date 2020/7/15 + */ +public class ServiceMethod { + + private Object service; + + private Method method; + + private String alias; + + private String protocolName; + + private int order = 2147483647; + + private boolean allowImplicit = true; + + private boolean hasMethodContext; + + private ImplicitMethod implicitMethod; + + private boolean methodContextOnLeft; + + private String chainName = "default"; + + public String getChainName() { + return chainName; + } + + public void setChainName(String chainName) { + this.chainName = chainName; + } + + public ImplicitMethod getImplicitMethod() { + return implicitMethod; + } + + public void setImplicitMethod(ImplicitMethod implicitMethod) { + this.implicitMethod = implicitMethod; + } + + public boolean isHasMethodContext() { + return hasMethodContext; + } + + public void setHasMethodContext(boolean hasMethodContext) { + this.hasMethodContext = hasMethodContext; + } + + public boolean isAllowImplicit() { + return allowImplicit; + } + + public void setAllowImplicit(boolean allowImplicit) { + this.allowImplicit = allowImplicit; + } + + public int getOrder() { + return order; + } + + public void setOrder(int order) { + this.order = order; + } + + public Object getService() { + return service; + } + + public void setService(Object service) { + this.service = service; + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public String getProtocolName() { + return protocolName; + } + + public void setProtocolName(String protocolName) { + this.protocolName = protocolName; + } + + public boolean isMethodContextOnLeft() { + return methodContextOnLeft; + } + + public void setMethodContextOnLeft(boolean methodContextOnLeft) { + this.methodContextOnLeft = methodContextOnLeft; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceParser.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceParser.java new file mode 100644 index 0000000000..39cf158a52 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/parser/ServiceParser.java @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.parser; + +import java.util.List; +import java.util.Map; + +/** + * @date 2020/7/15 + */ +public interface ServiceParser { + + Map> parse(Object service); + +} \ No newline at end of file diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/AbstractMessagePublisher.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/AbstractMessagePublisher.java new file mode 100644 index 0000000000..537016cb1e --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/AbstractMessagePublisher.java @@ -0,0 +1,154 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.publisher; + +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.message.builder.DefaultServiceMethodContext; +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.exception.MessageWarnException; +import com.webank.wedatasphere.linkis.message.parser.ImplicitMethod; +import com.webank.wedatasphere.linkis.message.parser.ServiceMethod; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import static com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.CONTEXT_KEY; + +/** + * @date 2020/7/15 + */ +public abstract class AbstractMessagePublisher extends JavaLog implements MessagePublisher { + + private AbstractMessageSchedulerContext context; + + public AbstractMessagePublisher(AbstractMessageSchedulerContext context) { + this.context = context; + } + + public void setContext(AbstractMessageSchedulerContext context) { + this.context = context; + } + + /** + * key是requestProtocol的全类名,Map中,key是groupName + */ + private final Map>> protocolServiceMethodCache = new ConcurrentHashMap<>(); + + + @Override + public MessageJob publish(RequestProtocol requestProtocol) { + return publish(requestProtocol, new DefaultServiceMethodContext()); + } + + @Override + public MessageJob publish(RequestProtocol requestProtocol, ServiceMethodContext serviceMethodContext) { + logger().debug(String.format("receive request:%s", requestProtocol.getClass().getName())); + serviceMethodContext.putIfAbsent(CONTEXT_KEY, this.context); + Map> methodExecuteWrappers = getMethodExecuteWrappers(requestProtocol); + MessageJob messageJob = this.context.getJobBuilder().of() + .with(serviceMethodContext).with(requestProtocol).with(this.context) + .with(methodExecuteWrappers).build(); + this.context.getScheduler().submit(messageJob); + return messageJob; + } + + private Map> getMethodExecuteWrappers(RequestProtocol requestProtocol) { + String protocolName = requestProtocol.getClass().getName(); + Map> protocolServiceMethods = this.protocolServiceMethodCache.get(protocolName); + //静态信息,无需加锁 + if (protocolServiceMethods == null) { + Map> serviceMethodCache = this.context.getServiceRegistry().getServiceMethodCache(); + Map> implicitMethodCache = this.context.getImplicitRegistry().getImplicitMethodCache(); + //找出注册方法中,参数是当前请求的父类的 + Map> serviceMatchs = serviceMethodCache.entrySet().stream() + .filter(e -> MessageUtils.isAssignableFrom(e.getKey(), protocolName)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + //找出implicit方法中,参数是当前请求父类的,根据注册规则,implicit的出参必然和上面的servicematchKeys 不会重复 + Map> implicitMatchs = new HashMap<>(); + for (Map.Entry> implicitEntry : implicitMethodCache.entrySet()) { + //当前implicitMehtod中,input需要是protocolName 的父类or同类 + String implicitEntryKey = implicitEntry.getKey(); + List implicitEntryValue = implicitEntry.getValue(); + // 支持隐式 返回值 和service之间的接口继承关系 + Map> implicitServiceMethods = serviceMethodCache.entrySet().stream() + .filter(e -> MessageUtils.isAssignableFrom(e.getKey(), implicitEntryKey)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + //排除implicit返回值是protocolName的父类,可能存在另外一个不相干protocol的转换方法的返回值是当前protocol的父类 + if (!MessageUtils.isAssignableFrom(implicitEntryKey, protocolName) && !implicitServiceMethods.isEmpty()) { + for (Map.Entry> implicitServiceMethodEntry : implicitServiceMethods.entrySet()) { + String implicitServiceMethodEntryKey = implicitServiceMethodEntry.getKey(); + List implicitServiceMethodEntryValue = implicitServiceMethodEntry.getValue(); + //参数中要支持implicit的 + List filteredServiceMethods = implicitServiceMethodEntryValue.stream() + .filter(ServiceMethod::isAllowImplicit) + .collect(Collectors.toList()); + //隐式方法中参数需要是当前请求protocol的本类或子类 + List filteredImplicitMethods = implicitEntryValue.stream() + .filter(v -> MessageUtils.isAssignableFrom(v.getInput(), protocolName)) + .collect(Collectors.toList()); + if (!filteredServiceMethods.isEmpty() && !filteredImplicitMethods.isEmpty()) { + //针对每个ServiceMethod 选择,因为可能他们处于不同的service之间 + for (ServiceMethod filteredServiceMethod : filteredServiceMethods) { + Object service = filteredServiceMethod.getService(); + //同service优先 + Optional first = filteredImplicitMethods.stream() + .filter(m -> m.getImplicitObject() == service).findFirst(); + if (first.isPresent()) { + filteredServiceMethod.setImplicitMethod(first.get()); + } else { + // TODO: 2020/7/30 入参父子类的判断优先级,和scala一致 + //简单的只取第一个 + filteredServiceMethod.setImplicitMethod(filteredImplicitMethods.get(0)); + } + } + //添加到缓存中 + implicitMatchs.put(implicitServiceMethodEntryKey, filteredServiceMethods); + } + } + } + } + //merge + serviceMatchs.putAll(implicitMatchs); + //group by chain name 扁平化后再group,这时protocol的父类可能和转换的处于同一个chain中 + serviceMatchs = serviceMatchs.values().stream().flatMap(Collection::stream).collect(Collectors.groupingBy(ServiceMethod::getChainName)); + //order判断 + for (List value : serviceMatchs.values()) { + Integer repeatOrder = MessageUtils.repeatOrder(value); + if (repeatOrder != null && !MessageUtils.orderIsLast(repeatOrder, value)) { + throw new MessageWarnException(10000, String.format("repeat order : %s for request %s", repeatOrder, protocolName)); + } + } + this.protocolServiceMethodCache.put(protocolName, serviceMatchs); + } + //clone 对象并返回 + return serviceMethod2Wrapper(this.protocolServiceMethodCache.get(protocolName)); + } + + private Map> serviceMethod2Wrapper(Map> source) { + HashMap> target = new HashMap<>(); + source.forEach((k, v) -> target.put(k, v.stream().map(MethodExecuteWrapper::new).collect(Collectors.toList()))); + return target; + } + + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/DefaultMessagePublisher.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/DefaultMessagePublisher.java new file mode 100644 index 0000000000..d5e6d80ffc --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/DefaultMessagePublisher.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.publisher; + +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; + +/** + * @date 2020/7/15 + */ +public class DefaultMessagePublisher extends AbstractMessagePublisher { + + public DefaultMessagePublisher(AbstractMessageSchedulerContext context) { + super(context); + } + + public DefaultMessagePublisher() { + this(null); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/MessagePublisher.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/MessagePublisher.java new file mode 100644 index 0000000000..d92fe12843 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/publisher/MessagePublisher.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.publisher; + +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + + +/** + * @date 2020/7/14 + */ +public interface MessagePublisher { + + MessageJob publish(RequestProtocol requestProtocol); + + MessageJob publish(RequestProtocol requestProtocol, ServiceMethodContext serviceMethodContext); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractImplicitRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractImplicitRegistry.java new file mode 100644 index 0000000000..cf4f9c617f --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractImplicitRegistry.java @@ -0,0 +1,88 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + +import com.google.common.collect.Interner; +import com.google.common.collect.Interners; +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.parser.ImplicitMethod; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @date 2020/7/28 + */ +public abstract class AbstractImplicitRegistry extends JavaLog implements ImplicitRegistry { + + private final AbstractMessageSchedulerContext context; + /** + * key: output + */ + private final Map> implicitMethodCache = new ConcurrentHashMap<>(); + + public AbstractImplicitRegistry(AbstractMessageSchedulerContext context) { + this.context = context; + } + + @SuppressWarnings("all") + public final Interner lock = Interners.newWeakInterner(); + + private final Map registedImplicitObjectMap = new ConcurrentHashMap<>(); + + + @Override + @SuppressWarnings("all") + public void register(Object implicitObject) { + String implicitObjectName = implicitObject.getClass().getName(); + synchronized (this.lock.intern(implicitObjectName)) { + //1.是否解析过 + Object o = this.registedImplicitObjectMap.get(implicitObjectName); + if (o != null) return; + Map> implicitMethods = this.context.getImplicitParser().parse(implicitObject); + implicitMethods.forEach(this::refreshImplicitMethodCache); + this.registedImplicitObjectMap.put(implicitObjectName, implicitObject); + } + } + + @SuppressWarnings("all") + private void refreshImplicitMethodCache(String key, List implicitMethods) { + synchronized (this.lock.intern(key)) { + //同一个implicitObject 下的入参,出参相同的implit,会被过滤掉 + List implicitMethodsOld = this.implicitMethodCache.computeIfAbsent(key, k -> new ArrayList<>()); + for (ImplicitMethod implicitMethod : implicitMethods) { + if (isImplicitRepeat(new ArrayList<>(implicitMethodsOld), implicitMethod)) { + // TODO: 2020/7/29 logging + continue; + } + implicitMethodsOld.add(implicitMethod); + } + } + } + + private boolean isImplicitRepeat(List implicitMethodsOld, ImplicitMethod implicitMethod) { + return implicitMethodsOld.stream(). + anyMatch(im -> im.getImplicitObject() == implicitMethod.getImplicitObject() && im.getInput().equals(implicitMethod.getInput())); + } + + public Map> getImplicitMethodCache() { + return this.implicitMethodCache; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractServiceRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractServiceRegistry.java new file mode 100644 index 0000000000..f96f98b22c --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/AbstractServiceRegistry.java @@ -0,0 +1,92 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + +import com.google.common.collect.Interner; +import com.google.common.collect.Interners; +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.exception.MessageWarnException; +import com.webank.wedatasphere.linkis.message.parser.ServiceMethod; +import com.webank.wedatasphere.linkis.message.parser.ServiceParser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @date 2020/7/15 + */ +public abstract class AbstractServiceRegistry extends JavaLog implements ServiceRegistry { + + @SuppressWarnings("all") + public final Interner lock = Interners.newWeakInterner(); + /** + * key:requestprotocol or custom implicit object class name + */ + private final Map> serviceMethodCache = new ConcurrentHashMap<>(); + + private final Map registedServieMap = new ConcurrentHashMap<>(); + + private final AbstractMessageSchedulerContext context; + + public AbstractServiceRegistry(AbstractMessageSchedulerContext context) { + this.context = context; + } + + @SuppressWarnings("all") + @Override + public void register(Object service) { + //防止不同方式注册时候的并发,比如spring和手动注册,同时防止不同包名下类名一样的service + String serviceName = service.getClass().getName(); + synchronized (this.lock.intern(serviceName)) { + //1.是否注册过 + Object o = this.registedServieMap.get(serviceName); + if (o != null) return; + //2..解析 + ServiceParser serviceParser = this.context.getservieParser(); + Map> serviceMethods = serviceParser.parse(service); + //3.注册 + serviceMethods.forEach(this::register); + this.registedServieMap.put(serviceName, service); + } + } + + /** + * @param key + * @param value + * @throws MessageWarnException + */ + @SuppressWarnings("all") + private void register(String key, List serviceMethods) { + //防止相同key在不同service的并发注册 + synchronized (this.lock.intern(key)) { + //1.添加cache + refreshServiceMethodCache(key, serviceMethods); + } + } + + private void refreshServiceMethodCache(String key, List serviceMethods) { + this.serviceMethodCache.computeIfAbsent(key, k -> new ArrayList<>()).addAll(serviceMethods); + } + + public Map> getServiceMethodCache() { + return this.serviceMethodCache; + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ImplicitRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ImplicitRegistry.java new file mode 100644 index 0000000000..432270fc28 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ImplicitRegistry.java @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + +/** + * @date 2020/7/28 + */ +public interface ImplicitRegistry { + + void register(Object implicitObject); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ServiceRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ServiceRegistry.java new file mode 100644 index 0000000000..f22fb8a8a8 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/ServiceRegistry.java @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + +/** + * @date 2020/7/14 + */ +public interface ServiceRegistry { + + void register(Object service); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringImplicitRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringImplicitRegistry.java new file mode 100644 index 0000000000..d375f895f2 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringImplicitRegistry.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + + +import com.webank.wedatasphere.linkis.message.annotation.Implicit; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; + +import java.lang.reflect.Method; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.REFLECTIONS; + +/** + * @date 2020/7/28 + */ +public class SpringImplicitRegistry extends AbstractImplicitRegistry { + + public SpringImplicitRegistry(AbstractMessageSchedulerContext context) { + super(context); + Set implicitMethods = REFLECTIONS.getMethodsAnnotatedWith(Implicit.class); + Set extends Class>> implicitClasses = implicitMethods.stream().map(Method::getDeclaringClass).collect(Collectors.toSet()); + //区分出 bean中的方法,和其他,其他使用反射创建方法对象 + for (Class> implicitClass : implicitClasses) { + Object bean = MessageUtils.getBean(implicitClass); + if (bean == null) { + try { + bean = implicitClass.newInstance(); + } catch (Throwable t) { + logger().warn(String.format("reflection failed to create object %s", implicitClass.getName())); + } + } + if (bean != null) this.register(bean); + } + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringServiceRegistry.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringServiceRegistry.java new file mode 100644 index 0000000000..693dd37d46 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/registry/SpringServiceRegistry.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.registry; + +import com.webank.wedatasphere.linkis.message.annotation.Receiver; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; + +import java.lang.reflect.Method; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.REFLECTIONS; + +/** + * @date 2020/7/15 + */ +public class SpringServiceRegistry extends AbstractServiceRegistry { + + public SpringServiceRegistry(AbstractMessageSchedulerContext context) { + super(context); + Set extends Class>> services = REFLECTIONS.getMethodsAnnotatedWith(Receiver.class).stream() + .map(Method::getDeclaringClass).collect(Collectors.toSet()); + services.stream().map(MessageUtils::getBean).filter(Objects::nonNull).forEach(this::register); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/AbstractMessageExecutor.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/AbstractMessageExecutor.java new file mode 100644 index 0000000000..c8a1c76eb4 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/AbstractMessageExecutor.java @@ -0,0 +1,158 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.message.builder.DefaultServiceMethodContext; +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext; +import com.webank.wedatasphere.linkis.message.exception.MessageWarnException; +import com.webank.wedatasphere.linkis.message.parser.ImplicitMethod; +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; +import java.util.stream.Collectors; + +/** + * @date 2020/7/21 + */ +public abstract class AbstractMessageExecutor extends JavaLog implements MessageExecutor { + + private Throwable t; + + private void methodErrorHandle(Throwable t) { + if (t.getCause() != null) { + this.t = t; + } else { + this.t = t; + logger().debug("unexpected error occur"); + } + } + + private List getMinOrderMethodWrapper(Map> methodWrappers) { + //获取所有key中order最小的 + List minOrderMethodWrapper = new ArrayList<>(); + methodWrappers.forEach((k, v) -> v.forEach(m -> { + if (MessageUtils.orderIsMin(m, v)) minOrderMethodWrapper.add(m); + })); + return minOrderMethodWrapper; + } + + private List getMinOrderMethodWrapper(List methodWrappers) { + //获取单个key中order最小的,一般是一个,尾链可能有多个 + return methodWrappers.stream().filter(m -> MessageUtils.orderIsMin(m, methodWrappers)).collect(Collectors.toList()); + } + + private boolean shouldBreak(Map> methodWrappers) { + return methodWrappers.values().stream().allMatch(List::isEmpty); + } + + private void cleanMethodContextThreadLocal(ServiceMethodContext methodContext) { + if (methodContext instanceof DefaultServiceMethodContext) { + ((DefaultServiceMethodContext) methodContext).removeJob(); + ((DefaultServiceMethodContext) methodContext).removeSkips(); + } + } + + private void setMethodContextThreadLocal(ServiceMethodContext methodContext, MessageJob job) { + if (methodContext instanceof DefaultServiceMethodContext && job instanceof Job) { + ((DefaultServiceMethodContext) methodContext).setJob((Job) job); + } + } + + @Override + public void run(MessageJob job) throws InterruptedException { + RequestProtocol requestProtocol = job.getRequestProtocol(); + ServiceMethodContext methodContext = job.getMethodContext(); + // TODO: 2020/7/22 data structure optimization of variable methodWrappers + Map> methodWrappers = job.getMethodExecuteWrappers(); + Integer count = methodWrappers.values().stream().map(List::size).reduce(0, Integer::sum); + LinkedBlockingDeque queue = new LinkedBlockingDeque<>(16); + CopyOnWriteArrayList> methodFutures = new CopyOnWriteArrayList<>(); + CountDownLatch countDownLatch = new CountDownLatch(count); + getMinOrderMethodWrapper(methodWrappers).forEach(queue::offer); + try { + while (!Thread.interrupted()) { + if (shouldBreak(methodWrappers)) { + break; + } + MethodExecuteWrapper methodWrapper = queue.poll(10, TimeUnit.MILLISECONDS); + if (methodWrapper == null) continue; + methodWrappers.get(methodWrapper.getChainName()).remove(methodWrapper); + Future> methodFuture = getExecutorService().submit(() -> { + Object result = null; + try { + // TODO: 2020/7/31 判断逻辑挪走 + if (!methodWrapper.shouldSkip) { + //放置job状态 + setMethodContextThreadLocal(methodContext, job); + Method method = methodWrapper.getMethod(); + Object service = methodWrapper.getService(); + info(String.format("message scheduler executor ===> service: %s,method: %s", service.getClass().getName(), method.getName())); + Object implicit; + // TODO: 2020/8/4 implicit 的结果应该复用下 + ImplicitMethod implicitMethod = methodWrapper.getImplicitMethod(); + if (implicitMethod != null) { + implicit = implicitMethod.getMethod().invoke(implicitMethod.getImplicitObject(), requestProtocol); + } else { + implicit = requestProtocol; + } + if (methodWrapper.isHasMethodContext()) { + if (methodWrapper.isMethodContextOnLeft()) { + result = method.invoke(service, methodContext, implicit); + } else { + result = method.invoke(service, implicit, methodContext); + } + } else { + result = method.invoke(service, implicit); + } + // TODO: 2020/8/5 执行完成后判断service是否有主动skip的逻辑 + } + } catch (Throwable t) { + logger().error(String.format("method %s call failed", methodWrapper.getAlias()), t); + methodWrappers.forEach((k, v) -> v.forEach(m -> m.setShouldSkip(true))); + methodErrorHandle(t); + } finally { + if (result != null) { + methodContext.setResult(result); + } + //末链并发的时候,小概率可能会有重复的method被offer到queue中,但是在poll前循环就break了,无影响 + getMinOrderMethodWrapper(methodWrappers.get(methodWrapper.getChainName())).forEach(queue::offer); + //移除state和skips的状态 + cleanMethodContextThreadLocal(methodContext); + countDownLatch.countDown(); + } + }); + methodFutures.add(methodFuture); + } + countDownLatch.await(); + } catch (InterruptedException ie) { + methodFutures.forEach(f -> f.cancel(true)); + throw ie; + } + if (this.t != null) { + throw new MessageWarnException(10000, "method call failed", t); + } + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageExecutor.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageExecutor.java new file mode 100644 index 0000000000..e86e596b28 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageExecutor.java @@ -0,0 +1,104 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.exception.MessageWarnException; +import com.webank.wedatasphere.linkis.message.tx.TransactionManager; +import com.webank.wedatasphere.linkis.protocol.engine.EngineState; +import com.webank.wedatasphere.linkis.scheduler.executer.*; +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEvent; + +import java.io.IOException; +import java.util.concurrent.ExecutorService; + +/** + * @date 2020/7/29 + */ +public class DefaultMessageExecutor extends AbstractMessageExecutor implements Executor { + + private final ExecutorService executorService; + + private final SchedulerEvent event; + + public DefaultMessageExecutor(SchedulerEvent event, ExecutorService executorService) { + this.event = event; + this.executorService = executorService; + } + + @Override + public ExecutorService getExecutorService() { + return this.executorService; + } + + @Override + public long getId() { + return 0; + } + + /** + * @param executeRequest + * @return + */ + @Override + public ExecuteResponse execute(ExecuteRequest executeRequest) { + if (event instanceof MessageJob) { + TransactionManager txManager = ((MessageJob) event).getContext().getTxManager(); + Object o = txManager.begin(); + try { + run((MessageJob) event); + txManager.commit(o); + return new SuccessExecuteResponse(); + } catch (InterruptedException ie) { + //handle InterruptedException + logger().error("message job execution interrupted", ie); + txManager.rollback(o); + return new ErrorExecuteResponse("message job execution interrupted", ie); + } catch (MessageWarnException mwe) { + //handle method call failed + logger().error("method call normal error return"); + txManager.rollback(o); + return new ErrorExecuteResponse("method call failed", mwe); + } catch (Throwable t) { + logger().debug("unexpected error occur", t); + txManager.rollback(o); + return new ErrorExecuteResponse("unexpected error", t); + } + } + MessageWarnException eventNotMatchError = new MessageWarnException(10000, "event is not instance of MessageJob"); + return new ErrorExecuteResponse("event is not instance of MessageJob", eventNotMatchError); + + } + + @Override + public EngineState state() { + return null; + } + + @Override + public ExecutorInfo getExecutorInfo() { + return new ExecutorInfo(0, null); + } + + + + + @Override + public void close() throws IOException { + + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageScheduler.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageScheduler.java new file mode 100644 index 0000000000..a07aa0426b --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/DefaultMessageScheduler.java @@ -0,0 +1,80 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.builder.MessageJobListener; +import com.webank.wedatasphere.linkis.scheduler.Scheduler; +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorManager; +import com.webank.wedatasphere.linkis.scheduler.queue.Group; +import com.webank.wedatasphere.linkis.scheduler.queue.GroupFactory; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelGroup; +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler; +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelSchedulerContextImpl; + +/** + * @date 2020/7/17 + */ +public class DefaultMessageScheduler implements MessageScheduler { + + // TODO: 2020/7/22 configuration + private static final int MAX_RUNING_JOB = Runtime.getRuntime().availableProcessors() * 2; + + private static final int MAX_PARALLELISM_USERS = Runtime.getRuntime().availableProcessors(); + + private static final int MAX_ASK_EXECUTOR_TIMES = 1000; + + private static final String GROUP_NAME = "message-scheduler"; + + private final Scheduler linkisScheduler; + + { + MessageExecutorExecutionManager messageExecutorManager = new MessageExecutorExecutionManager(); + linkisScheduler = new ParallelScheduler( + new ParallelSchedulerContextImpl(MAX_PARALLELISM_USERS) { + @Override + public ExecutorManager getOrCreateExecutorManager() { + return messageExecutorManager; + } + }); + linkisScheduler.init(); + GroupFactory groupFactory = linkisScheduler.getSchedulerContext().getOrCreateGroupFactory(); + //one consumer group is enough + Group group = groupFactory.getOrCreateGroup(GROUP_NAME); + if (group instanceof ParallelGroup) { + ParallelGroup parallelGroup = (ParallelGroup) group; + if (parallelGroup.getMaxRunningJobs() == 0) { + parallelGroup.setMaxRunningJobs(MAX_RUNING_JOB); + } + if (parallelGroup.getMaxAskExecutorTimes() == 0) { + parallelGroup.setMaxAskExecutorTimes(MAX_ASK_EXECUTOR_TIMES); + } + } + } + + @Override + public void submit(MessageJob messageJob) { + if (messageJob instanceof Job) { + ((Job) messageJob).setId(GROUP_NAME); + ((Job) messageJob).setJobListener(new MessageJobListener()); + linkisScheduler.submit((Job) messageJob); + } + } + + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutor.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutor.java new file mode 100644 index 0000000000..0dc353ac67 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutor.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.message.builder.MessageJob; + +import java.util.concurrent.ExecutorService; + +/** + * @date 2020/7/20 + */ +public interface MessageExecutor { + + void run(MessageJob job) throws InterruptedException; + + ExecutorService getExecutorService(); + + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutorExecutionManager.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutorExecutionManager.java new file mode 100644 index 0000000000..b8dcb28bae --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageExecutorExecutionManager.java @@ -0,0 +1,77 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.common.utils.Utils; +import com.webank.wedatasphere.linkis.scheduler.executer.Executor; +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorManager; +import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener; +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEvent; +import scala.Option; +import scala.Some; +import scala.concurrent.duration.Duration; + +import java.util.concurrent.ExecutorService; + +/** + * @date 2020/7/17 + */ +public class MessageExecutorExecutionManager extends ExecutorManager { + + private final ExecutorService executorService = Utils.newCachedThreadPool( + Runtime.getRuntime().availableProcessors() * 2, "message-executor_", false); + + @Override + public void setExecutorListener(ExecutorListener executorListener) { + + } + + @Override + public Executor createExecutor(SchedulerEvent event) { + return new DefaultMessageExecutor(event, executorService); + } + + @Override + public Option askExecutor(SchedulerEvent event) { + return new Some<>(createExecutor(event)); + } + + @Override + public Option askExecutor(SchedulerEvent event, Duration wait) { + return askExecutor(event); + } + + @Override + public Option getById(long id) { + return new Some<>(null); + } + + @Override + public Executor[] getByGroup(String groupName) { + return new Executor[0]; + } + + @Override + public void delete(Executor executor) { + + } + + @Override + public void shutdown() { + + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageScheduler.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageScheduler.java new file mode 100644 index 0000000000..1c0701b7d0 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MessageScheduler.java @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.message.builder.MessageJob; + +/** + * @date 2020/7/14 + */ +public interface MessageScheduler { + + void submit(MessageJob messageJob); + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MethodExecuteWrapper.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MethodExecuteWrapper.java new file mode 100644 index 0000000000..736a1b8e4f --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/scheduler/MethodExecuteWrapper.java @@ -0,0 +1,78 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.scheduler; + +import com.webank.wedatasphere.linkis.message.parser.ImplicitMethod; +import com.webank.wedatasphere.linkis.message.parser.ServiceMethod; + +import java.lang.reflect.Method; + +/** + * @date 2020/7/21 + */ +public class MethodExecuteWrapper { + + public MethodExecuteWrapper(ServiceMethod serviceMethod) { + this.serviceMethod = serviceMethod; + } + + private final ServiceMethod serviceMethod; + + public boolean shouldSkip; + + public boolean isShouldSkip() { + return shouldSkip; + } + + public void setShouldSkip(boolean shouldSkip) { + this.shouldSkip = shouldSkip; + } + + public Method getMethod() { + return this.serviceMethod.getMethod(); + } + + public Object getService() { + return this.serviceMethod.getService(); + } + + + public String getAlias() { + return this.serviceMethod.getAlias(); + } + + public int getOrder() { + return this.serviceMethod.getOrder(); + } + + public String getChainName() { + return this.serviceMethod.getChainName(); + } + + public boolean isHasMethodContext() { + return this.serviceMethod.isHasMethodContext(); + } + + public ImplicitMethod getImplicitMethod() { + return this.serviceMethod.getImplicitMethod(); + } + + public boolean isMethodContextOnLeft() { + return this.serviceMethod.isMethodContextOnLeft(); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/SpringTransactionManager.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/SpringTransactionManager.java new file mode 100644 index 0000000000..f203d7eedb --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/SpringTransactionManager.java @@ -0,0 +1,58 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.tx; + +import com.webank.wedatasphere.linkis.common.utils.JavaLog; +import com.webank.wedatasphere.linkis.message.utils.MessageUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.interceptor.DefaultTransactionAttribute; + +/** + * @date 2020/7/23 + */ +public class SpringTransactionManager extends JavaLog implements TransactionManager { + + private final PlatformTransactionManager platformTransactionManager; + + public SpringTransactionManager() { + platformTransactionManager = MessageUtils.getBean(PlatformTransactionManager.class); + } + + + @Override + public Object begin() { + if (platformTransactionManager != null) { + return platformTransactionManager.getTransaction(new DefaultTransactionAttribute()); + } + return null; + } + + @Override + public void commit(Object o) { + if (o instanceof TransactionStatus && platformTransactionManager != null) { + platformTransactionManager.commit((TransactionStatus) o); + } + } + + @Override + public void rollback(Object o) { + if (o instanceof TransactionStatus && platformTransactionManager != null) { + platformTransactionManager.rollback((TransactionStatus) o); + } + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/TransactionManager.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/TransactionManager.java new file mode 100644 index 0000000000..b0b4af36ec --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/tx/TransactionManager.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.tx; + +/** + * @date 2020/7/23 + */ +public interface TransactionManager { + + default Object begin() { + return null; + } + + default void commit(Object o) { + } + + default void rollback(Object o) { + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/utils/MessageUtils.java b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/utils/MessageUtils.java new file mode 100644 index 0000000000..55eaa98c30 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/java/com/webank/wedatasphere/linkis/message/utils/MessageUtils.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message.utils; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import com.webank.wedatasphere.linkis.message.parser.ServiceMethod; +import com.webank.wedatasphere.linkis.message.scheduler.MethodExecuteWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @date 2020/7/28 + */ +public class MessageUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(MessageUtils.class); + + public static T getBean(Class tClass) { + T t = null; + ApplicationContext applicationContext = DataWorkCloudApplication.getApplicationContext(); + if (applicationContext != null) { + try { + t = applicationContext.getBean(tClass); + } catch (NoSuchBeanDefinitionException e) { + LOGGER.warn(String.format("can not get bean from spring ioc:%s", tClass.getName())); + } + } + return t; + } + + public static boolean isAssignableFrom(String supperClassName, String className) { + try { + return Class.forName(supperClassName).isAssignableFrom(Class.forName(className)); + } catch (ClassNotFoundException e) { + LOGGER.error("class not found", e); + return false; + } + } + + public static boolean orderIsMin(MethodExecuteWrapper methodExecuteWrapper, List methodExecuteWrappers) { + for (MethodExecuteWrapper tmp : methodExecuteWrappers) { + if (tmp.getOrder() < methodExecuteWrapper.getOrder()) { + return false; + } + } + return true; + } + + public static boolean orderIsLast(int order, List serviceMethods) { + // TODO: 2020/8/5 方法判断修改为重复的order 支持头部 + if (order == 2147483647) return true; + for (ServiceMethod serviceMethod : serviceMethods) { + if (serviceMethod.getOrder() > order) { + return false; + } + } + return false; + } + + public static Integer repeatOrder(List serviceMethods) { + Map tmp = new HashMap<>(); + for (ServiceMethod serviceMethod : serviceMethods) { + int order = serviceMethod.getOrder(); + if (tmp.get(order) == null) { + tmp.put(order, order); + } else { + return order; + } + } + return null; + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/resources/META-INF/spring.factories b/linkis-commons/linkis-message-scheduler/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..7dcbee3eca --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.webank.wedatasphere.linkis.rpc.MessageRPCSpringConfiguration diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageConverter.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageConverter.scala new file mode 100644 index 0000000000..06ba68283f --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageConverter.scala @@ -0,0 +1,82 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import java.lang.reflect.Modifier +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.message.annotation.Method +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.{REFLECTIONS, _} +import com.webank.wedatasphere.linkis.message.exception.MessageErrorException +import com.webank.wedatasphere.linkis.protocol.message.RequestMethod +import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException +import com.webank.wedatasphere.linkis.server.{BDPJettyServerHelper, Message} + +import scala.collection.JavaConversions._ + +/** + * @date 2020/8/6 + * + */ +class MessageConverter { + + private val protocolNameCache = new util.HashMap[String, String] + + REFLECTIONS.getTypesAnnotatedWith(classOf[Method]).foreach { t => + val method = t.getAnnotation(classOf[Method]) + protocolNameCache.put(method.value(), t.getName) + } + + REFLECTIONS.getSubTypesOf(classOf[RequestMethod]).filter(!_.isInterface).filter(c => !Modifier.isAbstract(c.getModifiers)).foreach { t => + val protocol = try { + t.newInstance() + } catch { + case e: Throwable => + throw new RuntimeException(s"Failed to create new instance of class ${t.getName}", e) + } + val method = t.getMethod("method").invoke(protocol).toString + protocolNameCache.put(method, t.getName) + } + + @throws[MessageErrorException] + def convert(message: Message): util.Map[String, Object] = { + val methodUrl = message.getMethod + val protocolStr = protocolNameCache.get(methodUrl) + if (protocolStr == null) throw new MessageErrorException(10000, s"no suitable protocol was found for method:${methodUrl}") + val returnType = new util.HashMap[String, Object]() + val data = message.getData + returnType += REQUEST_KEY -> data.remove(REQUEST_KEY) + val protocol = Utils.tryThrow(Class.forName(protocolStr)) { + case _: ClassNotFoundException => + new DWCURIException(10003, s"The corresponding anti-sequence class $protocolStr was not found.(找不到对应的反序列类$protocolStr.)") + case t: ExceptionInInitializerError => + val exception = new DWCURIException(10004, s"The corresponding anti-sequence class ${protocolStr} failed to initialize.(对应的反序列类${protocolStr}初始化失败.)") + exception.initCause(t) + exception + case t: Throwable => t + } + returnType += "_request_protocol_" -> BDPJettyServerHelper.gson.fromJson(BDPJettyServerHelper.gson.toJson(data), protocol) + //设置一个restful请求的客户端 + // TODO: req中获取到ip和地址 + data.clear() + data.put("name", "") + data.put("instance", "") + returnType + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCConsumer.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCConsumer.scala new file mode 100644 index 0000000000..5398d03528 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCConsumer.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import java.util + +import com.webank.wedatasphere.linkis.common.exception.ExceptionManager +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException +import com.webank.wedatasphere.linkis.rpc.serializer.ProtostuffSerializeUtil +import com.webank.wedatasphere.linkis.rpc.transform.RPCProduct.{CLASS_VALUE, OBJECT_VALUE} +import com.webank.wedatasphere.linkis.server.{EXCEPTION_MSG, JMap, Message} + +import scala.runtime.BoxedUnit + +/** + * @date 2020/8/6 + * + */ + +class MessageRPCConsumer { + + private val messageConverter: MessageConverter = new MessageConverter + + def overrideToObject(message: Message): Any = { + message.getStatus match { + case 0 => + val data = message.getData + if (data.isEmpty) return BoxedUnit.UNIT + if (isRPCRequest(data)) { + val objectStr = data.get(OBJECT_VALUE).toString + val objectClass = data.get(CLASS_VALUE).toString + val clazz = Utils.tryThrow(Class.forName(objectClass)) { + case _: ClassNotFoundException => + new DWCURIException(10003, s"The corresponding anti-sequence class $objectClass was not found.(找不到对应的反序列类$objectClass.)") + case t: ExceptionInInitializerError => + val exception = new DWCURIException(10004, s"The corresponding anti-sequence class ${objectClass} failed to initialize.(对应的反序列类${objectClass}初始化失败.)") + exception.initCause(t) + exception + case t: Throwable => t + } +// if (null != data.get(IS_REQUEST_PROTOCOL_CLASS) && data.get(IS_REQUEST_PROTOCOL_CLASS).toString.toBoolean) { + ProtostuffSerializeUtil.deserialize(objectStr, clazz) +// } else if (data.get(IS_SCALA_CLASS).toString.toBoolean) { +// val realClass = getSerializableScalaClass(clazz) +// Serialization.read(objectStr)(formats, ManifestFactory.classType(realClass)) +// } else { +// BDPJettyServerHelper.gson.fromJson(objectStr, clazz) +// } + } else { + messageConverter.convert(message) + } + case 4 => + val errorMsg = message.getData.get(EXCEPTION_MSG).asInstanceOf[JMap[String, Object]] + ExceptionManager.generateException(errorMsg) + case _ => + val errorMsg = message.getData.get(EXCEPTION_MSG) + if (errorMsg == null) throw new DWCURIException(10005, message.getMessage) + val realError = ExceptionManager.generateException(errorMsg.asInstanceOf[JMap[String, Object]]) + throw realError; + } + } + + def isRPCRequest(data: util.HashMap[String, Object]): Boolean = { + data.containsKey(OBJECT_VALUE) + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCReceiveRestful.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCReceiveRestful.scala new file mode 100644 index 0000000000..0bebc3f4fe --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCReceiveRestful.scala @@ -0,0 +1,124 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf._ +import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException +import com.webank.wedatasphere.linkis.rpc.transform.{RPCConsumer, RPCProduct} +import com.webank.wedatasphere.linkis.server.{Message, catchIt} +import javax.annotation.PostConstruct +import javax.servlet.http.HttpServletRequest +import javax.ws.rs.core.MediaType +import javax.ws.rs.{Consumes, POST, Path, Produces} +import org.apache.commons.lang.StringUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.annotation.{Import, Primary} +import org.springframework.stereotype.Component +import org.springframework.web.context.request.{RequestContextHolder, ServletRequestAttributes} + +import scala.concurrent.duration.Duration +import scala.runtime.BoxedUnit + +/** + * @date 2020/8/3 + * + */ +@Component +@Path("/rpc") +@Produces(Array(MediaType.APPLICATION_JSON)) +@Consumes(Array(MediaType.APPLICATION_JSON)) +@Primary +@Import(Array(classOf[MessageRPCConsumer])) +class MessageRPCReceiveRestful extends RPCReceiveRestful { + + @Autowired(required = false) + private var receiverChoosers: Array[ReceiverChooser] = Array.empty + @Autowired(required = false) + private var receiverSenderBuilders: Array[ReceiverSenderBuilder] = Array.empty + @Autowired + private var messageRPCConsumer: MessageRPCConsumer = _ + + private def getFirst[K, T](buildArray: Array[K], buildObj: K => Option[T]): Option[T] = { + var obj: Option[T] = None + for (builder <- buildArray if obj.isEmpty) obj = buildObj(builder) + obj + } + + //广播功能去掉,messageScheduler可以提供这种功能,目前只有entrance有此类方法,后续调整 + + private implicit def getReceiver(event: RPCMessageEvent): Option[Receiver] = getFirst[ReceiverChooser, Receiver](receiverChoosers, _.chooseReceiver(event)) + + private implicit def getSender(event: RPCMessageEvent): Sender = getFirst[ReceiverSenderBuilder, Sender](receiverSenderBuilders, _.build(event)).get + + private implicit def getMessageRPCConsumer(rpcConsumer: RPCConsumer): MessageRPCConsumer = messageRPCConsumer + + override def registerReceiverChooser(receiverChooser: ReceiverChooser): Unit = { + info("register a new ReceiverChooser " + receiverChooser) + receiverChoosers = receiverChooser +: receiverChoosers + } + + @PostConstruct + def init(): Unit = { + if (!receiverChoosers.exists(_.isInstanceOf[CommonReceiverChooser])) + receiverChoosers = receiverChoosers :+ new CommonReceiverChooser + info("init all receiverChoosers in spring beans, list => " + receiverChoosers.toList) + if (!receiverSenderBuilders.exists(_.isInstanceOf[CommonReceiverSenderBuilder])) + receiverSenderBuilders = receiverSenderBuilders :+ new CommonReceiverSenderBuilder + receiverSenderBuilders = receiverSenderBuilders.sortBy(_.order) + info("init all receiverSenderBuilders in spring beans, list => " + receiverSenderBuilders.toList) + } + + private implicit def toMessage(obj: Any): Message = obj match { + case Unit | () => + RPCProduct.getRPCProduct.ok() + case _: BoxedUnit => RPCProduct.getRPCProduct.ok() + case _ => + RPCProduct.getRPCProduct.toMessage(obj) + } + + private implicit def getReq: HttpServletRequest = { + RequestContextHolder.getRequestAttributes.asInstanceOf[ServletRequestAttributes].getRequest + } + + @Path("receive") + @POST + override def receive(message: Message): Message = invokeReceiver(message, _.receive(_, _)) + + private def invokeReceiver(message: Message, opEvent: (Receiver, Any, Sender) => Message)(implicit req: HttpServletRequest): Message = catchIt { + message.getData.put(REQUEST_KEY, req) + val obj = RPCConsumer.getRPCConsumer.overrideToObject(message) + val serviceInstance = BaseRPCSender.getInstanceInfo(message.getData) + val event = RPCMessageEvent(obj, serviceInstance) + event.map(opEvent(_, obj, event)).getOrElse(RPCProduct.getRPCProduct.notFound()) + } + + @Path("receiveAndReply") + @POST + override def receiveAndReply(message: Message): Message = invokeReceiver(message, _.receiveAndReply(_, _)) + + @Path("replyInMills") + @POST + override def receiveAndReplyInMills(message: Message): Message = catchIt { + val duration = message.getData.get("duration") + if (duration == null || StringUtils.isEmpty(duration.toString)) throw new DWCURIException(10002, "The timeout period is not set!(超时时间未设置!)") + val timeout = Duration(duration.toString.toLong, TimeUnit.MILLISECONDS) + invokeReceiver(message, _.receiveAndReply(_, timeout, _)) + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCSpringConfiguration.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCSpringConfiguration.scala new file mode 100644 index 0000000000..9c21b534fd --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageRPCSpringConfiguration.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import com.webank.wedatasphere.linkis.message.context.{MessageSchedulerContext, SpringMessageSchedulerContext} +import com.webank.wedatasphere.linkis.message.publisher.{AbstractMessagePublisher, DefaultMessagePublisher, MessagePublisher} +import org.springframework.context.annotation.Bean + +/** + * @date 2020/8/4 + * + */ +class MessageRPCSpringConfiguration { + + @Bean + def getPublisher: AbstractMessagePublisher = { + new DefaultMessagePublisher() + } + + @Bean + def getMessageSchedulerContext(messagePublisher: AbstractMessagePublisher): MessageSchedulerContext = { + val context = new SpringMessageSchedulerContext + messagePublisher.setContext(context) + context.setPublisher(messagePublisher) + context + } + + @Bean + def getReceiverChooser(messagePublisher: MessagePublisher): ReceiverChooser = { + new MessageReceiverChooser(Option(new MessageReceiver(messagePublisher))) + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiver.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiver.scala new file mode 100644 index 0000000000..2cf60d0db0 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiver.scala @@ -0,0 +1,84 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import java.util.concurrent.{TimeUnit, TimeoutException} + +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.message.builder.{DefaultServiceMethodContext, MessageJobTimeoutPolicy, ServiceMethodContext} +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf.{SENDER_KEY, _} +import com.webank.wedatasphere.linkis.message.publisher.MessagePublisher +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.server.security.SecurityFilter +import javax.servlet.http.HttpServletRequest + +import scala.concurrent.duration.Duration +import scala.language.implicitConversions + +/** + * @date 2020/8/3 + * + */ +class MessageReceiver(mesagePublisher: MessagePublisher) extends Receiver { + + private val syncMaxTimeout: Duration = Duration(CommonVars("wds.linkis.ms.rpc.sync.timeout", 60 * 1000 * 5L).getValue, TimeUnit.MILLISECONDS) + + override def receive(message: Any, sender: Sender): Unit = { + mesagePublisher.publish(message, (message, syncMaxTimeout, sender)) + } + + override def receiveAndReply(message: Any, sender: Sender): Any = { + receiveAndReply(message, syncMaxTimeout, sender) + } + + override def receiveAndReply(message: Any, duration: Duration, sender: Sender): Any = { + val job = mesagePublisher.publish(message, (message, duration, sender)) + Utils.tryCatch(job.get(duration._1, duration._2)) { + case t: TimeoutException => + job.getMethodContext.getAttributeOrDefault(TIMEOUT_POLICY, MessageJobTimeoutPolicy.INTERRUPT) match { + case MessageJobTimeoutPolicy.CANCEL => job.cancel(false); throw t + case MessageJobTimeoutPolicy.INTERRUPT => job.cancel(true); throw t + case MessageJobTimeoutPolicy.PARTIAL => job.getPartial + } + case i: InterruptedException => job.cancel(true); throw i + case t: Throwable => job.cancel(true); throw t + } + } + + implicit def createMessageMethodScheduler(tunple: (Any, Duration, Sender)): ServiceMethodContext = { + val methodContext = new DefaultServiceMethodContext + methodContext.putAttribute(SENDER_KEY, tunple._3) + methodContext.putAttribute(DURATION_KEY, tunple._2) + tunple._1 match { + case m: java.util.Map[String, Object] => { + val req = m.get(REQUEST_KEY).asInstanceOf[HttpServletRequest] + methodContext.putAttribute(REQUEST_KEY, req) + methodContext.putAttribute(USER_KEY, SecurityFilter.getLoginUser(req)) + } + case _ => + } + methodContext + } + + implicit def any2RequestProtocol(message: Any): RequestProtocol = message match { + case p: RequestProtocol => p + case m: java.util.Map[String, Object] => m.get("_request_protocol_").asInstanceOf[RequestProtocol] + } + + +} diff --git a/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiverChooser.scala b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiverChooser.scala new file mode 100644 index 0000000000..525ea60a0c --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/main/scala/com/webank/wedatasphere/linkis/rpc/MessageReceiverChooser.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc + +import java.util + +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + +/** + * @date 2020/8/3 + * + */ + +class MessageReceiverChooser(receiver: Option[Receiver]) extends ReceiverChooser { + + override def chooseReceiver(event: RPCMessageEvent): Option[Receiver] = event.message match { + case _: util.Map[String, Object] => receiver + case _: RequestProtocol => receiver + case _ => None + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/DefaultRequestProtocol.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/DefaultRequestProtocol.java new file mode 100644 index 0000000000..1cd9175c5e --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/DefaultRequestProtocol.java @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + + +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +/** + * @date 2020/7/14 + */ +public class DefaultRequestProtocol implements RequestProtocol { +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterface.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterface.java new file mode 100644 index 0000000000..242aea73b3 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterface.java @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + + +/** + * @date 2020/7/22 + */ +public interface ImplicitInterface { +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterfaceImpl.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterfaceImpl.java new file mode 100644 index 0000000000..22cc4a6e50 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitInterfaceImpl.java @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + +/** + * @date 2020/7/30 + */ +public class ImplicitInterfaceImpl implements ImplicitInterface { +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitObject.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitObject.java new file mode 100644 index 0000000000..d3e9b00f58 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/ImplicitObject.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + +import com.webank.wedatasphere.linkis.message.annotation.Implicit; + +/** + * @date 2020/7/29 + */ +public class ImplicitObject { + + @Implicit + public ImplicitInterfaceImpl implicitMethod02(DefaultRequestProtocol requestProtocol) { + return null; + } +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/SchedulerMessageTest.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/SchedulerMessageTest.java new file mode 100644 index 0000000000..5895d30949 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/SchedulerMessageTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + +import com.webank.wedatasphere.linkis.message.annotation.Receiver; +import com.webank.wedatasphere.linkis.message.builder.MessageJob; +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf; +import com.webank.wedatasphere.linkis.message.context.AbstractMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.context.DefaultMessageSchedulerContext; +import com.webank.wedatasphere.linkis.message.parser.ImplicitMethod; +import com.webank.wedatasphere.linkis.message.parser.ServiceMethod; +import com.webank.wedatasphere.linkis.message.registry.AbstractImplicitRegistry; +import com.webank.wedatasphere.linkis.message.registry.AbstractServiceRegistry; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; +import org.reflections.scanners.MethodAnnotationsScanner; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import java.util.stream.Collectors; + +/** + * @date 2020/7/14 + */ +public class SchedulerMessageTest { + + private AbstractMessageSchedulerContext context; + + Reflections reflections = new Reflections(MessageSchedulerConf.SERVICE_SCAN_PACKAGE, new MethodAnnotationsScanner()); + + @Before + public void before() { + + context = new DefaultMessageSchedulerContext(); + } + + + @Test + public void servieParserTest() throws InterruptedException { + Map> parse = context.getservieParser().parse(new TestService()); + System.out.println(parse.size()); + } + + @Test + public void registryTest() throws InterruptedException { + TestService testService = new TestService(); + context.getServiceRegistry().register(testService); + context.getImplicitRegistry().register(testService); + System.out.println("serviceRegistry"); + } + + @Test + public void implicitParserTest() throws InterruptedException { + Map> parse = context.getImplicitParser().parse(new TestService()); + System.out.println(parse.size()); + } + + @Test + public void springRegisterTest() { + Set methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(Receiver.class); + Set extends Class>> collect = methodsAnnotatedWith.stream().map(Method::getDeclaringClass).collect(Collectors.toSet()); + System.out.println(collect.size()); + } + + @Test + public void test() { + System.out.println(RequestProtocol.class.isAssignableFrom(RequestProtocol.class)); + } + + @Test + public void publishTest() throws InterruptedException, ExecutionException, TimeoutException { + TestService testService = new TestService(); + TestService2 testService2 = new TestService2(); + AbstractImplicitRegistry implicitRegistry = this.context.getImplicitRegistry(); + implicitRegistry.register(testService); + implicitRegistry.register(testService2); + implicitRegistry.register(new ImplicitObject()); + AbstractServiceRegistry serviceRegistry = this.context.getServiceRegistry(); + serviceRegistry.register(testService); + serviceRegistry.register(testService2); + long start = System.currentTimeMillis(); + MessageJob publish = context.getPublisher().publish(new DefaultRequestProtocol()); + Object o = publish.get(); + System.out.println(o); + + System.out.println(System.currentTimeMillis() - start); + } + +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService.java new file mode 100644 index 0000000000..3c0f4eb442 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + +import com.webank.wedatasphere.linkis.message.annotation.*; +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext; +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + +import java.util.ArrayList; +import java.util.List; + +/** + * @date 2020/7/14 + */ +public class TestService { + @Receiver + @Order(1) + public void method01(ImplicitInterface protocol) throws InterruptedException { + Thread.sleep(5000); + System.out.println("TestService1.method01"); + } + + @Receiver + public void method02(ServiceMethodContext smc, ImplicitInterface protocol) throws InterruptedException { + Thread.sleep(2000); + System.out.println("TestService1.method02"); + } + + @Receiver + @Chain("fgf") + public void method03(ServiceMethodContext smc, ImplicitInterface protocol) throws InterruptedException { + Thread.sleep(3000); + System.out.println("TestService1.method03"); + } + + @Receiver + public List method04( ServiceMethodContext smc, @NotImplicit DefaultRequestProtocol protocol) throws InterruptedException { + Thread.sleep(2000); + System.out.println("TestService1.method04"); + return new ArrayList<>(); + } + + @Implicit + public ImplicitInterfaceImpl implicitMethod02(DefaultRequestProtocol requestProtocol) { + return null; + } + + /** + * 测试 转换方法的优先级 + * + * @param protocol + * @return + */ + @Implicit + public ImplicitInterfaceImpl implicitMetho01(RequestProtocol protocol) { + return null; + } + + +} diff --git a/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService2.java b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService2.java new file mode 100644 index 0000000000..be22ea2787 --- /dev/null +++ b/linkis-commons/linkis-message-scheduler/src/test/java/com/webank/wedatasphere/linkis/message/TestService2.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.message; + +/** + * @date 2020/7/29 + */ +public class TestService2 { + +/* @Receiver + public void method01(@Implicit SubRequestProtocol protocol) throws InterruptedException { + System.out.println("TestService2.method01"); + }*/ + + +} diff --git a/linkis-commons/linkis-module/pom.xml b/linkis-commons/linkis-module/pom.xml new file mode 100644 index 0000000000..c28e15487e --- /dev/null +++ b/linkis-commons/linkis-module/pom.xml @@ -0,0 +1,514 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-module + + + + com.webank.wedatasphere.linkis + linkis-common + + + + org.springframework + spring-core + ${spring.version} + + + + org.springframework.boot + spring-boot + ${spring.boot.version} + + + org.apache.logging.log4j + log4j-api + + + org.apache.logging.log4j + log4j-core + + + spring-core + org.springframework + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + ${spring.eureka.version} + + + jsr311-api + javax.ws.rs + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-boot-starter-aop + org.springframework.boot + + + spring-cloud-starter + org.springframework.cloud + + + spring-cloud-commons + org.springframework.cloud + + + spring-cloud-context + org.springframework.cloud + + + spring-boot-starter + org.springframework.boot + + + spring-boot-starter-cache + org.springframework.boot + + + jackson-core + com.fasterxml.jackson.core + + + jackson-databind + com.fasterxml.jackson.core + + + + + + org.springframework.boot + spring-boot-starter-cache + ${spring.boot.version} + + + spring-core + org.springframework + + + + + + org.springframework.boot + spring-boot-starter-jetty + ${spring.boot.version} + + + asm + org.ow2.asm + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + hibernate-validator + org.hibernate.validator + + + spring-core + org.springframework + + + ${spring.boot.version} + + + + org.springframework.boot + spring-boot-starter + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-logging + + + spring-core + org.springframework + + + + + org.springframework.boot + spring-boot-starter-log4j2 + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-actuator + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-logging + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.boot + spring-boot-starter-logging + + + spring-web + org.springframework + + + spring-boot-starter + org.springframework.boot + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-cloud-config-client + org.springframework.cloud + + + spring-cloud-starter + org.springframework.cloud + + + ${spring.cloud.version} + + + + spring-cloud-config-client + + + spring-cloud-commons + org.springframework.cloud + + + spring-cloud-context + org.springframework.cloud + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-web + org.springframework + + + org.springframework.cloud + ${spring.cloud.version} + + + spring-cloud-starter + + + spring-cloud-commons + org.springframework.cloud + + + spring-cloud-context + org.springframework.cloud + + + spring-boot-starter + org.springframework.boot + + + org.springframework.cloud + ${spring.cloud.version} + + + + org.springframework.cloud + spring-cloud-context + ${spring.cloud.version} + + + spring-security-crypto + org.springframework.security + + + + + + org.springframework.cloud + spring-cloud-commons + ${spring.cloud.version} + + + spring-security-crypto + org.springframework.security + + + + + + org.springframework.security + spring-security-crypto + ${spring.security.cryto.version} + + + + + org.springframework.boot + spring-boot-starter-aop + + + org.springframework.boot + spring-boot-starter-logging + + + spring-core + org.springframework + + + ${spring.boot.version} + + + + mysql + mysql-connector-java + 5.1.49 + + + + org.glassfish.jersey.bundles + jaxrs-ri + 2.21 + + + cglib + cglib + 2.2.2 + + + commons-dbcp + commons-dbcp + 1.4 + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + + + org.eclipse.jetty.websocket + websocket-server + ${jetty.version} + + + + org.glassfish.jersey.ext + jersey-spring3 + ${jersey.servlet.version} + + + org.springframework + spring + + + org.springframework + spring-core + + + org.springframework + spring-web + + + org.springframework + spring-beans + + + org.springframework + spring-context + + + + + + + com.sun.jersey + jersey-server + 1.19.1 + + + jsr311-api + javax.ws.rs + + + + + com.sun.jersey + jersey-servlet + 1.19.1 + + + org.glassfish.jersey.containers + jersey-container-servlet + ${jersey.servlet.version} + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey.servlet.version} + + + javax.ws.rs-api + javax.ws.rs + + + + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + + + jackson-core + com.fasterxml.jackson.core + + + jackson-databind + com.fasterxml.jackson.core + + + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey.version} + + + org.glassfish.jersey.ext + jersey-entity-filtering + ${jersey.version} + + + com.sun.jersey + jersey-json + + + jsr311-api + javax.ws.rs + + + jersey-core + com.sun.jersey + + + 1.19 + + + + com.fasterxml.jackson.core + jackson-databind + ${fasterxml.jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${fasterxml.jackson.version} + + + + org.reflections + reflections + ${reflections.version} + + + + com.google.code.gson + gson + ${gson.version} + + + io.netty + netty-all + ${netty.version} + + + org.json4s + json4s-jackson_${scala.binary.version} + ${json4s.version} + + + org.scala-lang + scala-library + + + jackson-databind + com.fasterxml.jackson.core + + + + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + diff --git a/core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java b/linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java similarity index 95% rename from core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java rename to linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java index 9aac150916..8500ea5ac3 100644 --- a/core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java +++ b/linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/DataWorkCloudApplication.java @@ -32,6 +32,7 @@ import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.webapp.WebAppContext; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.event.ApplicationPreparedEvent; @@ -102,6 +103,9 @@ public void onApplicationEvent(RefreshScopeRefreshedEvent applicationEvent) { application.addListeners((ApplicationListener>) Class.forName(listener).newInstance()); } } + if("true".equals(ServerConfiguration.IS_GATEWAY().getValue())){ + application.setWebApplicationType(WebApplicationType.REACTIVE); + } applicationContext = application.run(args); } @@ -138,9 +142,9 @@ private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrN private static void initDWCApplication() { serviceInstance = new ServiceInstance(); serviceInstance.setApplicationName(applicationContext.getEnvironment().getProperty("spring.application.name")); - serviceInstance.setInstance(Utils.getLocalHostname() + ":" + applicationContext.getEnvironment().getProperty("server.port")); + serviceInstance.setInstance(Utils.getComputerName() + ":" + applicationContext.getEnvironment().getProperty("server.port")); DWCException.setApplicationName(serviceInstance.getApplicationName()); - DWCException.setHostname(Utils.getLocalHostname()); + DWCException.setHostname(Utils.getComputerName()); DWCException.setHostPort(Integer.parseInt(applicationContext.getEnvironment().getProperty("server.port"))); } @@ -173,7 +177,6 @@ protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { public WebServerFactoryCustomizer jettyFactoryCustomizer() { return new WebServerFactoryCustomizer() { public void customize(JettyServletWebServerFactory jettyServletWebServerFactory) { - jettyServletWebServerFactory.getJsp().setRegistered(false); jettyServletWebServerFactory.addServerCustomizers(new JettyServerCustomizer() { public void customize(Server server) { Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class); diff --git a/core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java b/linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java similarity index 95% rename from core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java rename to linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java index b396486608..0a8468c1e5 100644 --- a/core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java +++ b/linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/server/restful/RestfulApplication.java @@ -40,7 +40,7 @@ public RestfulApplication() throws ClassNotFoundException { if(StringUtils.isNotBlank(registerClasses)) { for(String clazz : registerClasses.split(",")) { logger.info("register " + clazz); - register(Class.forName(clazz)); + register(Class.forName(clazz, true, Thread.currentThread().getContextClassLoader())); } } String packages = ServerConfiguration.BDP_SERVER_RESTFUL_SCAN_PACKAGES().acquireNew(); diff --git a/core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/server/utils/AopTargetUtils.java b/linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/server/utils/AopTargetUtils.java similarity index 100% rename from core/cloudModule/src/main/java/com/webank/wedatasphere/linkis/server/utils/AopTargetUtils.java rename to linkis-commons/linkis-module/src/main/java/com/webank/wedatasphere/linkis/server/utils/AopTargetUtils.java diff --git a/core/cloudModule/src/main/resources/mybatis-config.xml b/linkis-commons/linkis-module/src/main/resources/mybatis-config.xml similarity index 100% rename from core/cloudModule/src/main/resources/mybatis-config.xml rename to linkis-commons/linkis-module/src/main/resources/mybatis-config.xml diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala index a83fa66ec8..f809076b30 100644 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/BDPJettyServerHelper.scala @@ -23,13 +23,13 @@ import java.text.SimpleDateFormat import java.util.EnumSet import com.fasterxml.jackson.databind.ObjectMapper -import javax.servlet.{DispatcherType, Filter} import com.google.gson._ import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration._ import com.webank.wedatasphere.linkis.server.restful.RestfulApplication import com.webank.wedatasphere.linkis.server.socket.ControllerServer import com.webank.wedatasphere.linkis.server.socket.controller.{ServerEventService, ServerListenerEventBus} +import javax.servlet.{DispatcherType, Filter} import org.apache.commons.io.FileUtils import org.eclipse.jetty.server.session.SessionHandler import org.eclipse.jetty.servlet.{DefaultServlet, FilterHolder, ServletContextHandler, ServletHolder} diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala similarity index 99% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala index 5f7ac6df9b..bb9632bc9f 100644 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/Message.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +14,10 @@ package com.webank.wedatasphere.linkis.server import java.util + import javax.ws.rs.Path import javax.ws.rs.core.Response import javax.xml.bind.annotation.XmlRootElement - import org.apache.commons.lang.StringUtils import org.apache.commons.lang.exception.ExceptionUtils import org.reflections.ReflectionUtils @@ -108,7 +105,9 @@ object Message { message.setMessage(msg) message } + implicit def response(message: Message): String = BDPJettyServerHelper.gson.toJson(message) + def noLogin(msg: String, t: Throwable): Message = { val message = Message(status = -1) message.setMessage(msg) diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/conf/DataWorkCloudCustomExcludeFilter.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/conf/DataWorkCloudCustomExcludeFilter.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/conf/DataWorkCloudCustomExcludeFilter.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/conf/DataWorkCloudCustomExcludeFilter.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala similarity index 99% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala index 52c45689b6..dde2ba7b3a 100644 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/conf/ServerConfiguration.scala @@ -97,4 +97,5 @@ object ServerConfiguration { val BDP_SERVER_RESTFUL_SCAN_PACKAGES = CommonVars("wds.linkis.server.restful.scan.packages", "") val BDP_SERVER_RESTFUL_REGISTER_CLASSES = CommonVars("wds.linkis.server.restful.register.classes", "") // val BDP_SERVER_SOCKET_SERVICE_SCAN_PACKAGES = CommonVars("wds.linkis.server.socket.service.scan.packages", BDP_SERVER_RESTFUL_SCAN_PACKAGES.getValue) + val IS_GATEWAY = CommonVars("wds.linkis.is.gateway", "false") } diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/BDPServerException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/BDPServerException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/BDPServerException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/BDPServerException.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/FetchMapCacheFailedException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/FetchMapCacheFailedException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/FetchMapCacheFailedException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/FetchMapCacheFailedException.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/IllegalUserTicketException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/IllegalUserTicketException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/IllegalUserTicketException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/IllegalUserTicketException.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/LoginExpireException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/LoginExpireException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/LoginExpireException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/LoginExpireException.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NoApplicationExistsException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NoApplicationExistsException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NoApplicationExistsException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NoApplicationExistsException.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NonLoginException.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NonLoginException.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NonLoginException.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/exception/NonLoginException.scala diff --git a/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala new file mode 100644 index 0000000000..50c6a5e653 --- /dev/null +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/package.scala @@ -0,0 +1,112 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis + +import java.util + +import com.webank.wedatasphere.linkis.common.exception.{ErrorException, ExceptionManager, FatalException, WarnException} +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.server.exception.{BDPServerErrorException, NonLoginException} +import com.webank.wedatasphere.linkis.server.security.SecurityFilter +import javax.servlet.http.HttpServletRequest +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.exception.ExceptionUtils +import org.slf4j.Logger + +import scala.collection.{JavaConversions, mutable} + +/** + * Created by enjoyyin on 2018/5/2. + */ +package object server { + + val EXCEPTION_MSG = "errorMsg" + type JMap[K, V] = java.util.HashMap[K, V] + + implicit def getUser(req: HttpServletRequest): String = SecurityFilter.getLoginUsername(req) + + def validateFailed(message: String): Message = Message(status = 2).setMessage(message) + def validate[T](json: util.Map[String, T], keys: String*): Unit = { + keys.foreach(k => if(!json.contains(k) || json.get(k) == null || StringUtils.isEmpty(json.get(k).toString)) + throw new BDPServerErrorException(11001, s"Verification failed, $k cannot be empty!(验证失败,$k 不能为空!)")) + } + def error(message: String): Message = Message.error(message) + implicit def ok(msg: String): Message = Message.ok(msg) + implicit def error(t: Throwable): Message = Message.error(t) + implicit def error(e: (String, Throwable)): Message = Message.error(e) + implicit def error(msg: String, t: Throwable): Message = Message.error(msg -> t) + // def tryCatch[T](tryOp: => T)(catchOp: Throwable => T): T = Utils.tryCatch(tryOp)(catchOp) +// def tryCatch(tryOp: => Message)(catchOp: Throwable => Message): Message = Utils.tryCatch(tryOp){ +// case nonLogin: NonLoginException => Message.noLogin(msg = nonLogin.getMessage) +// case t => catchOp(t) +// } + def catchMsg(tryOp: => Message)(msg: String)(implicit log: Logger): Message = Utils.tryCatch(tryOp){ + case fatal: FatalException => + log.error("Fatal Error, system exit...", fatal) + System.exit(fatal.getErrCode) + Message.error("Fatal Error, system exit...") + case nonLogin: NonLoginException => + val message = Message.noLogin(nonLogin.getMessage) + message.data(EXCEPTION_MSG, nonLogin.toMap) + message + case error: ErrorException => + val cause = error.getCause + val errorMsg = cause match { + case t: ErrorException => s"error code(错误码): ${t.getErrCode}, error message(错误信息): ${t.getDesc}." + case _ => s"error code(错误码): ${error.getErrCode}, error message(错误信息): ${error.getDesc}." + } + log.error(errorMsg, error) + val message = Message.error(errorMsg) + message.data(EXCEPTION_MSG, error.toMap) + message + case warn: WarnException => + val warnMsg = s"Warning code(警告码): ${warn.getErrCode}, Warning message(警告信息): ${warn.getDesc}." + log.warn(warnMsg, warn) + val message = Message.warn(warnMsg) + message.data(EXCEPTION_MSG, warn.toMap) + message + case t => + log.error(msg, t) + val errorMsg = ExceptionUtils.getRootCauseMessage(t) + val message = if(StringUtils.isNotEmpty(errorMsg) && "operation failed(操作失败)" != msg) error(msg + "!the reason(原因):" + errorMsg) + else if(StringUtils.isNotEmpty(errorMsg)) error(errorMsg) else error(msg) + message.data(EXCEPTION_MSG, ExceptionManager.unknownException(message.getMessage)) + } + def catchIt(tryOp: => Message)(implicit log: Logger): Message = catchMsg(tryOp)("operation failed(操作失败)s") + implicit def toScalaBuffer[T](list: util.List[T]): mutable.Buffer[T] = JavaConversions.asScalaBuffer(list) + implicit def toScalaMap[K, V](map: util.Map[K, V]): mutable.Map[K, V] = JavaConversions.mapAsScalaMap(map) + implicit def toJavaList[T](list: mutable.Buffer[T]): util.List[T] = { + val arrayList = new util.ArrayList[T] + list.foreach(arrayList.add) + arrayList + } + implicit def toJavaMap[K, V](map: mutable.Map[K, V]): JMap[K, V] = { + val hashMap = new util.HashMap[K, V]() + map.foreach(m => hashMap.put(m._1, m._2)) + hashMap + } + implicit def toJavaMap[K, V](map: Map[K, V]): JMap[K, V] = { + val hashMap = new util.HashMap[K, V]() + map.foreach(m => hashMap.put(m._1, m._2)) + hashMap + } + implicit def asString(mapWithKey: (util.Map[String, Object], String)): String = mapWithKey._1.get(mapWithKey._2).asInstanceOf[String] + implicit def getString(mapWithKey: (util.Map[String, String], String)): String = mapWithKey._1.get(mapWithKey._2) + implicit def asInt(map: util.Map[String, Object], key: String): Int = map.get(key).asInstanceOf[Int] + implicit def asBoolean(mapWithKey: (util.Map[String, Object], String)): Boolean = mapWithKey._1.get(mapWithKey._2).asInstanceOf[Boolean] + +} diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala similarity index 99% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala index 70d3c0c74f..97b54dad9f 100644 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/restful/RestfulCatchAOP.scala @@ -16,10 +16,9 @@ package com.webank.wedatasphere.linkis.server.restful -import javax.ws.rs.core.Response - import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.server.{Message, catchIt} +import javax.ws.rs.core.Response import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.{Around, Aspect, Pointcut} import org.springframework.stereotype.Component diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/security/SSOUtils.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/security/SSOUtils.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/security/SSOUtils.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/security/SSOUtils.scala diff --git a/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala new file mode 100644 index 0000000000..bab363bb3e --- /dev/null +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/security/SecurityFilter.scala @@ -0,0 +1,151 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.server.security + +import java.text.DateFormat +import java.util.{Date, Locale} + +import com.webank.wedatasphere.linkis.common.conf.Configuration +import com.webank.wedatasphere.linkis.common.utils.{Logging, RSAUtils, Utils} +import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration +import com.webank.wedatasphere.linkis.server.exception.{IllegalUserTicketException, LoginExpireException, NonLoginException} +import com.webank.wedatasphere.linkis.server.security.SSOUtils.sslEnable +import com.webank.wedatasphere.linkis.server.{Message, _} +import javax.servlet._ +import javax.servlet.http.{Cookie, HttpServletRequest, HttpServletResponse} +import org.apache.commons.lang.StringUtils + +/** + * Created by enjoyyin on 2018/1/9. + */ +class SecurityFilter extends Filter { + + private val refererValidate = ServerConfiguration.BDP_SERVER_SECURITY_REFERER_VALIDATE.getValue + private val localAddress = ServerConfiguration.BDP_SERVER_ADDRESS.getValue + protected val testUser = ServerConfiguration.BDP_TEST_USER.getValue + + + override def init(filterConfig: FilterConfig): Unit = {} + + private def filterResponse(message: Message)(implicit response: HttpServletResponse): Unit = { + response.setHeader("Content-Type", "application/json;charset=UTF-8") + response.setStatus(Message.messageToHttpStatus(message)) + response.getOutputStream.print(message) + response.getOutputStream.flush() + } + + def doFilter(request: HttpServletRequest)(implicit response: HttpServletResponse): Boolean = { + addAccessHeaders(response) + if (refererValidate) { + //Security certification support, referer limited(安全认证支持,referer限定) + val referer = request.getHeader("Referer") + if (StringUtils.isNotEmpty(referer) && !referer.trim.contains(localAddress)) { + filterResponse(validateFailed("不允许的跨站请求!")) + return false + } + //Security certification support, solving verb tampering(安全认证支持,解决动词篡改) + request.getMethod.toUpperCase match { + case "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "TRACE" | "CONNECT" | "OPTIONS" => + case _ => + filterResponse(validateFailed("Do not use HTTP verbs to tamper with!(不可使用HTTP动词篡改!)")) + return false + } + } + if(request.getRequestURI == ServerConfiguration.BDP_SERVER_SECURITY_SSL_URI.getValue) { + val message = Message.ok("Get success!(获取成功!)").data("enable", SSOUtils.sslEnable) + if(SSOUtils.sslEnable) message.data("publicKey", RSAUtils.getDefaultPublicKey()) + filterResponse(message) + false + } else if(request.getRequestURI == ServerConfiguration.BDP_SERVER_RESTFUL_LOGIN_URI.getValue) { + true + } else { + val userName = Utils.tryCatch(SecurityFilter.getLoginUser(request)){ + case n: NonLoginException => + if(Configuration.IS_TEST_MODE.getValue) None else { + filterResponse(Message.noLogin(n.getMessage) << request.getRequestURI) + return false + } + case t: Throwable => + SecurityFilter.warn("", t) + throw t + } + if(userName.isDefined) { + true + } else if(Configuration.IS_TEST_MODE.getValue) { + SecurityFilter.info("test mode! login for uri: " + request.getRequestURI) + SecurityFilter.setLoginUser(response, testUser) + true + } else { + filterResponse(Message.noLogin("You are not logged in, please login first!(您尚未登录,请先登录!)") << request.getRequestURI) + false + } + } + } + + override def doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain): Unit = { + val request = servletRequest.asInstanceOf[HttpServletRequest] + implicit val response = servletResponse.asInstanceOf[HttpServletResponse] + if(doFilter(request)) filterChain.doFilter(servletRequest, servletResponse) + if(SecurityFilter.isRequestIgnoreTimeout(request)) SecurityFilter.removeIgnoreTimeoutSignal(response) + } + + protected def addAccessHeaders(response: HttpServletResponse) { + response.setHeader("Access-Control-Allow-Origin", "*") + response.setHeader("Access-Control-Allow-Credentials", "true") + response.setHeader("Access-Control-Allow-Headers", "authorization,Content-Type") + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, HEAD, DELETE") + val fullDateFormatEN = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, new Locale("EN", "en")) + response.setHeader("Date", fullDateFormatEN.format(new Date)) + } + + override def destroy(): Unit = {} +} + +object SecurityFilter extends Logging { + private[linkis] val OTHER_SYSTEM_IGNORE_UM_USER = "dataworkcloud_rpc_user" + private[linkis] val ALLOW_ACCESS_WITHOUT_TIMEOUT = "dataworkcloud_inner_request" + def getLoginUserThrowsExceptionWhenTimeout(req: HttpServletRequest): Option[String] = Option(req.getCookies).flatMap(cs => SSOUtils.getLoginUser(cs)) + .orElse(SSOUtils.getLoginUserIgnoreTimeout(key => Option(req.getHeader(key))).filter(_ == OTHER_SYSTEM_IGNORE_UM_USER)) + def getLoginUser(req: HttpServletRequest): Option[String] = Utils.tryCatch(getLoginUserThrowsExceptionWhenTimeout(req)) { + case _: LoginExpireException => + SSOUtils.getLoginUserIgnoreTimeout(key => Option(req.getCookies).flatMap(_.find(_.getName == key).map(_.getValue))).filter(user => user != OTHER_SYSTEM_IGNORE_UM_USER && + isRequestIgnoreTimeout(req)) + case t => throw t + } + def isRequestIgnoreTimeout(req: HttpServletRequest): Boolean = Option(req.getCookies).exists(_.exists(c => c.getName == ALLOW_ACCESS_WITHOUT_TIMEOUT && c.getValue == "true")) + def addIgnoreTimeoutSignal(response: HttpServletResponse): Unit = response.addCookie(ignoreTimeoutSignal()) + def ignoreTimeoutSignal(): Cookie = { + val cookie = new Cookie(ALLOW_ACCESS_WITHOUT_TIMEOUT, "true") + cookie.setMaxAge(-1) + cookie.setPath("/") + if(sslEnable) cookie.setSecure(true) + cookie + } + def removeIgnoreTimeoutSignal(response: HttpServletResponse): Unit = { + val cookie = new Cookie(ALLOW_ACCESS_WITHOUT_TIMEOUT, "false") + cookie.setMaxAge(0) + cookie.setPath("/") + if(sslEnable) cookie.setSecure(true) + response.addCookie(cookie) + } + def getLoginUsername(req: HttpServletRequest): String = getLoginUser(req).getOrElse(throw new IllegalUserTicketException( s"Illegal user token information(非法的用户token信息).")) + def setLoginUser(resp: HttpServletResponse, username: String): Unit = SSOUtils.setLoginUser(c => resp.addCookie(c), username) + def removeLoginUser(req: HttpServletRequest, resp: HttpServletResponse): Unit = { + SSOUtils.removeLoginUser(req.getCookies) + SSOUtils.removeLoginUserByAddCookie(s => resp.addCookie(s)) + } +} \ No newline at end of file diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ControllerServer.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ControllerServer.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ControllerServer.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ControllerServer.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala index f79b552def..2b195fa3fc 100644 --- a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala +++ b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/ServerSocket.scala @@ -20,8 +20,8 @@ import java.util.concurrent.TimeUnit import com.webank.wedatasphere.linkis.common.collection.BlockingLoopArray import com.webank.wedatasphere.linkis.common.utils.Utils -import javax.servlet.http.HttpServletRequest import com.webank.wedatasphere.linkis.server.security.SecurityFilter +import javax.servlet.http.HttpServletRequest import org.eclipse.jetty.websocket.api.{Session, WebSocketAdapter} /** diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/SocketListener.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/SocketListener.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/SocketListener.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/SocketListener.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEvent.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEvent.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEvent.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEvent.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEventService.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEventService.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEventService.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerEventService.scala diff --git a/core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerListenerEventBus.scala b/linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerListenerEventBus.scala similarity index 100% rename from core/cloudModule/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerListenerEventBus.scala rename to linkis-commons/linkis-module/src/main/scala/com/webank/wedatasphere/linkis/server/socket/controller/ServerListenerEventBus.scala diff --git a/linkis-commons/linkis-mybatis/pom.xml b/linkis-commons/linkis-mybatis/pom.xml new file mode 100644 index 0000000000..c60393013e --- /dev/null +++ b/linkis-commons/linkis-mybatis/pom.xml @@ -0,0 +1,92 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + jar + + linkis-mybatis + + + + com.webank.wedatasphere.linkis + linkis-module + provided + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.boot.starter.version} + + + spring-boot-starter + org.springframework.boot + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-beans + org.springframework + + + spring-jdbc + org.springframework + + + + + spring-jdbc + org.springframework + ${spring.version} + + + com.github.pagehelper + pagehelper + 5.1.4 + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + \ No newline at end of file diff --git a/core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/DataSourceConfig.java b/linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/DataSourceConfig.java similarity index 100% rename from core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/DataSourceConfig.java rename to linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/DataSourceConfig.java diff --git a/core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MyBatisMapperScannerConfig.java b/linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MyBatisMapperScannerConfig.java similarity index 100% rename from core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MyBatisMapperScannerConfig.java rename to linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MyBatisMapperScannerConfig.java diff --git a/core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java b/linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java similarity index 95% rename from core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java rename to linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java index 131b4127dd..9d6efd2c1d 100644 --- a/core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java +++ b/linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/MybatisConfigurationFactory.java @@ -16,7 +16,7 @@ package com.webank.wedatasphere.linkis.mybatis; -import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import com.github.pagehelper.PageInterceptor; import com.webank.wedatasphere.linkis.common.utils.JavaLog; import com.webank.wedatasphere.linkis.mybatis.conf.MybatisConfiguration; @@ -59,14 +59,14 @@ public class MybatisConfigurationFactory extends JavaLog { // Provide SqlSeesion(提供SqlSeesion) @Bean(name = "sqlSessionFactory") @Primary - public SqlSessionFactory sqlSessionFactory() { + public MybatisSqlSessionFactoryBean sqlSessionFactory() { String typeAliasesPackage = MybatisConfiguration.BDP_SERVER_MYBATIS_TYPEALIASESPACKAGE.getValue(); //Configure the mapper scan to find all mapper.xml mapping files(配置mapper的扫描,找到所有的mapper.xml映射文件) String mapperLocations = MybatisConfiguration.BDP_SERVER_MYBATIS_MAPPER_LOCATIONS.getValue(); //Load the global configuration file(加载全局的配置文件) String configLocation = MybatisConfiguration.BDP_SERVER_MYBATIS_CONFIGLOCATION.getValue(); try { - SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); + MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); info("Mybatis typeAliasesPackage=" + typeAliasesPackage); @@ -89,11 +89,12 @@ public SqlSessionFactory sqlSessionFactory() { // Set the location of the mybatis-config.xml configuration file(设置mybatis-config.xml配置文件位置) sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); + // Add paging plugin, print sql plugin(添加分页插件、打印sql插件) Interceptor[] plugins = new Interceptor[]{pageInterceptor()}; sessionFactoryBean.setPlugins(plugins); - return sessionFactoryBean.getObject(); + return sessionFactoryBean; } catch (IOException e) { error("mybatis resolver mapper*xml is error",e); return null; diff --git a/core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/conf/MybatisConfiguration.java b/linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/conf/MybatisConfiguration.java similarity index 100% rename from core/cloudMybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/conf/MybatisConfiguration.java rename to linkis-commons/linkis-mybatis/src/main/java/com/webank/wedatasphere/linkis/mybatis/conf/MybatisConfiguration.java diff --git a/linkis-commons/linkis-protocol/pom.xml b/linkis-commons/linkis-protocol/pom.xml new file mode 100644 index 0000000000..ee148de050 --- /dev/null +++ b/linkis-commons/linkis-protocol/pom.xml @@ -0,0 +1,59 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-protocol + + + + com.webank.wedatasphere.linkis + linkis-common + provided + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/AbstractRetryableProtocol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/AbstractRetryableProtocol.java new file mode 100644 index 0000000000..3a161b7c47 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/AbstractRetryableProtocol.java @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.webank.wedatasphere.linkis.protocol; + + +public class AbstractRetryableProtocol implements RetryableProtocol { + + @Override + public long maxPeriod() { + return 3000L; + } + + @Override + public Class extends Throwable>[] retryExceptions() { + return new Class[]{}; + } + + @Override + public int retryNum() { + return 2; + } + + @Override + public long period() { + return 1000L; + } + +} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java similarity index 79% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java index b45d05261a..060ecaf757 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/constants/TaskConstant.java @@ -16,12 +16,15 @@ package com.webank.wedatasphere.linkis.protocol.constants; -/** - * created by enjoyyin on 2018/10/10 - * Description: - */ + public interface TaskConstant { + String UMUSER = "umUser"; + + String SUBMIT_USER = "submitUser"; + + String EXECUTE_USER = "executeUser"; + String TASKTYPE = "taskType"; String STORAGETYPE = "storageType"; String EXECUTIONCODE = "executionCode"; @@ -34,11 +37,20 @@ public interface TaskConstant { String SCRIPTPATH = "scriptPath"; String SOURCE = "source"; String RUNTYPE = "runType"; + String CACHE = "cache"; + String CACHE_EXPIRE_AFTER = "cacheExpireAfter"; + String READ_FROM_CACHE = "readFromCache"; + String READ_CACHE_BEFORE = "readCacheBefore"; String PARAMS_VARIABLE = "variable"; String PARAMS_CONFIGURATION = "configuration"; String PARAMS_CONFIGURATION_STARTUP = "startup"; String PARAMS_CONFIGURATION_RUNTIME = "runtime"; String PARAMS_CONFIGURATION_SPECIAL = "special"; - String PARAMS_CONFIGURATION_DATASOURCE = "datasource"; + + String LABELS = "labels"; + String EXECUTION_CONTENT = "executionContent"; + String CODE = "code"; + + } diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/EngineState.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/EngineState.java new file mode 100644 index 0000000000..a7f28b0378 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/EngineState.java @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.webank.wedatasphere.linkis.protocol.engine; + + +public enum EngineState { + + /** + * 引擎的各种状态 + */ + Starting, Idle, Busy, ShuttingDown, Error, Dead, Success; + + public int id() { + return this.ordinal(); + } + + public static boolean isCompleted(EngineState engineState) { + switch (engineState) { + case Error: + case Dead: + case Success: + return true; + default: + return false; + } + } + + public static boolean isAvailable(EngineState engineState) { + switch (engineState) { + case Idle: + case Busy: + return true; + default: + return false; + } + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/JobProgressInfo.scala b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/JobProgressInfo.scala new file mode 100644 index 0000000000..c13f78f915 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/engine/JobProgressInfo.scala @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.engine + + +case class JobProgressInfo(id: String, totalTasks: Int, runningTasks: Int, failedTasks: Int, succeedTasks: Int) + diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelAttachRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelAttachRequest.java new file mode 100644 index 0000000000..8f5392a53d --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelAttachRequest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; + +import java.util.HashMap; +import java.util.Map; + + +public class InsLabelAttachRequest implements LabelRequest { + /** + * Service instance + */ + private ServiceInstance serviceInstance; + + /** + * Labels stored as map structure + */ + private Map labels = new HashMap<>(); + + + public InsLabelAttachRequest(){ + + } + + public InsLabelAttachRequest(ServiceInstance serviceInstance, Map labels){ + this.serviceInstance = serviceInstance; + this.labels = labels; + } + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + public Map getLabels() { + return labels; + } + + public void setLabels(Map labels) { + this.labels = labels; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRefreshRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRefreshRequest.java new file mode 100644 index 0000000000..0564686d96 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRefreshRequest.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; + +import java.util.Map; + + +public class InsLabelRefreshRequest extends InsLabelAttachRequest{ + + public InsLabelRefreshRequest(){ + + } + + public InsLabelRefreshRequest(ServiceInstance serviceInstance, Map labels){ + super(serviceInstance, labels); + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRemoveRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRemoveRequest.java new file mode 100644 index 0000000000..7da068c228 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/InsLabelRemoveRequest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; + + +public class InsLabelRemoveRequest implements LabelRequest{ + + private ServiceInstance serviceInstance; + + public InsLabelRemoveRequest(){ + + } + + public InsLabelRemoveRequest(ServiceInstance serviceInstance){ + this.serviceInstance = serviceInstance; + } + + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/LabelRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/LabelRequest.java new file mode 100644 index 0000000000..b3d93eba10 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/LabelRequest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol; + + +public interface LabelRequest extends RequestProtocol { +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelAddRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelAddRequest.java new file mode 100644 index 0000000000..cc4b50b1ff --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelAddRequest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; + +import java.util.Map; + + +public class NodeLabelAddRequest implements LabelRequest { + + private ServiceInstance serviceInstance; + + private Map labels; + + + public NodeLabelAddRequest() { + + } + + public NodeLabelAddRequest(ServiceInstance serviceInstance, Map labels) { + this.serviceInstance = serviceInstance; + this.labels = labels; + } + + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + public Map getLabels() { + return labels; + } + + public void setLabels(Map labels) { + this.labels = labels; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelRemoveRequest.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelRemoveRequest.java new file mode 100644 index 0000000000..79224834fc --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/label/NodeLabelRemoveRequest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.label; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; + + +public class NodeLabelRemoveRequest implements LabelRequest { + + private ServiceInstance serviceInstance; + + private boolean isEngine; + + public NodeLabelRemoveRequest() { + + } + + public NodeLabelRemoveRequest(ServiceInstance serviceInstance, boolean isEngine) { + this.serviceInstance = serviceInstance; + this.isEngine = isEngine; + } + + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + public boolean isEngine() { + return isEngine; + } + + public void setEngine(boolean engine) { + isEngine = engine; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/HttpPrototol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/HttpPrototol.java new file mode 100644 index 0000000000..bf58e339c0 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/HttpPrototol.java @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.webank.wedatasphere.linkis.protocol.message; + +import com.webank.wedatasphere.linkis.protocol.Protocol; + + +public interface HttpPrototol extends Protocol { +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestMethod.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestMethod.java new file mode 100644 index 0000000000..7c3dc8ec5f --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestMethod.java @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.webank.wedatasphere.linkis.protocol.message; + + +public interface RequestMethod { + + default String method() { + return null; + } + +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestProtocol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestProtocol.java new file mode 100644 index 0000000000..2027061b4c --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/message/RequestProtocol.java @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.message; + + +public interface RequestProtocol extends HttpPrototol { + +} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/QueryProtocol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/QueryProtocol.java similarity index 100% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/QueryProtocol.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/QueryProtocol.java diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java new file mode 100644 index 0000000000..82def11507 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheNotFound.java @@ -0,0 +1,20 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +public class CacheNotFound implements ResponseReadCache { +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java new file mode 100644 index 0000000000..dfb0668195 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/CacheTaskResult.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +public class CacheTaskResult implements ResponseReadCache { + + private String resultLocation; + + public CacheTaskResult(String resultLocation) { + this.resultLocation = resultLocation; + } + + public String getResultLocation() { + return resultLocation; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java new file mode 100644 index 0000000000..504f469ff6 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/FailedToDeleteCache.java @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +public class FailedToDeleteCache { + private String errorMessage; + + public FailedToDeleteCache(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return errorMessage; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java new file mode 100644 index 0000000000..1a7599f7c8 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestDeleteCache.java @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + +public class RequestDeleteCache implements QueryProtocol { + + private String executionCode; + private String engineType; + private String user; + + public RequestDeleteCache(String executionCode, String engineType, String user) { + this.executionCode = executionCode; + this.engineType = engineType; + this.user = user; + } + + public String getExecutionCode() { + return executionCode; + } + + public String getEngineType() { + return engineType; + } + + public String getUser() { + return user; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java new file mode 100644 index 0000000000..aa4d28d93a --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/RequestReadCache.java @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + +public class RequestReadCache implements QueryProtocol { + private String executionCode; + private String engineType; + private String user; + private Long readCacheBefore; + + public RequestReadCache(String executionCode, String engineType, String user, Long readCacheBefore) { + this.executionCode = executionCode; + this.engineType = engineType; + this.user = user; + this.readCacheBefore = readCacheBefore; + } + + public String getExecutionCode() { + return executionCode; + } + + public String getEngineType() { + return engineType; + } + + public String getUser() { + return user; + } + + public Long getReadCacheBefore() { + return readCacheBefore; + } +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java new file mode 100644 index 0000000000..d8a7f8c7d9 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseDeleteCache.java @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + +public interface ResponseDeleteCache extends QueryProtocol { +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java new file mode 100644 index 0000000000..fa6f4d8b92 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/ResponseReadCache.java @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + +public interface ResponseReadCache extends QueryProtocol { +} diff --git a/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java new file mode 100644 index 0000000000..2007494915 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/cache/SuccessDeletedCache.java @@ -0,0 +1,20 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.query.cache; + +public class SuccessDeletedCache { +} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java similarity index 97% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java index 76237ea9f6..7f66f199c1 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestLogin.java @@ -17,9 +17,7 @@ package com.webank.wedatasphere.linkis.protocol.usercontrol; -/** - * Created by alexyang - */ + public class RequestLogin implements UserControlLoginProtocol { private String userName; diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java similarity index 93% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java index f36a0211e2..08a75ba044 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/RequestRegister.java @@ -16,15 +16,13 @@ package com.webank.wedatasphere.linkis.protocol.usercontrol; -/** - * Created by alexyang - */ + public class RequestRegister implements UserControlRegtisterProtocol{ // json string private String params; - public RequestRegister() {} + public RequestRegister() {}; public String getParams() { return params; diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java similarity index 97% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java index e82a4a73f2..cdbae958ea 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseLogin.java @@ -18,9 +18,7 @@ import java.util.Date; -/** - * Created by alexyang - */ + public class ResponseLogin implements UserControlLoginProtocol { private String userName; diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java similarity index 97% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java index 5c12d62626..a6b0e4dfac 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/ResponseRegister.java @@ -18,10 +18,8 @@ import java.util.HashMap; -/** - * Created by alexyang - */ -public class ResponseRegister implements UserControlRegtisterProtocol { + +public class ResponseRegister implements UserControlRegtisterProtocol{ private int status; private String message; diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java similarity index 77% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java index 95b00362d2..4cdb39dd86 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlLoginProtocol.java @@ -1,7 +1,5 @@ package com.webank.wedatasphere.linkis.protocol.usercontrol; -/** - * Created by alexyang - */ + public interface UserControlLoginProtocol { } diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java similarity index 78% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java rename to linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java index 04a6d1f7c9..1ea4e04542 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java +++ b/linkis-commons/linkis-protocol/src/main/java/com/webank/wedatasphere/linkis/protocol/usercontrol/UserControlRegtisterProtocol.java @@ -1,7 +1,5 @@ package com.webank.wedatasphere.linkis.protocol.usercontrol; -/** - * Created by alexyang - */ + public interface UserControlRegtisterProtocol { } diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala similarity index 94% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala index 6f5e20f1a0..2ea57147bc 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/BroadcastProtocol.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/14. - */ + trait BroadcastProtocol extends Protocol { val throwsIfAnyFailed = false diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala index b4706a78dd..88b90800f4 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/CacheableProtocol.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/14. - */ + trait CacheableProtocol extends Protocol { override def toString: String = super.toString } diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala index 218ad3ebf2..bf5612b4c0 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRCommonProtocol.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/14. - */ + trait IRCommonProtocol extends IRProtocol { val rule: String } diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala index f086081e1f..885133f7d2 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRProtocol.scala @@ -16,7 +16,5 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait IRProtocol \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala similarity index 95% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala index 89afccc0ed..b9f8e4df44 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/IRServiceGroupProtocol.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait IRServiceGroupProtocol extends IRProtocol with InstanceProtocol { val userWithCreator: UserWithCreator diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala similarity index 94% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala index 650476cd3f..311d0d64a7 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/InstanceProtocol.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait InstanceProtocol extends Protocol { var choseInstance: Option[String] = None diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala index f7501493ca..2bfa075683 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/Protocol.scala @@ -16,7 +16,5 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait Protocol \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala similarity index 79% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala index 84bf31b280..9fd2f40e96 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/RetryableProtocol.scala @@ -16,12 +16,10 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait RetryableProtocol extends Protocol { - val retryNum = 2 - val period = 1000l - val maxPeriod = 3000l - val retryExceptions = Array.empty[Class[_ <: Throwable]] + def retryNum: Int = 2 + def period: Long = 1000l + def maxPeriod: Long = 3000l + def retryExceptions: Array[Class[_ <: Throwable]] = Array.empty[Class[_ <: Throwable]] } \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala index 3b25e4318e..3ea12e17e3 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/SingleInstanceProtocol.scala @@ -16,7 +16,5 @@ package com.webank.wedatasphere.linkis.protocol -/** - * Created by enjoyyin on 2019/1/7. - */ + trait SingleInstanceProtocol extends Protocol \ No newline at end of file diff --git a/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/callback/LogCallbackProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/callback/LogCallbackProtocol.scala new file mode 100644 index 0000000000..67d7c7e142 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/callback/LogCallbackProtocol.scala @@ -0,0 +1,11 @@ +package com.webank.wedatasphere.linkis.protocol.callback + +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + + +// TODO: log type +case class LogCallbackProtocol(nodeId: String, logs: Array[String]) extends RequestProtocol + +case class YarnAPPIdCallbackProtocol(nodeId: String, applicationId: String) extends RequestProtocol + +case class YarnInfoCallbackProtocol(nodeId: String, uri: String) extends RequestProtocol diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala similarity index 96% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala index e5cef4085b..5ba62fc236 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineCallback.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.protocol.engine -/** - * Created by enjoyyin on 2018/9/26. - */ + object EngineCallback { private val DWC_APPLICATION_NAME = "dwc.application.name" private val DWC_INSTANCE = "dwc.application.instance" diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala similarity index 92% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala index 5e16ca27a0..ddeed2a36f 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/EngineState.scala @@ -16,10 +16,8 @@ package com.webank.wedatasphere.linkis.protocol.engine -/** - * Created by enjoyyin on 2018/9/27. - */ -object EngineState extends Enumeration { + +object EngineState0 extends Enumeration { type EngineState = Value val Starting, Idle, Busy, ShuttingDown, Error, Dead, Success = Value def isCompleted(executorState: EngineState): Boolean = executorState match { diff --git a/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala new file mode 100644 index 0000000000..5c089ba75c --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestEngineStatus.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.engine + +import com.webank.wedatasphere.linkis.protocol.RetryableProtocol +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + + +case class RequestEngineStatus(messageType: Int) extends RetryableProtocol with RequestProtocol +object RequestEngineStatus { + val Status_Only = 1 + val Status_Overload = 2 + val Status_Concurrent = 3 + val Status_Overload_Concurrent = 4 + val Status_BasicInfo = 5 + val ALL = 6 +} \ No newline at end of file diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala similarity index 85% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala index c3596c305e..3808be496d 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/engine/RequestUserEngineKill.scala @@ -16,9 +16,9 @@ package com.webank.wedatasphere.linkis.protocol.engine -import com.webank.wedatasphere.linkis.protocol.RetryableProtocol +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol -case class RequestUserEngineKill(ticketId: String, creator: String, user: String, properties: Map[String, String]) extends RetryableProtocol +case class RequestUserEngineKill(ticketId: String, creator: String, user: String, properties: Map[String, String]) extends RequestProtocol case class ResponseUserEngineKill(ticketId: String, status: String, message: String) object ResponseUserEngineKill{ val Success = "Success" diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/mdq/MDQProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/mdq/MDQProtocol.scala similarity index 100% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/mdq/MDQProtocol.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/mdq/MDQProtocol.scala diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala similarity index 92% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala index e2f02f28b0..82cb9e7d61 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/task/Task.scala @@ -16,10 +16,7 @@ package com.webank.wedatasphere.linkis.protocol.task -/** - * created by enjoyyin on 2018/10/8 - * Description: - */ + trait Task { def getInstance: String diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala similarity index 96% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala index 63e4e71059..9449f8746a 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ProtocolUtils.scala @@ -18,9 +18,7 @@ package com.webank.wedatasphere.linkis.protocol.utils import com.webank.wedatasphere.linkis.common.conf.CommonVars -/** - * Created by enjoyyin on 2019/1/7. - */ + object ProtocolUtils { val SERVICE_SUFFIX = CommonVars("wds.linkis.service.suffix","engineManager,entrance,engine") diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala similarity index 93% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala index e888fe1316..5ea907f305 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/TaskUtils.scala @@ -79,7 +79,9 @@ object TaskUtils { def addSpecialMap(params: util.Map[String, Any], specialMap: util.Map[String, Any]) = addConfigurationMap(params, specialMap, TaskConstant.PARAMS_CONFIGURATION_SPECIAL) - def addDatasourceMap(params: util.Map[String, Any], datasourceMap: util.Map[String, Any]) = - addConfigurationMap(params, datasourceMap, TaskConstant.PARAMS_CONFIGURATION_DATASOURCE) + // tdoo + def getLabelsMap(params: util.Map[String, Any]) = getMap(params, TaskConstant.LABELS) + + def addLabelsMap(params: util.Map[String, Any], labels: util.Map[String, Any]): Unit = addMap(params, labels, TaskConstant.LABELS) } diff --git a/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala new file mode 100644 index 0000000000..0849d31ae0 --- /dev/null +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/utils/ZuulEntranceUtils.scala @@ -0,0 +1,149 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.protocol.utils + +import com.webank.wedatasphere.linkis.common.ServiceInstance + + +object ZuulEntranceUtils { + + + private val INSTANCE_SPLIT_TOKEN = "_" + + private val EXEC_ID = "exec_id" + + private val SPLIT_LEN = 3 + + def parseExecID(longExecID: String): Array[String] = { + //Add creator to execID while old code is compatible(添加creator到execID,同时老代码兼容) + if (longExecID.startsWith(EXEC_ID)) { + val content = longExecID.replaceFirst(EXEC_ID, "") + val applicationNameLength = Integer.parseInt(content.substring(0, SPLIT_LEN)) + val instanceLength = Integer.parseInt(content.substring(SPLIT_LEN, SPLIT_LEN * 2)) + val applicationName = content.substring(SPLIT_LEN * 2, SPLIT_LEN * 2 + applicationNameLength) + val instances = content.substring(SPLIT_LEN * 2 + applicationNameLength, SPLIT_LEN * 2 + applicationNameLength + instanceLength) + val shortExecID = content.substring(SPLIT_LEN * 2 + applicationNameLength + instanceLength, content.length) + Array[String](EXEC_ID, applicationName, instances, shortExecID) + } else { + // @Deprecated 将在之后删掉该部分内容 + val creatorLength = Integer.parseInt(longExecID.substring(0, 2)) + val executeLength = Integer.parseInt(longExecID.substring(2, 4)) + val instanceLength = Integer.parseInt(longExecID.substring(4, 6)) + val creator = longExecID.substring(6, 6 + creatorLength) + val executeApplicationName = longExecID.substring(6 + creatorLength, 6 + creatorLength + executeLength) + val instance = longExecID.substring(6 + creatorLength + executeLength, 6 + creatorLength + executeLength + instanceLength) + val shortExecID = longExecID.substring(6 + creatorLength + executeLength + instanceLength, longExecID.length) + Array(creator, executeApplicationName, instance, shortExecID) + } + /*val executeLength = Integer.parseInt(longExecID.substring(0,2)) + val instanceLength = Integer.parseInt(longExecID.substring(2,4)) + val executeApplicationName:String = longExecID.substring(4, 4 + executeLength) + val instance:String = longExecID.substring(4 + executeLength, 4 + executeLength + instanceLength) + val shortExecID:String = longExecID.substring(4 + executeLength + instanceLength, longExecID.length) + Array[String](executeApplicationName, instance, shortExecID)*/ + } + + @Deprecated + def generateExecID(shortExecID: String, executeApplicationName: String, instance: String, creator: String): String = { + val creatorLength = getLengthStr(creator) + val executeLength = getLengthStr(executeApplicationName) + val instanceLength = getLengthStr(instance) + creatorLength + executeLength + instanceLength + creator + executeApplicationName + instance + shortExecID + } + + + private def isNumberic(s: String): Boolean = { + s.toCharArray foreach { + c => if (c < 48 || c > 57) return false + } + true + } + + /** + * + * @param shortExecID ExecID generated by the scheduler, such as IDE_neiljianliu_0(scheduler生成的ExecID, 如 IDE_neiljianliu_0) + * @param executeApplicationName {dd}{dd}${executeApplicationName}${instance}${shortExecID} + * @return + */ + @Deprecated + def generateExecID(shortExecID:String, executeApplicationName:String, instance:String):String = { + val executeLength = getLengthStr(executeApplicationName) + val instanceLength = getLengthStr(instance) + if (shortExecID.split("_").length == 3) { + //Backward compatible(向下兼容) + val creator = shortExecID.split("_")(0) + val creatorLength = getLengthStr(creator) + return creatorLength + executeLength + instanceLength + creator + executeApplicationName + instance + shortExecID + } + executeLength + instanceLength + executeApplicationName + instance + shortExecID + } + + def main(args: Array[String]): Unit = { + val str = generateExecID("spark_test_01", "linkis-cg-entrance", Array[String]("172.0.0.1:8080")) + val array = parseServiceInstanceByExecID(str) + println(array(3)) + } + + def parseServiceInstanceByExecID(longExecID: String): Array[ServiceInstance] = { + if (longExecID.startsWith(EXEC_ID)) { + val content = longExecID.replaceFirst(EXEC_ID, "") + val applicationNameLength = Integer.parseInt(content.substring(0, SPLIT_LEN)) + val instanceLength = Integer.parseInt(content.substring(SPLIT_LEN, SPLIT_LEN * 2)) + val applicationName = content.substring(SPLIT_LEN * 2, SPLIT_LEN * 2 + applicationNameLength) + val instances = content.substring(SPLIT_LEN * 2 + applicationNameLength, SPLIT_LEN * 2 + applicationNameLength + instanceLength) + val shortExecID = content.substring(SPLIT_LEN * 2 + applicationNameLength + instanceLength, content.length) + instances.split(INSTANCE_SPLIT_TOKEN).map(ServiceInstance(applicationName, _)) + } else { + // @Deprecated 将在之后删掉该部分内容 + val creatorLength = Integer.parseInt(longExecID.substring(0, 2)) + val executeLength = Integer.parseInt(longExecID.substring(2, 4)) + val instanceLength = Integer.parseInt(longExecID.substring(4, 6)) + val executeApplicationName = longExecID.substring(6 + creatorLength, 6 + creatorLength + executeLength) + val instance = longExecID.substring(6 + creatorLength + executeLength, 6 + creatorLength + executeLength + instanceLength) + Array(ServiceInstance(executeApplicationName, instance)) + } + } + + + private def getLengthStr(string: String): String = { + val length = string.length + if (length >= 10) String.valueOf(length) else "0" + String.valueOf(length) + } + + def generateExecID(shortExecID: String, applicationName: String, instances: Array[String]): String = { + if (null == instances || instances.isEmpty) { + throw new RuntimeException("生成ExecID失败,传入的Instance不能为空") + } + val applicationNameLength = getStrFixedLen(applicationName, SPLIT_LEN) + val instanceStr = instances.mkString(INSTANCE_SPLIT_TOKEN) + val instanceStrLength = getStrFixedLen(instanceStr, SPLIT_LEN) + EXEC_ID + applicationNameLength + instanceStrLength + applicationName + instanceStr + shortExecID + } + + + /*private def getLengthStr(string:String):String = { + val length = string.length + if (length >= 10) String.valueOf(length) else "0" + String.valueOf(length) + }*/ + + private def getStrFixedLen(string: String, len: Int): String = { + val str = String.valueOf(string.length) + val res = "0" * (len - str.length) + str + res + } + +} diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala similarity index 95% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala index 4629cefc2d..c920a65851 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/RequestQueryGlobalVariable.scala @@ -18,9 +18,7 @@ package com.webank.wedatasphere.linkis.protocol.variable import com.webank.wedatasphere.linkis.protocol.{CacheableProtocol, RetryableProtocol} -/** - * Created by enjoyyin on 2018/10/18. - */ + trait VariableProtocol case class RequestQueryGlobalVariable (userName:String) extends CacheableProtocol with RetryableProtocol with VariableProtocol diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala similarity index 95% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala rename to linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala index fe87ce42ae..4a92c75a7e 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala +++ b/linkis-commons/linkis-protocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/variable/ResponseQueryVariable.scala @@ -18,9 +18,7 @@ package com.webank.wedatasphere.linkis.protocol.variable import java.util -/** - * Created by enjoyyin on 2018/10/18. - */ + class ResponseQueryVariable extends VariableProtocol { private var keyAndValue: util.Map[String, String] = _ def getKeyAndValue :util.Map[String, String] = keyAndValue diff --git a/linkis-commons/linkis-rpc/pom.xml b/linkis-commons/linkis-rpc/pom.xml new file mode 100644 index 0000000000..8084bf8369 --- /dev/null +++ b/linkis-commons/linkis-rpc/pom.xml @@ -0,0 +1,167 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-rpc + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + + + com.webank.wedatasphere.linkis + linkis-module + + + spring-cloud-commons + org.springframework.cloud + + + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring.feign.version} + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-boot-starter-aop + org.springframework.boot + + + spring-web + org.springframework + + + jackson-annotations + com.fasterxml.jackson.core + + + jackson-core + com.fasterxml.jackson.core + + + jackson-databind + com.fasterxml.jackson.core + + + jsr305 + com.google.code.findbugs + + + HdrHistogram + org.hdrhistogram + + + spring-cloud-commons + org.springframework.cloud + + + spring-cloud-starter-openfeign + org.springframework.cloud + + + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring.cloud.version} + + + spring-boot-autoconfigure + org.springframework.boot + + + spring-boot-starter-aop + org.springframework.boot + + + spring-cloud-commons + org.springframework.cloud + + + spring-web + org.springframework + + + + + org.springframework.cloud + spring-cloud-commons + ${spring.cloud.version} + + + spring-security-crypto + org.springframework.security + + + + + + io.protostuff + protostuff-core + 1.6.2 + compile + + + + + + io.protostuff + protostuff-runtime + 1.6.2 + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/NoneDelegate.java b/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/NoneDelegate.java new file mode 100644 index 0000000000..e2e57467ec --- /dev/null +++ b/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/NoneDelegate.java @@ -0,0 +1,79 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc.serializer; + +import io.protostuff.*; +import io.protostuff.runtime.Delegate; +import scala.Option; + +import java.io.IOException; + + +public class NoneDelegate implements Delegate { + @Override + public WireFormat.FieldType getFieldType() { + return WireFormat.FieldType.UINT32; + } + + @Override + public Option readFrom(Input input) throws IOException { + throw new ProtostuffException("Corrupt input. option cannot serialize"); + } + + @Override + public void writeTo(Output output, int i, Option option, boolean b) throws IOException { + throw new ProtostuffException("Corrupt input. option cannot serialize"); + } + + @Override + public void transfer(Pipe pipe, Input input, Output output, int i, boolean b) throws IOException { + throw new ProtostuffException("Corrupt input. option cannot serialize"); + } + + @Override + public Class> typeClass() { + return Option.class; + } + + /*@Override + public WireFormat.FieldType getFieldType() { + return WireFormat.FieldType.UINT32; + } + + @Override + public None$ readFrom(Input input) throws IOException { + if(0 != input.readUInt32()) + throw new ProtostuffException("Corrupt input."); + + return None$.MODULE$; + } + + @Override + public void writeTo(Output output, int number, None$ none$, boolean repeated) throws IOException { + output.writeFixed64(number, 0, repeated); + } + + @Override + public void transfer(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException { + output.writeUInt32(number, input.readUInt32(), repeated); + } + + @Override + public Class> typeClass() { + return None$.class; + }*/ +} diff --git a/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/ProtostuffSerializeUtil.java b/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/ProtostuffSerializeUtil.java new file mode 100644 index 0000000000..00dbf5a4e6 --- /dev/null +++ b/linkis-commons/linkis-rpc/src/main/java/com/webank/wedatasphere/linkis/rpc/serializer/ProtostuffSerializeUtil.java @@ -0,0 +1,128 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.rpc.serializer; + +import io.protostuff.LinkedBuffer; +import io.protostuff.ProtostuffIOUtil; +import io.protostuff.Schema; +import io.protostuff.runtime.DefaultIdStrategy; +import io.protostuff.runtime.Delegate; +import io.protostuff.runtime.RuntimeEnv; +import io.protostuff.runtime.RuntimeSchema; +import scala.Option; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + + +public class ProtostuffSerializeUtil { + + private final static Delegate TIMESTAMP_DELEGATE = new NoneDelegate(); + + private final static DefaultIdStrategy idStrategy = ((DefaultIdStrategy) RuntimeEnv.ID_STRATEGY); + + static { + idStrategy.registerDelegate(TIMESTAMP_DELEGATE); + } + + /** + * 缓存Schema + */ + private static Map, Schema>> schemaCache = new ConcurrentHashMap, Schema>>(); + + public static String serialize(T obj) { + + if (obj == null) { + throw new NullPointerException(); + } + Class clazz = (Class) obj.getClass(); + Schema schema = getSchema(clazz); + byte[] data; + LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); + try { + data = ProtostuffIOUtil.toByteArray(obj, schema, buffer); + } finally { + buffer.clear(); + } + return toHexString(data); + } + + public static T deserialize(String str, Class clazz) { + Schema schema = getSchema(clazz); + T obj = schema.newMessage(); + ProtostuffIOUtil.mergeFrom(toByteArray(str), obj, schema); + return obj; + } + + + private static Schema getSchema(Class clazz) { + Schema schema = (Schema) schemaCache.get(clazz); + if (schema == null) { + schema = RuntimeSchema.createFrom(clazz, idStrategy); + if (schema != null) { + schemaCache.put(clazz, schema); + } + } + + return schema; + } + + /** + * 16进制的字符串表示转成字节数组 + * + * @param hexString 16进制格式的字符串 + * @return 转换后的字节数组 + **/ + public static byte[] toByteArray(String hexString) { + if (null == hexString) + throw new IllegalArgumentException("this hexString must not be null"); + + if ("".equals(hexString)) + return new byte[0]; + + hexString = hexString.toLowerCase(); + final byte[] byteArray = new byte[hexString.length() / 2]; + int k = 0; + for (int i = 0; i < byteArray.length; i++) {//因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先 + byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff); + byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff); + byteArray[i] = (byte) (high << 4 | low); + k += 2; + } + return byteArray; + } + + /** + * 字节数组转成16进制表示格式的字符串 + * + * @param byteArray 需要转换的字节数组 + * @return 16进制表示格式的字符串 + **/ + public static String toHexString(byte[] byteArray) { + if (byteArray == null) + throw new IllegalArgumentException("this byteArray must not be null "); + + final StringBuilder hexString = new StringBuilder(); + for (int i = 0; i < byteArray.length; i++) { + if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零 + hexString.append("0"); + hexString.append(Integer.toHexString(0xFF & byteArray[i])); + } + return hexString.toString().toLowerCase(); + } + +} diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/AsynRPCMessageBus.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/AsynRPCMessageBus.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/AsynRPCMessageBus.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/AsynRPCMessageBus.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/BaseRPCSender.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/BaseRPCSender.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/BaseRPCSender.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/BaseRPCSender.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/BroadcastListener.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/BroadcastListener.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/BroadcastListener.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/BroadcastListener.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCMapCache.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCMapCache.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCMapCache.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCMapCache.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRemote.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRemote.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRemote.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRemote.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRestful.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRestful.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRestful.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCReceiveRestful.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCSpringBeanCache.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCSpringBeanCache.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCSpringBeanCache.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/RPCSpringBeanCache.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/Receiver.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/Receiver.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/Receiver.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/Receiver.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverChooser.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverChooser.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverChooser.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverChooser.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverSenderBuilder.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverSenderBuilder.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverSenderBuilder.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/ReceiverSenderBuilder.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/Sender.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/Sender.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/Sender.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/Sender.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala similarity index 95% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala index e1d067002e..b28f5999da 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCConfiguration.scala @@ -18,15 +18,13 @@ package com.webank.wedatasphere.linkis.rpc.conf import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} -/** - * Created by enjoyyin on 2019/1/14. - */ + object RPCConfiguration { val BDP_RPC_BROADCAST_THREAD_SIZE = CommonVars("wds.linkis.rpc.broadcast.thread.num", new Integer(10)) val BDP_RPC_EUREKA_SERVICE_REFRESH_INTERVAL = CommonVars("wds.linkis.rpc.eureka.client.refresh.interval", new TimeType("1s")) - val BDP_RPC_EUREKA_SERVICE_REFRESH_MAX_WAIT_TIME = CommonVars("wds.linkis.rpc.eureka.client.refresh.wait.time.max", new TimeType("5s")) + val BDP_RPC_EUREKA_SERVICE_REFRESH_MAX_WAIT_TIME = CommonVars("wds.linkis.rpc.eureka.client.refresh.wait.time.max", new TimeType("1m")) val BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX = CommonVars("wds.linkis.rpc.receiver.asyn.consumer.thread.max", 10) val BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_FREE_TIME_MAX = CommonVars("wds.linkis.rpc.receiver.asyn.consumer.freeTime.max", new TimeType("2m")) val BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY = CommonVars("wds.linkis.rpc.receiver.asyn.queue.size.max", 1000) @@ -41,5 +39,5 @@ object RPCConfiguration { val BDP_RPC_INSTANCE_ALIAS_SERVICE_REFRESH_INTERVAL = CommonVars("wds.linkis.rpc.instancealias.refresh.interval", new TimeType("3s")) - val CONTEXT_SERVICE_APPLICATION_NAME = CommonVars("wds.linkis.gateway.conf.contextservice.name", "contextservice") + val CONTEXT_SERVICE_APPLICATION_NAME = CommonVars("wds.linkis.gateway.conf.contextservice.name", "linkis-ps-contextservice") } diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala similarity index 91% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala index b6a43a8f8d..cb19997336 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/conf/RPCSpringConfiguration.scala @@ -30,9 +30,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients import org.springframework.context.annotation.{Bean, Configuration} import org.springframework.context.event.EventListener -/** - * Created by enjoyyin on 2019/1/14. - */ + @Configuration @EnableFeignClients class RPCSpringConfiguration extends Logging { @@ -45,11 +43,12 @@ class RPCSpringConfiguration extends Logging { @EventListener def completeInitialize(applicationPreparedEvent: ApplicationPreparedEvent): Unit = { val restfulClasses = ServerConfiguration.BDP_SERVER_RESTFUL_REGISTER_CLASSES.getValue + val rpcRestfulName = applicationPreparedEvent.getApplicationContext.getBean(classOf[RPCReceiveRestful]).getClass.getName if(StringUtils.isEmpty(restfulClasses)) - DataWorkCloudApplication.setProperty(ServerConfiguration.BDP_SERVER_RESTFUL_REGISTER_CLASSES.key, classOf[RPCReceiveRestful].getName) + DataWorkCloudApplication.setProperty(ServerConfiguration.BDP_SERVER_RESTFUL_REGISTER_CLASSES.key, rpcRestfulName) else DataWorkCloudApplication.setProperty(ServerConfiguration.BDP_SERVER_RESTFUL_REGISTER_CLASSES.key, restfulClasses + - "," + classOf[RPCReceiveRestful].getName) + "," + rpcRestfulName) info("DataWorkCloud RPC need register RPCReceiveRestful, now add it to configuration.") } diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCRPCRetryException.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCRPCRetryException.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCRPCRetryException.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCRPCRetryException.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCURIException.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCURIException.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCURIException.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/DWCURIException.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/NoInstanceExistsException.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/NoInstanceExistsException.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/NoInstanceExistsException.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/NoInstanceExistsException.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/RPCInitFailedException.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/RPCInitFailedException.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/RPCInitFailedException.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/exception/RPCInitFailedException.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasConverter.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasConverter.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasConverter.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasConverter.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala similarity index 91% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala index 3a6b4a771c..dbe475f5ba 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/InstanceAliasManager.scala @@ -3,10 +3,6 @@ package com.webank.wedatasphere.linkis.rpc.instancealias import com.webank.wedatasphere.linkis.common.ServiceInstance import javax.annotation.Nullable -/** - * @Author alexyang - * @Date 2020/2/18 - */ trait InstanceAliasManager { def getAliasByServiceInstance(instance: ServiceInstance): String diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/DefaultInstanceAliasConverter.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/DefaultInstanceAliasConverter.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/DefaultInstanceAliasConverter.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/DefaultInstanceAliasConverter.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala similarity index 98% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala index 353f6a4c07..a46724277a 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/instancealias/impl/InstanceAliasManagerImpl.scala @@ -14,10 +14,6 @@ import org.springframework.stereotype.Component import scala.collection.JavaConversions._ -/** - * @Author alexyang - * @Date 2020/2/18 - */ @Component class InstanceAliasManagerImpl extends InstanceAliasManager with Logging { diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptor.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptor.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorChain.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorChain.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorChain.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorChain.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorExchange.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorExchange.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorExchange.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCInterceptorExchange.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCLoadBalancer.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCLoadBalancer.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCLoadBalancer.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCLoadBalancer.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCServerLoader.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCServerLoader.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCServerLoader.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/RPCServerLoader.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastRPCInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastRPCInterceptor.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastRPCInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastRPCInterceptor.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastSenderBuilder.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastSenderBuilder.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastSenderBuilder.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/BroadcastSenderBuilder.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala similarity index 75% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala index b5f67d974e..90a8b3a29d 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CacheableRPCInterceptor.scala @@ -16,18 +16,14 @@ package com.webank.wedatasphere.linkis.rpc.interceptor.common -import java.util.concurrent.{Callable, TimeUnit} +import java.util.concurrent.TimeUnit import com.google.common.cache.{Cache, CacheBuilder, RemovalListener, RemovalNotification} -import com.webank.wedatasphere.linkis.common.exception.WarnException import com.webank.wedatasphere.linkis.common.utils.Logging -import com.webank.wedatasphere.linkis.protocol.CacheableProtocol import com.webank.wedatasphere.linkis.rpc.interceptor.{RPCInterceptor, RPCInterceptorChain, RPCInterceptorExchange} import org.springframework.stereotype.Component -/** - * Created by enjoyyin on 2019/1/14. - */ + @Component class CacheableRPCInterceptor extends RPCInterceptor with Logging{ @@ -42,18 +38,18 @@ class CacheableRPCInterceptor extends RPCInterceptor with Logging{ override val order: Int = 10 override def intercept(interceptorExchange: RPCInterceptorExchange, chain: RPCInterceptorChain): Any = interceptorExchange.getProtocol match { - case cacheable: CacheableProtocol => - guavaCache.get(cacheable.toString, new Callable[Any] { - override def call(): Any = { - val returnMsg = chain.handle(interceptorExchange) - returnMsg match { - case warn: WarnException => - throw warn - case _ => - returnMsg - } - } - }) +// case cacheable: CacheableProtocol => +// guavaCache.get(cacheable.toString, new Callable[Any] { +// override def call(): Any = { +// val returnMsg = chain.handle(interceptorExchange) +// returnMsg match { +// case warn: WarnException => +// throw warn +// case _ => +// returnMsg +// } +// } +// }) case _ => chain.handle(interceptorExchange) } } diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CommonRPCInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CommonRPCInterceptor.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CommonRPCInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/CommonRPCInterceptor.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/InstanceRPCLoadBalancer.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/InstanceRPCLoadBalancer.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/InstanceRPCLoadBalancer.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/InstanceRPCLoadBalancer.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala similarity index 96% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala index 7a8e7841f6..d6a396123c 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/RetryableRPCInterceptor.scala @@ -22,16 +22,14 @@ import com.webank.wedatasphere.linkis.common.ServiceInstance import com.webank.wedatasphere.linkis.common.exception.DWCRetryException import com.webank.wedatasphere.linkis.common.utils.RetryHandler import com.webank.wedatasphere.linkis.protocol.RetryableProtocol -import com.webank.wedatasphere.linkis.rpc.exception.{DWCRPCRetryException, NoInstanceExistsException} +import com.webank.wedatasphere.linkis.rpc.exception.DWCRPCRetryException import com.webank.wedatasphere.linkis.rpc.interceptor.{RPCInterceptor, RPCInterceptorChain, RPCInterceptorExchange, ServiceInstanceRPCInterceptorChain} import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils import feign.RetryableException import org.apache.commons.lang.StringUtils import org.springframework.stereotype.Component -/** - * Created by enjoyyin on 2019/1/14. - */ + @Component class RetryableRPCInterceptor extends RPCInterceptor { override val order: Int = 20 diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/SingleInstanceRPCLoadBalancer.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/SingleInstanceRPCLoadBalancer.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/SingleInstanceRPCLoadBalancer.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/interceptor/common/SingleInstanceRPCLoadBalancer.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/FeignClientRequestInterceptor.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/FeignClientRequestInterceptor.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/FeignClientRequestInterceptor.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/FeignClientRequestInterceptor.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala similarity index 94% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala index 2fd1ce4763..eed683accb 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringCloudFeignConfigurationCache.scala @@ -17,21 +17,19 @@ package com.webank.wedatasphere.linkis.rpc.sender import com.webank.wedatasphere.linkis.DataWorkCloudApplication -import com.webank.wedatasphere.linkis.rpc.{RPCReceiveRestful, RPCSpringBeanCache, Receiver} +import com.webank.wedatasphere.linkis.rpc.{RPCReceiveRestful, Receiver} import feign.codec.{Decoder, Encoder} import feign.{Client, Contract} import javax.annotation.PostConstruct import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.{AutoConfigureAfter, AutoConfigureBefore} +import org.springframework.boot.autoconfigure.AutoConfigureBefore import org.springframework.cloud.client.discovery.DiscoveryClient import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory import org.springframework.cloud.netflix.ribbon.SpringClientFactory import org.springframework.cloud.openfeign.FeignClientsConfiguration import org.springframework.context.annotation.{Configuration, Import} -/** - * Created by enjoyyin on 2019/1/14. - */ + @Import(Array(classOf[FeignClientsConfiguration])) @Autowired @Configuration diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala similarity index 96% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala index 29d74a5d9a..42919a195b 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/SpringMVCRPCSender.scala @@ -24,7 +24,7 @@ import com.netflix.loadbalancer.reactive.LoadBalancerCommand import com.webank.wedatasphere.linkis.common.ServiceInstance import com.webank.wedatasphere.linkis.common.conf.{Configuration => DWCConfiguration} import com.webank.wedatasphere.linkis.protocol.Protocol -import com.webank.wedatasphere.linkis.rpc.interceptor.{BaseRPCInterceptorChain, RPCInterceptor, RPCLoadBalancer, ServiceInstanceRPCInterceptorChain} +import com.webank.wedatasphere.linkis.rpc.interceptor.{RPCInterceptor, RPCLoadBalancer, ServiceInstanceRPCInterceptorChain} import com.webank.wedatasphere.linkis.rpc.transform.RPCConsumer import com.webank.wedatasphere.linkis.rpc.{BaseRPCSender, RPCMessageEvent, RPCSpringBeanCache} import com.webank.wedatasphere.linkis.server.{BDPJettyServerHelper, Message} @@ -33,9 +33,7 @@ import org.apache.commons.lang.StringUtils import org.springframework.cloud.netflix.ribbon.ServerIntrospector import org.springframework.cloud.openfeign.ribbon.{CachingSpringLoadBalancerFactory, FeignLoadBalancer, LoadBalancerFeignClient} -/** - * Created by enjoyyin on 2018/8/28. - */ + private[rpc] class SpringMVCRPCSender private[rpc](private[rpc] val serviceInstance: ServiceInstance) extends BaseRPCSender(serviceInstance.getApplicationName) { diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala similarity index 93% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala index a3694b5460..4835480421 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/UnionSender.scala @@ -18,14 +18,11 @@ package com.webank.wedatasphere.linkis.rpc.sender import java.util -import com.webank.wedatasphere.linkis.rpc.Sender -import com.webank.wedatasphere.linkis.rpc.Receiver +import com.webank.wedatasphere.linkis.rpc.{Receiver, Sender} import scala.concurrent.duration.Duration -/** - * Created by enjoyyin on 2018/11/3. - */ + private class UnionSender private(receiver: Receiver, recycler: Receiver) extends Sender { override def ask(message: Any): Any = diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaClientRefreshUtils.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaClientRefreshUtils.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaClientRefreshUtils.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaClientRefreshUtils.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala similarity index 94% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala index 033a6318ac..b43db06904 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/sender/eureka/EurekaRPCServerLoader.scala @@ -16,7 +16,6 @@ package com.webank.wedatasphere.linkis.rpc.sender.eureka -import com.netflix.loadbalancer.{DynamicServerListLoadBalancer, ILoadBalancer} import com.webank.wedatasphere.linkis.common.ServiceInstance import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.rpc.conf.RPCConfiguration @@ -25,9 +24,7 @@ import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient.EurekaServ import scala.concurrent.duration.Duration -/** - * Created by enjoyyin on 2019/1/14. - */ + class EurekaRPCServerLoader extends AbstractRPCServerLoader { override def refreshAllServers(): Unit = Utils.tryAndWarn(EurekaClientRefreshUtils().refreshEurekaClient()) diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala similarity index 91% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala index dbefa9af38..5f4bc84ff3 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/JavaCollectionSerializer.scala @@ -17,16 +17,14 @@ package com.webank.wedatasphere.linkis.rpc.transform import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper -import org.json4s.{CustomSerializer, JArray, JObject} -import org.json4s.jackson.Serialization.write import org.json4s.jackson.JsonMethods.parse +import org.json4s.jackson.Serialization.write +import org.json4s.{CustomSerializer, JArray, JObject} //TODO is now only the simplest implementation, and there is a need to optimize it later.(TODO 现在只做最简单的实现,后续有需要再优化) -/** - * Created by enjoyyin on 2018/10/27. - */ + object JavaCollectionSerializer extends CustomSerializer[java.util.List[_]](implicit formats => ( { - case j: JArray=> BDPJettyServerHelper.gson.fromJson(write(j), classOf[java.util.List[_]]) + case j: JArray => BDPJettyServerHelper.gson.fromJson(write(j), classOf[java.util.List[_]]) }, { case list: java.util.List[_] => parse(BDPJettyServerHelper.gson.toJson(list)) } diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala similarity index 86% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala index dba8f1052e..6042e57b6c 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCConsumer.scala @@ -19,15 +19,12 @@ package com.webank.wedatasphere.linkis.rpc.transform import com.webank.wedatasphere.linkis.common.exception.ExceptionManager import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException -import com.webank.wedatasphere.linkis.server.{BDPJettyServerHelper, JMap, Message, EXCEPTION_MSG} -import org.json4s.jackson.Serialization +import com.webank.wedatasphere.linkis.rpc.serializer.ProtostuffSerializeUtil +import com.webank.wedatasphere.linkis.server.{EXCEPTION_MSG, JMap, Message} -import scala.reflect.ManifestFactory import scala.runtime.BoxedUnit -/** - * Created by enjoyyin on 2018/9/13. - */ + private[linkis] trait RPCConsumer { def toObject(message: Message): Any @@ -43,7 +40,7 @@ private[linkis] object RPCConsumer { if(data.isEmpty) return BoxedUnit.UNIT val objectStr = data.get(OBJECT_VALUE).toString val objectClass = data.get(CLASS_VALUE).toString - val clazz = Utils.tryThrow(Class.forName(objectClass)){ + val clazz = Utils.tryThrow(Class.forName(objectClass)) { case _: ClassNotFoundException => new DWCURIException(10003, s"The corresponding anti-sequence class $objectClass was not found.(找不到对应的反序列类$objectClass.)") case t: ExceptionInInitializerError => @@ -52,12 +49,14 @@ private[linkis] object RPCConsumer { exception case t: Throwable => t } - if(data.get(IS_SCALA_CLASS).toString.toBoolean) { +// if (null != data.get(IS_REQUEST_PROTOCOL_CLASS) && data.get(IS_REQUEST_PROTOCOL_CLASS).toString.toBoolean) { + ProtostuffSerializeUtil.deserialize(objectStr, clazz) + /*} else if (data.get(IS_SCALA_CLASS).toString.toBoolean) { val realClass = getSerializableScalaClass(clazz) Serialization.read(objectStr)(formats, ManifestFactory.classType(realClass)) } else { BDPJettyServerHelper.gson.fromJson(objectStr, clazz) - } + }*/ case 4 => val errorMsg = message.getData.get(EXCEPTION_MSG).asInstanceOf[JMap[String, Object]] ExceptionManager.generateException(errorMsg) diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCFormats.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCFormats.scala similarity index 100% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCFormats.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCFormats.scala diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala similarity index 80% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala index 6323bc7dc2..f363872ffe 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/transform/RPCProduct.scala @@ -21,17 +21,16 @@ import java.util import com.webank.wedatasphere.linkis.DataWorkCloudApplication import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException -import com.webank.wedatasphere.linkis.server.{BDPJettyServerHelper, EXCEPTION_MSG, Message} +import com.webank.wedatasphere.linkis.rpc.serializer.ProtostuffSerializeUtil +import com.webank.wedatasphere.linkis.server.{EXCEPTION_MSG, Message} import org.apache.commons.lang.ClassUtils -import org.json4s.jackson.Serialization import org.json4s.{DefaultFormats, Formats, Serializer} import scala.collection.JavaConversions -/** - * Created by enjoyyin on 2018/9/13. - */ + private[linkis] trait RPCProduct { def toMessage(t: Any): Message @@ -42,6 +41,8 @@ private[linkis] trait RPCProduct { } private[linkis] object RPCProduct extends Logging { + + private[rpc] val IS_REQUEST_PROTOCOL_CLASS = "rpc_is_request_protocol" private[rpc] val IS_SCALA_CLASS = "rpc_is_scala_class" private[rpc] val CLASS_VALUE = "rpc_object_class" private[rpc] val OBJECT_VALUE = "rpc_object_value" @@ -49,20 +50,26 @@ private[linkis] object RPCProduct extends Logging { private var serializerClasses: List[Class[_]] = List.empty private val rpcProduct: RPCProduct = new RPCProduct { private val rpcFormats = DataWorkCloudApplication.getApplicationContext.getBeansOfType(classOf[RPCFormats]) - if(rpcFormats != null && !rpcFormats.isEmpty) { + if (rpcFormats != null && !rpcFormats.isEmpty) { val serializers = JavaConversions.mapAsScalaMap(rpcFormats).map(_._2.getSerializers).toArray.flatMap(_.iterator) setFormats(serializers) } override def toMessage(t: Any): Message = { - if(t == null) throw new DWCURIException(10001, "The transmitted bean is Null.(传输的bean为Null.)") + if (t == null) throw new DWCURIException(10001, "The transmitted bean is Null.(传输的bean为Null.)") val message = Message.ok("RPC Message.") - if(isScalaClass(t)){ + if (isRequestProtocol(t)) { + message.data(IS_REQUEST_PROTOCOL_CLASS, "true") + } else { + message.data(IS_REQUEST_PROTOCOL_CLASS, "false") + } + message.data(OBJECT_VALUE, ProtostuffSerializeUtil.serialize(t)) + /*} else if (isScalaClass(t)) { message.data(IS_SCALA_CLASS, "true") message.data(OBJECT_VALUE, Serialization.write(t.asInstanceOf[AnyRef])) } else { message.data(IS_SCALA_CLASS, "false") message.data(OBJECT_VALUE, BDPJettyServerHelper.gson.toJson(t)) - } + }*/ message.setMethod("/rpc/message") message.data(CLASS_VALUE, t.getClass.getName) } @@ -86,19 +93,25 @@ private[linkis] object RPCProduct extends Logging { info("RPC Serializers: " + this.formats.customSerializers.map(_.getClass.getSimpleName) + ", serializerClasses: " + "" + serializerClasses) } + private def getActualTypeClass(classType: Type): Class[_] = classType match { case p: ParameterizedType => val params = p.getActualTypeArguments - if(params == null || params.isEmpty) null + if (params == null || params.isEmpty) null else getActualTypeClass(params(0)) case c: Class[_] => c case _ => null } + + private[rpc] def isRequestProtocol(obj: Any): Boolean = obj.isInstanceOf[RequestProtocol] + private[rpc] def isScalaClass(obj: Any): Boolean = (obj.isInstanceOf[Product] && obj.isInstanceOf[Serializable]) || serializerClasses.exists(ClassUtils.isAssignable(obj.getClass, _)) || - obj.getClass.getName.startsWith("scala.") + obj.getClass.getName.startsWith("scala.") + private[rpc] def getSerializableScalaClass(clazz: Class[_]): Class[_] = serializerClasses.find(ClassUtils.isAssignable(clazz, _)).getOrElse(clazz) + def getRPCProduct: RPCProduct = rpcProduct } \ No newline at end of file diff --git a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala similarity index 79% rename from core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala rename to linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala index cd50461060..efa3e3ba2f 100644 --- a/core/cloudRPC/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala +++ b/linkis-commons/linkis-rpc/src/main/scala/com/webank/wedatasphere/linkis/rpc/utils/RPCUtils.scala @@ -20,15 +20,16 @@ import java.lang.reflect.UndeclaredThrowableException import java.net.ConnectException import com.netflix.client.ClientException +import com.webank.wedatasphere.linkis.common.ServiceInstance import com.webank.wedatasphere.linkis.rpc.exception.NoInstanceExistsException -import com.webank.wedatasphere.linkis.rpc.sender.SpringCloudFeignConfigurationCache +import com.webank.wedatasphere.linkis.rpc.sender.{SpringCloudFeignConfigurationCache, SpringMVCRPCSender} +import com.webank.wedatasphere.linkis.rpc.{BaseRPCSender, Sender} import feign.RetryableException import org.apache.commons.lang.StringUtils + import scala.collection.JavaConversions._ -/** - * Created by enjoyyin on 2019/2/22. - */ + object RPCUtils { def isReceiverNotExists(t: Throwable): Boolean = t match { @@ -59,4 +60,16 @@ object RPCUtils { else if(services.length > 1) tooManyDeal(services) else None } + + def getServiceInstanceFromSender(sender: Sender): ServiceInstance = { + sender match { + case springMVCRPCSender: SpringMVCRPCSender => + springMVCRPCSender.serviceInstance + case baseRPCSender: BaseRPCSender => + ServiceInstance(baseRPCSender.getApplicationName, null) + case _ => + null + } + } + } diff --git a/core/cloudRPC/src/test/scala/com/webank/wedatasphere/linkis/rpc/RPCFormatsTest.scala b/linkis-commons/linkis-rpc/src/test/scala/com/webank/wedatasphere/linkis/rpc/RPCFormatsTest.scala similarity index 100% rename from core/cloudRPC/src/test/scala/com/webank/wedatasphere/linkis/rpc/RPCFormatsTest.scala rename to linkis-commons/linkis-rpc/src/test/scala/com/webank/wedatasphere/linkis/rpc/RPCFormatsTest.scala diff --git a/linkis-commons/linkis-scheduler/pom.xml b/linkis-commons/linkis-scheduler/pom.xml new file mode 100644 index 0000000000..5c0a43f0d9 --- /dev/null +++ b/linkis-commons/linkis-scheduler/pom.xml @@ -0,0 +1,63 @@ + + + + + 4.0.0 + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + linkis-scheduler + + + + com.webank.wedatasphere.linkis + linkis-common + provided + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/AbstractScheduler.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/AbstractScheduler.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/AbstractScheduler.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/AbstractScheduler.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala similarity index 92% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala index 4ce1971b07..47de3afa0b 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/Scheduler.scala @@ -17,13 +17,11 @@ package com.webank.wedatasphere.linkis.scheduler import com.webank.wedatasphere.linkis.common.utils.Logging -import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEvent} +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEvent import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOScheduler import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler -/** - * Created by enjoyyin on 2018/9/1. - */ + abstract class Scheduler { def init(): Unit def start(): Unit diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/SchedulerContext.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/SchedulerContext.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/SchedulerContext.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/SchedulerContext.scala diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/conf/SchedulerConfiguration.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/conf/SchedulerConfiguration.scala new file mode 100644 index 0000000000..7ec0e1cd6c --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/conf/SchedulerConfiguration.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + +object SchedulerConfiguration { + + val FIFO_CONSUMER_AUTO_CLEAR_ENABLED = CommonVars("wds.linkis.fifo.consumer.auto.clear.enabled", true) + + val FIFO_CONSUMER_MAX_IDLE_TIME = CommonVars("wds.linkis.fifo.consumer.max.idle.time", new TimeType("2h")).getValue.toLong + + val FIFO_CONSUMER_IDLE_SCAN_INTERVAL = CommonVars("wds.linkis.fifo.consumer.idle.scan.interval", new TimeType("6h")) + + val FIFO_CONSUMER_IDLE_SCAN_INIT_TIME = CommonVars("wds.linkis.fifo.consumer.idle.scan.init.time", new TimeType("1s")) + + +} diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/LogEvent.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/LogEvent.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/LogEvent.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/LogEvent.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/ScheduleEvent.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/ScheduleEvent.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/ScheduleEvent.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/ScheduleEvent.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/SchedulerEventListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/SchedulerEventListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/SchedulerEventListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/event/SchedulerEventListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/DWCJobRetryException.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/DWCJobRetryException.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/DWCJobRetryException.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/DWCJobRetryException.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/SchedulerErrorException.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/SchedulerErrorException.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/SchedulerErrorException.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/SchedulerErrorException.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/WaitForNextAskExecutorException.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/WaitForNextAskExecutorException.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/WaitForNextAskExecutorException.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/exception/WaitForNextAskExecutorException.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala similarity index 85% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala index 74300adab0..6fd3093603 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/AbstractExecutor.scala @@ -21,34 +21,34 @@ import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorExceptio import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorState._ import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener -/** - * Created by enjoyyin on 2018/9/20. - */ + abstract class AbstractExecutor(id: Long) extends Executor with Logging { private var _state: ExecutorState = Starting private var lastActivityTime = System.currentTimeMillis private var executorListener: Option[ExecutorListener] = None + def setExecutorListener(executorListener: ExecutorListener): Unit = this.executorListener = Some(executorListener) protected def callback(): Unit protected def isIdle = _state == Idle + protected def isBusy = _state == Busy protected def whenBusy[A](f: => A) = whenState(Busy, f) protected def whenIdle[A](f: => A) = whenState(Idle, f) - protected def whenState[A](state: ExecutorState, f: => A) = if(_state == state) f + protected def whenState[A](state: ExecutorState, f: => A) = if (_state == state) f protected def ensureBusy[A](f: => A): A = { lastActivityTime = System.currentTimeMillis - if(_state == Busy) synchronized { + if (_state == Busy) synchronized { if (_state == Busy) return f } - throw new SchedulerErrorException(20001, "%s is in state %s." format (toString, _state)) + throw new SchedulerErrorException(20001, "%s is in state %s." format(toString, _state)) } protected def ensureIdle[A](f: => A): A = ensureIdle(f, true) @@ -56,25 +56,25 @@ abstract class AbstractExecutor(id: Long) extends Executor with Logging { protected def ensureIdle[A](f: => A, transitionState: Boolean): A = { if (_state == Idle) synchronized { if (_state == Idle) { - if(transitionState) transition(Busy) - return Utils.tryFinally(f){ - if(transitionState) transition(Idle) + if (transitionState) transition(Busy) + return Utils.tryFinally(f) { + if (transitionState) transition(Idle) callback() } } } - throw new SchedulerErrorException(20001, "%s is in state %s." format (toString, _state)) + throw new SchedulerErrorException(20001, "%s is in state %s." format(toString, _state)) } protected def ensureAvailable[A](f: => A): A = { - if(ExecutorState.isAvailable(_state)) synchronized { - if(ExecutorState.isAvailable(_state)) return Utils.tryFinally(f)(callback()) + if (ExecutorState.isAvailable(_state)) synchronized { + if (ExecutorState.isAvailable(_state)) return Utils.tryFinally(f)(callback()) } - throw new SchedulerErrorException(20001, "%s is in state %s." format (toString, _state)) + throw new SchedulerErrorException(20001, "%s is in state %s." format(toString, _state)) } protected def whenAvailable[A](f: => A): A = { - if(ExecutorState.isAvailable(_state)) return Utils.tryFinally(f)(callback()) + if (ExecutorState.isAvailable(_state)) return Utils.tryFinally(f)(callback()) throw new SchedulerErrorException(20001, "%s is in state %s." format (toString, _state)) } @@ -107,4 +107,7 @@ abstract class AbstractExecutor(id: Long) extends Executor with Logging { override def getExecutorInfo: ExecutorInfo = ExecutorInfo(id, _state) def getLastActivityTime = lastActivityTime + + def setLastActivityTime(lastActivityTime:Long):Unit = this.lastActivityTime = lastActivityTime + } diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskInfoSupport.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskInfoSupport.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskInfoSupport.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskInfoSupport.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskOperateSupport.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskOperateSupport.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskOperateSupport.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ConcurrentTaskOperateSupport.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala similarity index 83% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala index 0228257dd7..e539f9cee6 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteRequest.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.scheduler.executer -/** - * Created by enjoyyin on 2018/8/31. - */ + trait ExecuteRequest { val code: String } @@ -27,4 +25,10 @@ trait JobExecuteRequest { } trait RunTypeExecuteRequest{ val runType:String +} +trait PythonExecuteRequest{ + val sparkPythonVersion:String + val sparkPythonExtraPackage:String + val pythonVersion:String + val pythonExtraPackage:String } \ No newline at end of file diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala new file mode 100644 index 0000000000..595b91bac1 --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecuteResponse.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.executer + + +trait ExecuteResponse +trait CompletedExecuteResponse extends ExecuteResponse +case class SuccessExecuteResponse() extends CompletedExecuteResponse + +trait OutputExecuteResponse extends ExecuteResponse { + def getOutput: String +} + +case class AliasOutputExecuteResponse(alias: String, output: String) extends OutputExecuteResponse { + override def getOutput: String = output +} + +case class ErrorExecuteResponse(message: String, t: Throwable) extends CompletedExecuteResponse + +case class IncompleteExecuteResponse(message: String) extends ExecuteResponse + +case class SubmitResponse(taskId: String) extends ExecuteResponse + +trait AsynReturnExecuteResponse extends ExecuteResponse { + def notify(rs: ExecuteResponse => Unit): Unit +} \ No newline at end of file diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala new file mode 100644 index 0000000000..99eddc15fe --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/Executor.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.executer + +import java.io.Closeable + +import com.webank.wedatasphere.linkis.protocol.engine.EngineState + + +trait Executor extends Closeable { + + def getId: Long + def execute(executeRequest: ExecuteRequest): ExecuteResponse + + def state: ExecutorState.ExecutorState + + def getExecutorInfo: ExecutorInfo +} +object ExecutorState { + type ExecutorState = EngineState + val Starting = EngineState.Starting + val Idle = EngineState.Idle + val Busy = EngineState.Busy + val ShuttingDown = EngineState.ShuttingDown + val Error = EngineState.Error + val Dead = EngineState.Dead + val Success = EngineState.Success + + def apply(x: Int): ExecutorState = EngineState.values()(x) + + def isCompleted(state: ExecutorState) = EngineState.isCompleted(state.asInstanceOf[EngineState]) + + def isAvailable(state: ExecutorState) = EngineState.isAvailable(state.asInstanceOf[EngineState]) +} \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorInfo.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorInfo.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorInfo.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorInfo.scala diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala new file mode 100644 index 0000000000..aee8f6e690 --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/ExecutorManager.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.executer + +import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEvent + +import scala.concurrent.duration.Duration + + +abstract class ExecutorManager { + + def setExecutorListener(engineListener: ExecutorListener): Unit + + protected def createExecutor(event: SchedulerEvent): Executor + + def askExecutor(event: SchedulerEvent): Option[Executor] + + def askExecutor(event: SchedulerEvent, wait: Duration): Option[Executor] + + def getById(id: Long): Option[Executor] + + def getByGroup(groupName: String): Array[Executor] + + def delete(executor: Executor): Unit + + def shutdown(): Unit + +} \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala similarity index 94% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala index f4eba381a3..229a892f8d 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskInfoSupport.scala @@ -18,9 +18,7 @@ package com.webank.wedatasphere.linkis.scheduler.executer import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo -/** - * Created by enjoyyin on 2018/10/30. - */ + trait SingleTaskInfoSupport { def progress(): Float diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskOperateSupport.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskOperateSupport.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskOperateSupport.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/executer/SingleTaskOperateSupport.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFuture.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFuture.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFuture.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFuture.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFutureTask.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFutureTask.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFutureTask.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/future/BDPFutureTask.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ConsumerListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ConsumerListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ConsumerListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ConsumerListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala similarity index 79% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala index 146989011a..a3032d42b1 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ExecutorListener.scala @@ -16,14 +16,14 @@ package com.webank.wedatasphere.linkis.scheduler.listener +import com.webank.wedatasphere.linkis.protocol.engine.EngineState import com.webank.wedatasphere.linkis.scheduler.executer.Executor -import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorState._ -/** - * Created by enjoyyin on 2018/9/3. - */ + trait ExecutorListener extends SchedulerListener { def onExecutorCreated(executor: Executor): Unit + def onExecutorCompleted(executor: Executor, message: String): Unit - def onExecutorStateChanged(executor: Executor, fromState: ExecutorState, toState: ExecutorState): Unit + + def onExecutorStateChanged(executor: Executor, fromState: EngineState, toState: EngineState): Unit } \ No newline at end of file diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/JobListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/JobListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/JobListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/JobListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/LogListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/LogListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/LogListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/LogListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ProgressListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ProgressListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ProgressListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/ProgressListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/SchedulerListener.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/SchedulerListener.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/SchedulerListener.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/listener/SchedulerListener.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/AbstractGroup.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/AbstractGroup.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/AbstractGroup.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/AbstractGroup.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumeQueue.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumeQueue.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumeQueue.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumeQueue.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala similarity index 92% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala index e456e952d3..4a0b313ba6 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Consumer.scala @@ -18,12 +18,10 @@ package com.webank.wedatasphere.linkis.scheduler.queue import java.util.concurrent.ExecutorService -import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.scheduler.SchedulerContext -/** - * Created by enjoyyin on 2018/8/31. - */ + abstract class Consumer(schedulerContext: SchedulerContext, executeService: ExecutorService) extends Runnable with Logging { diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumerManager.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumerManager.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumerManager.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/ConsumerManager.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Group.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Group.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Group.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Group.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/GroupFactory.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/GroupFactory.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/GroupFactory.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/GroupFactory.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala similarity index 96% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala index 284584928d..27f3133dd8 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/Job.scala @@ -34,13 +34,11 @@ import org.apache.commons.lang.StringUtils import org.apache.commons.lang.exception.ExceptionUtils -/** - * Created by enjoyyin on 2018/8/31. - */ + abstract class Job extends Runnable with SchedulerEvent with Closeable with Logging { import SchedulerEventState._ - private[queue] var future: Future[_] = _ + private[linkis] var future: Future[_] = _ /** * the future of consumer */ @@ -52,10 +50,10 @@ abstract class Job extends Runnable with SchedulerEvent with Closeable with Logg private var jobListener: Option[JobListener] = None private var logListener: Option[LogListener] = None private var progressListener: Option[ProgressListener] = None - private var interrupt = false + private[linkis] var interrupt = false private var progress: Float = 0f private var retryNum = 0 - private var errorExecuteResponse: ErrorExecuteResponse = _ + private[linkis] var errorExecuteResponse: ErrorExecuteResponse = _ override def isWaiting = super.isWaiting && !interrupt override def isCompleted = super.isCompleted || interrupt @@ -124,7 +122,7 @@ abstract class Job extends Runnable with SchedulerEvent with Closeable with Logg * updated by enjoyyin * After some jobs call kill, they cannot be killed correctly, causing the state to not be flipped.(一些job调用kill之后,不能被正确kill,导致状态不能翻转) */ - private def forceCancel(t:Throwable):Unit = { + protected def forceCancel(t: Throwable): Unit = { logger.info(s"force to cancel job $getName") val executeCompleted = ErrorExecuteResponse("force to transition Failed", t) transitionCompleted(executeCompleted) @@ -162,17 +160,25 @@ abstract class Job extends Runnable with SchedulerEvent with Closeable with Logg def getErrorResponse = errorExecuteResponse protected def existsJobDaemon: Boolean = false + protected def createJobDaemon: JobDaemon = new JobDaemon(this, jobDaemonUpdateInterval, executor) + protected def jobDaemonUpdateInterval: Long = 1000l + override def beforeStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = toState match { + case Succeed | Failed | Cancelled | Timeout => + jobListener.foreach(_.onJobCompleted(this)) + case _ => + } + override def afterStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = toState match { case Inited => jobListener.foreach(_.onJobInited(this)) //TODO Add event(加事件) case Scheduled => jobListener.foreach(_.onJobScheduled(this)) - // logListener.foreach(_.onLogUpdate(this, "job is scheduled.")) - //TODO Add event(加事件) + // logListener.foreach(_.onLogUpdate(this, "job is scheduled.")) + //TODO Add event(加事件) case Running => jobListener.foreach(_.onJobRunning(this)) //logListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo( "job is running."))) diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala similarity index 93% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala index 48e0825da5..29b37e196d 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/JobInfo.scala @@ -16,8 +16,6 @@ package com.webank.wedatasphere.linkis.scheduler.queue -import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState.SchedulerEventState - /** * Created by enjoyyin on 2018/9/4. * JobInfo Is the job information that the server sends to the front end.(是服务端传给前端的job信息) diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LockJob.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LockJob.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LockJob.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LockJob.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LoopArrayQueue.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LoopArrayQueue.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LoopArrayQueue.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/LoopArrayQueue.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala similarity index 92% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala index cbfe3632df..ffd6cd7573 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEvent.scala @@ -20,9 +20,7 @@ import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState._ -/** - * Created by enjoyyin on 2018/9/17. - */ + trait SchedulerEvent extends Logging { private[queue] var id: String = _ @@ -58,19 +56,26 @@ trait SchedulerEvent extends Logging { def cancel() = transition(Cancelled) def isWaiting = state == Inited + def isScheduled = state == Scheduled + def isRunning = state == Running + def isCompleted = SchedulerEventState.isCompleted(state) + def isSucceed: Boolean = SchedulerEventState.isSucceed(state) + def isWaitForRetry: Boolean = state == WaitForRetry def getState = state def afterStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit + def beforeStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = {} + protected def transition(state: SchedulerEventState): Unit = synchronized { - if(state.id < this.state.id && state != WaitForRetry) - throw new SchedulerErrorException(12000, s"Task status flip error! Cause: Failed to flip from ${this.state} to $state.(任务状态翻转出错!原因:不允许从${this.state} 翻转为$state.)")//抛异常 + if (state.id < this.state.id && state != WaitForRetry) + throw new SchedulerErrorException(12000, s"Task status flip error! Cause: Failed to flip from ${this.state} to $state.(任务状态翻转出错!原因:不允许从${this.state} 翻转为$state.)") //抛异常 info(s"$toString change state ${this.state} => $state.") val oldState = this.state this.state = state diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEventState.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEventState.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEventState.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/SchedulerEventState.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/UserJob.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/UserJob.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/UserJob.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/UserJob.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOConsumerManager.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOConsumerManager.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOConsumerManager.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOConsumerManager.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroup.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroup.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroup.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroup.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala similarity index 95% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala index 1e28644131..30f6140a42 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOGroupFactory.scala @@ -16,13 +16,11 @@ package com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue -import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, Job, SchedulerEvent} +import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, SchedulerEvent} import scala.collection.mutable -/** - * Created by enjoyyin on 2018/9/12. - */ + class FIFOGroupFactory extends GroupFactory { private val groupMap = new mutable.HashMap[String, Group]() diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala similarity index 89% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala index a4c27cd6cb..85f0ac7402 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOScheduler.scala @@ -17,13 +17,10 @@ package com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.scheduler.{AbstractScheduler, Scheduler, SchedulerContext} import com.webank.wedatasphere.linkis.scheduler.queue._ +import com.webank.wedatasphere.linkis.scheduler.{AbstractScheduler, SchedulerContext} + -/** - * Created by enjoyyin on 2018/9/13. - */ class FIFOScheduler(val schedulerContext: SchedulerContext) extends AbstractScheduler { private var consumerManager: ConsumerManager = _ diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOSchedulerContextImpl.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOSchedulerContextImpl.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOSchedulerContextImpl.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOSchedulerContextImpl.scala diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala new file mode 100644 index 0000000000..3fa6fc56e2 --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala @@ -0,0 +1,178 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue + + + +import java.util.concurrent.{ExecutorService, Future} + +import com.webank.wedatasphere.linkis.common.exception.{ErrorException, WarnException} +import com.webank.wedatasphere.linkis.common.log.LogUtils +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.scheduler.SchedulerContext +import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException +import com.webank.wedatasphere.linkis.scheduler.executer.Executor +import com.webank.wedatasphere.linkis.scheduler.future.{BDPFuture, BDPFutureTask} +import com.webank.wedatasphere.linkis.scheduler.queue._ + +import scala.beans.BeanProperty +import scala.collection.mutable.ArrayBuffer +import scala.concurrent.TimeoutException + +class FIFOUserConsumer(schedulerContext: SchedulerContext, + executeService: ExecutorService, private var group: Group) extends Consumer(schedulerContext, executeService) { + private var fifoGroup = group.asInstanceOf[FIFOGroup] + private var queue: ConsumeQueue = _ + private val maxRunningJobsNum = fifoGroup.getMaxRunningJobs + private val runningJobs = new Array[Job](maxRunningJobsNum) + private var future: Future[_] = _ + + private var bdpFutureTask: BDPFuture = _ + + @BeanProperty + var lastTime: Long = _ + + def this(schedulerContext: SchedulerContext,executeService: ExecutorService) = { + this(schedulerContext,executeService, null) + } + + def start(): Unit = { + future = executeService.submit(this) + bdpFutureTask = new BDPFutureTask(this.future) + } + + override def setConsumeQueue(consumeQueue: ConsumeQueue) = { + queue = consumeQueue + } + + override def getConsumeQueue = queue + + override def getGroup = fifoGroup + + override def setGroup(group: Group) = { + this.fifoGroup = group.asInstanceOf[FIFOGroup] + } + + override def getRunningEvents = getEvents(e => e.isRunning || e.isWaitForRetry) + + private def getEvents(op: SchedulerEvent => Boolean): Array[SchedulerEvent] = { + val result = ArrayBuffer[SchedulerEvent]() + runningJobs.filter(_ != null).filter(x => op(x)).foreach(result += _) + result.toArray + } + + override def run() = { + Thread.currentThread().setName(s"${toString}Thread") + info(s"$toString thread started!") + while (!terminate) { + Utils.tryAndError(loop()) + Utils.tryAndError(Thread.sleep(10)) + } + info(s"$toString thread stopped!") + } + + protected def askExecutorGap(): Unit = {} + + protected def loop(): Unit = { + var isRetryJob = false + def getWaitForRetryEvent: Option[SchedulerEvent] = { + val waitForRetryJobs = runningJobs.filter(job => job != null && job.isJobCanRetry) + waitForRetryJobs.find{job => + isRetryJob = Utils.tryCatch(job.turnToRetry()){ t => + job.onFailure("Job state flipped to Scheduled failed in Retry(Retry时,job状态翻转为Scheduled失败)!", t) + false + } + isRetryJob + } + } + var event: Option[SchedulerEvent] = getWaitForRetryEvent + if(event.isEmpty) { + val completedNums = runningJobs.filter(e => e == null || e.isCompleted) + if (completedNums.length < 1) { + Utils.tryQuietly(Thread.sleep(1000)) //TODO 还可以优化,通过实现JobListener进行优化 + return + } + while(event.isEmpty) { + val takeEvent = if(getRunningEvents.isEmpty) Option(queue.take()) else queue.take(3000) + event = if(takeEvent.exists(e => Utils.tryCatch(e.turnToScheduled()) {t => + takeEvent.get.asInstanceOf[Job].onFailure("Job状态翻转为Scheduled失败!", t) + false + })) takeEvent else getWaitForRetryEvent + } + } + event.foreach { case job: Job => + Utils.tryCatch { + val (totalDuration, askDuration) = (fifoGroup.getMaxAskExecutorDuration, fifoGroup.getAskExecutorInterval) + var executor: Option[Executor] = None + job.consumerFuture = bdpFutureTask + Utils.waitUntil(() => { + executor = Utils.tryCatch(schedulerContext.getOrCreateExecutorManager.askExecutor(job, askDuration)) { + case warn: WarnException => + job.getLogListener.foreach(_.onLogUpdate(job, LogUtils.generateWarn(warn.getDesc))) + None + case e: ErrorException => + job.getLogListener.foreach(_.onLogUpdate(job, LogUtils.generateERROR(e.getMessage))) + throw e + case error: Throwable => + job.getLogListener.foreach(_.onLogUpdate(job, LogUtils.generateERROR(error.getMessage))) + throw error + } + Utils.tryQuietly(askExecutorGap()) + executor.isDefined + }, totalDuration) + job.consumerFuture = null + executor.foreach { executor => + job.setExecutor(executor) + job.future = executeService.submit(job) + job.getJobDaemon.foreach(jobDaemon => jobDaemon.future = executeService.submit(jobDaemon)) + if(!isRetryJob) putToRunningJobs(job) + } + }{ + case _: TimeoutException => + warn(s"Ask executor for Job $job timeout!") + job.onFailure("The request engine times out and the cluster cannot provide enough resources(请求引擎超时,集群不能提供足够的资源).", + new SchedulerErrorException(11055, "Insufficient resources, requesting available engine timeout(资源不足,请求可用引擎超时)!")) + case error: Throwable => + job.onFailure("请求引擎失败,可能是由于后台进程错误!请联系管理员", error) + if(job.isWaitForRetry) { + warn(s"Ask executor for Job $job failed, wait for the next retry!", error) + if(!isRetryJob) putToRunningJobs(job) + } else warn(s"Ask executor for Job $job failed!", error) + } + } + } + + private def putToRunningJobs(job: Job): Unit = { + val index = runningJobs.indexWhere(f => f == null || f.isCompleted) + runningJobs(index) = job + } + + override def shutdown() = { + future.cancel(true) + super.shutdown() + } + + /** + * Determine whether the consumer is idle, by determining whether the queue and running job are empty + * @return + */ + def isIdle: Boolean = { + info(s"${getGroup.getGroupName} queue isEmpty:${queue.isEmpty},size ${queue.size}") + info(s"${getGroup.getGroupName} running jobs is not empty:${this.runningJobs.exists(job => job !=null && ! job.isCompleted)}") + this.queue.peek.isEmpty && ! this.runningJobs.exists(job => job !=null && ! job.isCompleted) + } +} \ No newline at end of file diff --git a/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala new file mode 100644 index 0000000000..ac0fe0e6f9 --- /dev/null +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelConsumerManager.scala @@ -0,0 +1,109 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue + +import java.util.concurrent.{ExecutorService, TimeUnit} + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.scheduler.conf.SchedulerConfiguration +import com.webank.wedatasphere.linkis.scheduler.listener.ConsumerListener +import com.webank.wedatasphere.linkis.scheduler.queue._ +import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer + +import scala.collection.mutable + + +class ParallelConsumerManager(maxParallelismUsers: Int) extends ConsumerManager with Logging{ + + private val UJES_CONTEXT_CONSTRUCTOR_LOCK = new Object() + + private val CONSUMER_LOCK = new Object() + + private var consumerListener: Option[ConsumerListener] = None + + private var executorService: ExecutorService = _ + + private val consumerGroupMap = new mutable.HashMap[String, FIFOUserConsumer]() + + /** + * Clean up idle consumers regularly + */ + if (SchedulerConfiguration.FIFO_CONSUMER_AUTO_CLEAR_ENABLED.getValue) { + info("The feature that auto Clean up idle consumers is enabled ") + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = CONSUMER_LOCK.synchronized { + info("Start to Clean up idle consumers ") + val nowTime = System.currentTimeMillis() + consumerGroupMap.values.filter(_.isIdle) + .filter(consumer => nowTime - consumer.getLastTime > SchedulerConfiguration.FIFO_CONSUMER_MAX_IDLE_TIME) + .foreach(consumer => destroyConsumer(consumer.getGroup.getGroupName)) + info(s"Finished to Clean up idle consumers,cost ${System.currentTimeMillis() - nowTime} ms ") + } + }, + SchedulerConfiguration.FIFO_CONSUMER_IDLE_SCAN_INIT_TIME.getValue.toLong, + SchedulerConfiguration.FIFO_CONSUMER_IDLE_SCAN_INTERVAL.getValue.toLong, TimeUnit.MILLISECONDS) + } + + override def setConsumerListener(consumerListener: ConsumerListener) = { + this.consumerListener = Some(consumerListener) + } + + override def getOrCreateExecutorService = if(executorService != null) executorService + else UJES_CONTEXT_CONSTRUCTOR_LOCK.synchronized { + if (executorService == null) { + executorService = Utils.newCachedThreadPool(5 * maxParallelismUsers + 1, "Engine-Scheduler-ThreadPool-", true) + } + executorService + } + + override def getOrCreateConsumer(groupName: String) = CONSUMER_LOCK.synchronized { + val consumer = if (consumerGroupMap.contains(groupName)) consumerGroupMap(groupName) + else UJES_CONTEXT_CONSTRUCTOR_LOCK.synchronized { + consumerGroupMap.getOrElse(groupName, { + val newConsumer = createConsumer(groupName) + val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) + newConsumer.setGroup(group) + newConsumer.setConsumeQueue(new LoopArrayQueue(group)) + consumerGroupMap.put(groupName, newConsumer) + consumerListener.foreach(_.onConsumerCreated(newConsumer)) + newConsumer.start() + newConsumer + }) + } + consumer.setLastTime(System.currentTimeMillis()) + consumer + } + + override protected def createConsumer(groupName: String) = { + val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) + new FIFOUserConsumer(getSchedulerContext, getOrCreateExecutorService, group) + } + + override def destroyConsumer(groupName: String) = + consumerGroupMap.get(groupName).foreach { tmpConsumer => + tmpConsumer.shutdown() + consumerGroupMap.remove(groupName) + consumerListener.foreach(_.onConsumerDestroyed(tmpConsumer)) + warn(s"Consumer of group ($groupName) is destroyed") + } + + override def shutdown() = { + consumerGroupMap.iterator.foreach(x => x._2.shutdown()) + } + + override def listConsumers() = consumerGroupMap.values.toArray +} diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroup.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroup.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroup.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroup.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala similarity index 95% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala index c64112d484..0f97b67faa 100644 --- a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala +++ b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelGroupFactory.scala @@ -16,13 +16,11 @@ package com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue -import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, Job, SchedulerEvent} +import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, SchedulerEvent} import scala.collection.mutable -/** - * Created by enjoyyin on 2018/9/12. - */ + class ParallelGroupFactory extends GroupFactory{ private val groupMap = new mutable.HashMap[String, Group]() def getInitCapacity(groupName: String): Int= 100 diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelScheduler.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelScheduler.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelScheduler.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelScheduler.scala diff --git a/core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelSchedulerContextImpl.scala b/linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelSchedulerContextImpl.scala similarity index 100% rename from core/scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelSchedulerContextImpl.scala rename to linkis-commons/linkis-scheduler/src/main/scala/com/webank/wedatasphere/linkis/scheduler/queue/parallelqueue/ParallelSchedulerContextImpl.scala diff --git a/linkis-commons/linkis-storage/pom.xml b/linkis-commons/linkis-storage/pom.xml new file mode 100644 index 0000000000..c59e4a0af3 --- /dev/null +++ b/linkis-commons/linkis-storage/pom.xml @@ -0,0 +1,98 @@ + + + + + 4.0.0 + + + 1.0.0-RC1 + com.webank.wedatasphere.linkis + linkis + + + + jar + linkis-storage + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-hadoop-common + ${linkis.version} + + + + org.json4s + json4s-jackson_${scala.binary.version} + ${json4s.version} + + + org.scala-lang + scala-library + + + provided + + + + cglib + cglib + 2.2.2 + + + net.sourceforge.javacsv + javacsv + 2.0 + + + com.monitorjbl + xlsx-streamer + 1.2.1 + + + com.fasterxml.jackson.core + jackson-databind + + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + \ No newline at end of file diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/domain/FsPathListWithError.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/domain/FsPathListWithError.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/domain/FsPathListWithError.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/domain/FsPathListWithError.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/ExcelStorageReader.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/ExcelStorageReader.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/ExcelStorageReader.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/ExcelStorageReader.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsUtils.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsUtils.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsUtils.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsUtils.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsxUtils.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsxUtils.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsxUtils.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/excel/XlsxUtils.java diff --git a/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/FSNotInitException.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/FSNotInitException.java new file mode 100644 index 0000000000..bcd55034cc --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/FSNotInitException.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.exception; + +import com.webank.wedatasphere.linkis.common.exception.WarnException; + + +public class FSNotInitException extends WarnException { + + public FSNotInitException(){ + super(52000, "FSNotInitException"); + } + + public FSNotInitException(int errCode, String desc) { + super(errCode, desc); + } +} diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageErrorException.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageErrorException.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageErrorException.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageErrorException.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageFatalException.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageFatalException.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageFatalException.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageFatalException.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageWarnException.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageWarnException.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageWarnException.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/exception/StorageWarnException.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java similarity index 92% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java index a207bc8841..bb503b7984 100644 --- a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/BuildFactory.java @@ -18,10 +18,12 @@ import com.webank.wedatasphere.linkis.common.io.Fs; -/** - * Created by johnnwang on 10/17/18. - */ + public interface BuildFactory { + Fs getFs(String user, String proxyUser); + + Fs getFs(String user, String proxyUser, String label); + String fsName(); } diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java similarity index 85% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java index b41b373eb6..79a8235ac2 100644 --- a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildHDFSFileSystem.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,16 +18,14 @@ import com.webank.wedatasphere.linkis.storage.factory.BuildFactory; import com.webank.wedatasphere.linkis.storage.fs.FileSystem; import com.webank.wedatasphere.linkis.storage.fs.impl.HDFSFileSystem; -import com.webank.wedatasphere.linkis.storage.io.IOMethodInterceptor; +import com.webank.wedatasphere.linkis.storage.io.IOMethodInterceptorCreator$; import com.webank.wedatasphere.linkis.storage.utils.StorageUtils; import net.sf.cglib.proxy.Enhancer; -/** - * Created by johnnwang on 10/17/18. - */ public class BuildHDFSFileSystem implements BuildFactory { + /** * If it is a node with hdfs configuration file, then go to the proxy mode of hdfs, if not go to io proxy mode * 如果是有hdfs配置文件的节点,则走hdfs的代理模式,如果不是走io代理模式 @@ -48,13 +43,21 @@ public Fs getFs(String user, String proxyUser) { //TODO Agent user(代理的用户) Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HDFSFileSystem.class.getSuperclass()); - enhancer.setCallback(new IOMethodInterceptor(fsName())); + enhancer.setCallback(IOMethodInterceptorCreator$.MODULE$.getIOMethodInterceptor(fsName())); fs = (FileSystem) enhancer.create(); } fs.setUser(proxyUser); return fs; } + @Override + public Fs getFs(String user, String proxyUser, String label) { + HDFSFileSystem fs = new HDFSFileSystem(); + fs.setUser(proxyUser); + fs.setLabel(label); + return fs; + } + @Override public String fsName() { return "hdfs"; diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java similarity index 80% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java index d31d235241..aac775ba63 100644 --- a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/factory/impl/BuildLocalFileSystem.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,13 +17,11 @@ import com.webank.wedatasphere.linkis.storage.factory.BuildFactory; import com.webank.wedatasphere.linkis.storage.fs.FileSystem; import com.webank.wedatasphere.linkis.storage.fs.impl.LocalFileSystem; -import com.webank.wedatasphere.linkis.storage.io.IOMethodInterceptor; +import com.webank.wedatasphere.linkis.storage.io.IOMethodInterceptorCreator$; import com.webank.wedatasphere.linkis.storage.utils.StorageConfiguration; import net.sf.cglib.proxy.Enhancer; -/** - * Created by johnnwang on 10/17/18. - */ + public class BuildLocalFileSystem implements BuildFactory { @Override @@ -36,20 +31,25 @@ public Fs getFs(String user, String proxyUser){ if((Boolean) StorageConfiguration.IS_SHARE_NODE().getValue()){ fs = new LocalFileSystem(); } else { - fs = getProxyFs(); + fs = getProxyFs(); } } else { - fs = getProxyFs(); + fs = getProxyFs(); } fs.setUser(proxyUser); - return fs; + return fs; + } + + @Override + public Fs getFs(String user, String proxyUser, String label) { + return getFs(user, proxyUser); } - private FileSystem getProxyFs(){ + private FileSystem getProxyFs() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(LocalFileSystem.class.getSuperclass()); - enhancer.setCallback(new IOMethodInterceptor(fsName())); - return (FileSystem)enhancer.create(); + enhancer.setCallback(IOMethodInterceptorCreator$.MODULE$.getIOMethodInterceptor(fsName())); + return (FileSystem) enhancer.create(); } @Override diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java similarity index 93% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java index f361006425..28e3d6e69a 100644 --- a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/FileSystem.java @@ -23,9 +23,7 @@ import java.io.File; import java.io.IOException; -/** - * Created by johnnwang on 10/15/18. - */ + public abstract class FileSystem implements Fs{ protected String user; @@ -52,6 +50,8 @@ public abstract class FileSystem implements Fs{ public abstract boolean mkdirs(FsPath dest) throws IOException; + public abstract boolean copy(String origin, String dest) throws IOException; + public FsPathListWithError listPathWithError(FsPath path) throws IOException { return null; } @@ -60,6 +60,10 @@ public boolean createNewFile(FsPath dest) throws IOException{ return create(dest.getPath()); } + public boolean copyFile(FsPath origin, FsPath dest) throws IOException{ + return copy(origin.getPath(), dest.getPath()); + } + /** * Set permissions for a path(设置某个路径的权限) * @param dest path(路径) diff --git a/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/HDFSFileSystem.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/HDFSFileSystem.java new file mode 100644 index 0000000000..6195bc30fa --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/HDFSFileSystem.java @@ -0,0 +1,406 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.fs.impl; + +import com.webank.wedatasphere.linkis.common.io.FsPath; +import com.webank.wedatasphere.linkis.hadoop.common.utils.HDFSUtils; +import com.webank.wedatasphere.linkis.storage.domain.FsPathListWithError; +import com.webank.wedatasphere.linkis.storage.fs.FileSystem; +import com.webank.wedatasphere.linkis.storage.utils.StorageConfiguration; +import com.webank.wedatasphere.linkis.storage.utils.StorageUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileUtil; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.permission.FsAction; +import org.apache.hadoop.fs.permission.FsPermission; +import org.apache.hadoop.security.UserGroupInformation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +public class HDFSFileSystem extends FileSystem { + + public static final String HDFS_PREFIX_WITHOUT_AUTH = "hdfs:///"; + public static final String HDFS_PREFIX_WITH_AUTH = "hdfs://"; + private org.apache.hadoop.fs.FileSystem fs = null; + private Configuration conf = null; + + private String label = null; + + private static final Logger logger = LoggerFactory.getLogger(HDFSFileSystem.class); + + /** + * File System abstract method start + */ + + + @Override + public String listRoot() throws IOException { + return "/"; + } + + @Override + public long getTotalSpace(FsPath dest) throws IOException { + return 0; + } + + @Override + public long getFreeSpace(FsPath dest) throws IOException { + return 0; + } + + @Override + public long getUsableSpace(FsPath dest) throws IOException { + return 0; + } + + @Override + public boolean canExecute(FsPath dest) throws IOException { + return canAccess(dest, FsAction.EXECUTE); + } + + @Override + public boolean setOwner(FsPath dest, String user, String group) throws IOException { + fs.setOwner(new Path(checkHDFSPath(dest.getPath())), user, group); + return true; + } + + @Override + public boolean setOwner(FsPath dest, String user) throws IOException { + Path path = new Path(checkHDFSPath(dest.getPath())); + fs.setOwner(path, user, fs.getFileStatus(path).getGroup()); + return true; + } + + @Override + public boolean setGroup(FsPath dest, String group) throws IOException { + Path path = new Path(checkHDFSPath(dest.getPath())); + fs.setOwner(path, fs.getFileStatus(path).getOwner(), group); + return true; + } + + @Override + public boolean mkdir(FsPath dest) throws IOException { + String path = checkHDFSPath(dest.getPath()); + if (!canExecute(getParentPath(path))) { + throw new IOException("You have not permission to access path " + path); + } + return fs.mkdirs(new Path(path)); + } + + @Override + public boolean mkdirs(FsPath dest) throws IOException { + String path = checkHDFSPath(dest.getPath()); + FsPath parentPath = getParentPath(path); + while (!exists(parentPath)) { + parentPath = getParentPath(parentPath.getPath()); + } + if (!canExecute(parentPath)) { + throw new IOException("You have not permission to access path " + path); + } + return fs.mkdirs(new Path(path)); + } + + + @Override + public boolean setPermission(FsPath dest, String permission) throws IOException { + String path = checkHDFSPath(dest.getPath()); + if (!isOwner(path)) { + throw new IOException(path + " only can be set by owner."); + } + FsAction u = null; + FsAction g = null; + FsAction o = null; + if (StringUtils.isNumeric(permission) && permission.length() == 3) { + u = FsAction.getFsAction(FsPath.permissionFormatted(permission.charAt(0))); + g = FsAction.getFsAction(FsPath.permissionFormatted(permission.charAt(1))); + o = FsAction.getFsAction(FsPath.permissionFormatted(permission.charAt(2))); + } else if (!StringUtils.isNumeric(permission) && permission.length() == 9) { + u = FsAction.getFsAction(permission.substring(0, 3)); + g = FsAction.getFsAction(permission.substring(3, 6)); + o = FsAction.getFsAction(permission.substring(6, 9)); + } else { + throw new IOException("Incorrent permission string " + permission); + } + FsPermission fsPermission = new FsPermission(u, g, o); + fs.setPermission(new Path(path), fsPermission); + return true; + } + + @Override + public FsPathListWithError listPathWithError(FsPath path) throws IOException { + FileStatus[] stat = fs.listStatus(new Path(checkHDFSPath(path.getPath()))); + List fsPaths = new ArrayList(); + for (FileStatus f : stat) { + fsPaths.add(fillStorageFile(new FsPath(StorageUtils.HDFS_SCHEMA() + f.getPath().toUri().getPath()), f)); + } + if (fsPaths.isEmpty()) { + return null; + } + return new FsPathListWithError(fsPaths, ""); + } + + /** + * FS interface method start + */ + @Override + public void init(Map properties) throws IOException { + if (MapUtils.isNotEmpty(properties) && properties.containsKey(StorageConfiguration.PROXY_USER().key())) { + user = StorageConfiguration.PROXY_USER().getValue(properties); + } + + if (user == null) { + throw new IOException("User cannot be empty(用户不能为空)"); + } + + conf = HDFSUtils.getConfigurationByLabel(user, label); + + if (MapUtils.isNotEmpty(properties)) { + for (String key : properties.keySet()) { + String v = properties.get(key); + if (StringUtils.isNotEmpty(v)) { + conf.set(key, v); + } + } + + } + /*conf.set("fs.hdfs.impl.disable.cache","true");*/ + fs = HDFSUtils.getHDFSUserFileSystem(user, conf); + if (fs == null) { + throw new IOException("init HDFS FileSystem failed!"); + } + } + + + @Override + public String fsName() { + return "hdfs"; + } + + @Override + public String rootUserName() { + return StorageConfiguration.HDFS_ROOT_USER().getValue(); + } + + @Override + public FsPath get(String dest) throws IOException { + return fillStorageFile(new FsPath(dest), fs.getFileStatus(new Path(dest))); + } + + @Override + public InputStream read(FsPath dest) throws IOException { + if (!canRead(dest)) { + throw new IOException("You have not permission to access path " + dest.getPath()); + } + return fs.open(new Path(dest.getPath())); + } + + @Override + public OutputStream write(FsPath dest, boolean overwrite) throws IOException { + String path = checkHDFSPath(dest.getPath()); + if (!exists(dest)) { + if (!canWrite(dest.getParent())) { + throw new IOException("You have not permission to access path " + dest.getParent()); + } + } else { + if (!canWrite(dest)) { + throw new IOException("You have not permission to access path " + path); + } + } + if (!overwrite) { + return fs.append(new Path(path)); + } else { + return fs.create(new Path(path), true); + } + } + + @Override + public boolean create(String dest) throws IOException { + if (!canExecute(getParentPath(dest))) { + throw new IOException("You have not permission to access path " + dest); + } + return fs.createNewFile(new Path(checkHDFSPath(dest))); + } + + @Override + public boolean copy(String origin, String dest) throws IOException { + if (!canExecute(getParentPath(dest))) { + throw new IOException("You have not permission to access path " + dest); + } + return FileUtil.copy(fs, new Path(checkHDFSPath(origin)), fs, new Path(checkHDFSPath(dest)), false, true, fs.getConf()); + } + + @Override + public List list(FsPath path) throws IOException { + FileStatus[] stat = fs.listStatus(new Path(checkHDFSPath(path.getPath()))); + List fsPaths = new ArrayList(); + for (FileStatus f : stat) { + fsPaths.add(fillStorageFile(new FsPath(f.getPath().toUri().getPath()), f)); + } + return fsPaths; + } + + @Override + public boolean canRead(FsPath dest) throws IOException { + return canAccess(dest, FsAction.READ); + } + + @Override + public boolean canWrite(FsPath dest) throws IOException { + return canAccess(dest, FsAction.WRITE); + } + + @Override + public boolean exists(FsPath dest) throws IOException { + return fs.exists(new Path(checkHDFSPath(dest.getPath()))); + } + + @Override + public boolean delete(FsPath dest) throws IOException { + String path = checkHDFSPath(dest.getPath()); + if (!isOwner(path)) { + throw new IOException("You have not permission to delete path " + path); + } + return fs.delete(new Path(path), true); + } + + @Override + public boolean renameTo(FsPath oldDest, FsPath newDest) throws IOException { + if (!isOwner(checkHDFSPath(oldDest.getPath()))) { + throw new IOException("You have not permission to rename path " + oldDest.getPath()); + } + return fs.rename(new Path(checkHDFSPath(oldDest.getPath())), new Path(checkHDFSPath(newDest.getPath()))); + } + + @Override + public void close() throws IOException { + fs.close(); + } + + + /** + * Utils method start + */ + + private FsPath fillStorageFile(FsPath fsPath, FileStatus fileStatus) throws IOException { + fsPath.setAccess_time(fileStatus.getAccessTime()); + fsPath.setModification_time(fileStatus.getModificationTime()); + fsPath.setOwner(fileStatus.getOwner()); + fsPath.setGroup(fileStatus.getGroup()); + fsPath.setIsdir(fileStatus.isDirectory()); + try { + if (fsPath.isdir()) { + fsPath.setLength(fs.getContentSummary(fileStatus.getPath()).getLength()); + } else { + fsPath.setLength(fileStatus.getLen()); + } + fsPath.setPermissionString(fileStatus.getPermission().toString()); + } catch (Throwable e) { + logger.error("Failed to fill storage file:" + fileStatus.getPath(), e); + } + return fsPath; + } + + private boolean canAccess(FsPath fsPath, FsAction access) throws IOException { + String path = checkHDFSPath(fsPath.getPath()); + if (!exists(fsPath)) { + throw new IOException("directory or file not exists: " + path); + } + + FileStatus f = fs.getFileStatus(new Path(path)); + FsPermission permission = f.getPermission(); + UserGroupInformation ugi = HDFSUtils.getUserGroupInformation(user); + String[] groupNames; + try { + groupNames = ugi.getGroupNames(); + } catch (NullPointerException e) { + if ((Boolean) com.webank.wedatasphere.linkis.common.conf.Configuration.IS_TEST_MODE().getValue()) { + groupNames = new String[]{"hadoop"}; + } else { + throw e; + } + } + if (user.equals(f.getOwner()) || user.equals(rootUserName())) { + if (permission.getUserAction().implies(access)) { + return true; + } + } else if (ArrayUtils.contains(groupNames, f.getGroup())) { + if (permission.getGroupAction().implies(access)) { + return true; + } + } else { //other class + if (permission.getOtherAction().implies(access)) { + return true; + } + } + return false; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + private String checkHDFSPath(String path) { + try { + boolean checkHdfsPath = (boolean) StorageConfiguration.HDFS_PATH_PREFIX_CHECK_ON().getValue(); + if (checkHdfsPath) { + boolean rmHdfsPrefix = (boolean) StorageConfiguration.HDFS_PATH_PREFIX_REMOVE().getValue(); + if (rmHdfsPrefix) { + if (StringUtils.isBlank(path)) { + return path; + } + if (path.startsWith(HDFS_PREFIX_WITHOUT_AUTH)) { + // leave the first "/" in path + int remainIndex = HDFS_PREFIX_WITHOUT_AUTH.length() - 1; + if (logger.isDebugEnabled()) { + logger.debug("checkHDFSPath ori path : {}, after path : {}", path, path.substring(remainIndex)); + } + return path.substring(remainIndex); + } else if (path.startsWith(HDFS_PREFIX_WITH_AUTH)) { + int remainIndex = HDFS_PREFIX_WITH_AUTH.length(); + String[] t1 = path.substring(remainIndex).split("/", 2); + if (t1.length != 2) { + logger.error("checkHDFSPath Invalid path: " + path); + return path; + } + if (logger.isDebugEnabled()) { + logger.debug("checkHDFSPath ori path : {}, after path : {}", path, "/" + t1[1]); + } + return "/" + t1[1]; + } else { + return path; + } + } + } + } catch (Exception e) { + logger.error("checkHDFSPath error. msg : " + e.getMessage() + " ", e); + } + return path; + } +} diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java similarity index 94% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java index b7a00606c2..36157d980e 100644 --- a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java +++ b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/fs/impl/LocalFileSystem.java @@ -23,6 +23,7 @@ import com.webank.wedatasphere.linkis.storage.fs.FileSystem; import com.webank.wedatasphere.linkis.storage.utils.StorageConfiguration; import org.apache.commons.collections.MapUtils; +import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,9 +33,7 @@ import java.nio.file.attribute.*; import java.util.*; -/** - * Created by johnnwang on 10/15/18. - */ + public class LocalFileSystem extends FileSystem { @@ -145,6 +144,29 @@ public boolean mkdirs(FsPath dest) throws IOException { return true; } + @Override + public boolean copy(String origin, String dest) throws IOException { + File file = new File(dest); + if(!isOwner(file.getParent())) { + throw new IOException("you have on permission to create file " + dest); + } + FileUtils.copyFile(new File(origin), file); + try { + setPermission(new FsPath(dest), "rwxr-----"); + if(!user.equals(getOwner(dest))) { + setOwner(new FsPath(dest), user, null); + } + } catch (Throwable e) { + file.delete(); + if(e instanceof IOException) { + throw (IOException) e; + } else { + throw new IOException(e); + } + } + return true; + } + @Override public boolean setPermission(FsPath dest, String permission) throws IOException { String path = dest.getPath(); diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/DefaultPipelineFactory.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/DefaultPipelineFactory.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/DefaultPipelineFactory.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/DefaultPipelineFactory.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineReader.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineReader.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineReader.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineReader.java diff --git a/storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineWriter.java b/linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineWriter.java similarity index 100% rename from storage/storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineWriter.java rename to linkis-commons/linkis-storage/src/main/java/com/webank/wedatasphere/linkis/storage/pipeline/PipelineWriter.java diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala similarity index 78% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala index 6b7aa39bfb..d7a1b7908b 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/FSFactory.scala @@ -22,9 +22,7 @@ import com.webank.wedatasphere.linkis.storage.exception.StorageFatalException import com.webank.wedatasphere.linkis.storage.factory.BuildFactory import com.webank.wedatasphere.linkis.storage.utils.{StorageConfiguration, StorageUtils} -/** - * Created by johnnwang on 10/17/18. - */ + object FSFactory extends Logging{ private val buildClasses: Map[String, BuildFactory] = StorageUtils.loadClass[BuildFactory](StorageConfiguration.STORAGE_BUILD_FS_CLASSES.getValue, t => t.fsName()) @@ -61,19 +59,30 @@ object FSFactory extends Logging{ /** * 1. If the process user is passed and the proxy user and the process user are consistent, the file:// type FS is the FS of the process user (the shared storage exists) - * 2, if the process user is passed and the proxy user and the process user are consistent and there is no shared storage, the file:// type FS is the proxy to the remote (shared storage machine root) FS - * 3. If the passed proxy user and process user are consistent, the hdfs type is the FS of the process user. - * 4. If the proxy user and the process user are inconsistent, the hdfs type is the FS after the proxy. + * * 2, if the process user is passed and the proxy user and the process user are consistent and there is no shared storage, the file:// type FS is the proxy to the remote (shared storage machine root) FS + * * 3. If the passed proxy user and process user are consistent, the hdfs type is the FS of the process user. + * * 4. If the proxy user and the process user are inconsistent, the hdfs type is the FS after the proxy. * 1、如果传了进程用户且代理用户和进程用户一致则file://类型的FS为该进程用户的FS(存在共享存储) * 2、如果传了进程用户且代理用户和进程用户一致且没有共享存储则file://类型的FS为代理到Remote(共享存储机器root)的FS * 3、如果传了的代理用户和进程用户一致则hdfs类型为该进程用户的FS * 4、如果传了代理用户和进程用户不一致则hdfs类型为代理后的FS + * * @param fsPath * @param proxyUser * @return */ - def getFsByProxyUser(fsPath: FsPath, proxyUser:String): Fs = { - getFs(fsPath.getFsType(), proxyUser) + def getFsByProxyUser(fsPath: FsPath, proxyUser: String): Fs = { + getFs(fsPath.getFsType(), proxyUser) + } + + def getFSByLabel(fs: String, label: String): Fs = { + val user = StorageUtils.getJvmUser + getBuildFactory(fs).getFs(user, user, label) + } + + def getFSByLabelAndUser(fs: String, label: String, proxy: String): Fs = { + val user = StorageUtils.getJvmUser + getBuildFactory(fs).getFs(user, proxy, label) } } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineMetaData.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineMetaData.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineMetaData.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineMetaData.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineRecord.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineRecord.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineRecord.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/LineRecord.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsWriter.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/CSVFsWriter.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVWriter.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/csv/StorageCSVWriter.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala similarity index 93% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala index 8c9168c14b..c5e1fce9f9 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/DataType.scala @@ -17,14 +17,10 @@ package com.webank.wedatasphere.linkis.storage.domain import java.sql.{Date, Timestamp} -import com.webank.wedatasphere.linkis.common.utils.Utils -import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} -/** - * Created by johnnwang on 10/17/18. - */ + object DataType extends Logging{ @@ -38,7 +34,8 @@ object DataType extends Logging{ val BIGINT_REGEX = "^bigint.*".r.unanchored val FLOAT_REGEX = "^float.*".r.unanchored val DOUBLE_REGEX = "^double.*".r.unanchored - + + val VARCHAR_REGEX = "^varchar.*".r.unanchored val CHAR_REGEX = "^char.*".r.unanchored @@ -55,7 +52,8 @@ object DataType extends Logging{ case "string" => StringType case "boolean" => BooleanType case SHORT_REGEX() => ShortIntType - case LONG_REGEX() | BIGINT_REGEX() => LongType + case LONG_REGEX() => LongType + case BIGINT_REGEX() => BigIntType case INT_REGEX() | "integer" | "smallint" => IntType case FLOAT_REGEX() => FloatType case DOUBLE_REGEX() => DoubleType @@ -72,7 +70,7 @@ object DataType extends Logging{ case _ => StringType } -def toValue(dataType: DataType, value: String): Any = Utils.tryCatch(dataType match { + def toValue(dataType: DataType, value: String): Any = Utils.tryCatch(dataType match { case NullType => null case StringType | CharType | VarcharType | StructType | ListType | ArrayType | MapType => value case BooleanType => if(isNull(value)) null else value.toBoolean @@ -86,11 +84,10 @@ def toValue(dataType: DataType, value: String): Any = Utils.tryCatch(dataType ma case TimestampType => if(isNull(value)) null else Timestamp.valueOf(value).toString.stripSuffix(".0") case BinaryType => if(isNull(value)) null else value.getBytes() case _ => value - }){ + }){ t => warn(s"Failed to $value switch to dataType:",t) - value + value } - def isNull(value:String):Boolean= if(value == null || value == NULL_VALUE || value.trim == "") true else false } @@ -104,8 +101,8 @@ case object BooleanType extends DataType("boolean", 16) case object TinyIntType extends DataType("tinyint", -6) case object ShortIntType extends DataType("short", 5) case object IntType extends DataType("int", 4) -case object BigIntType extends DataType("bigint", -5) case object LongType extends DataType("long", -5) +case object BigIntType extends DataType("bigint", -5) case object FloatType extends DataType("float", 6) case object DoubleType extends DataType("double", 8) case object CharType extends DataType("char", 1) diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/Dolphin.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/Dolphin.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/Dolphin.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/Dolphin.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/MethodEntity.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/MethodEntity.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/MethodEntity.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/domain/MethodEntity.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsWriter.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelFsWriter.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java similarity index 99% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java index 7051ab26f9..14e7fd76ee 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/ExcelXlsReader.java @@ -25,15 +25,15 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; -/** - * Created by johnnwang on 7/10/18. - */ + public class ExcelXlsReader implements HSSFListener { private int minColumns = -1; diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala similarity index 90% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala index 6b3ba726d8..95c146999e 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageExcelWriter.scala @@ -33,16 +33,16 @@ import scala.collection.mutable.ArrayBuffer */ class StorageExcelWriter(val charset: String, val sheetName: String, val dateFormat: String, val outputStream: OutputStream) extends ExcelFsWriter { - private var workBook: SXSSFWorkbook = _ - private var sheet: SXSSFSheet = _ - private var format: DataFormat = _ - private var types: Array[DataType] = _ - private var rowPoint = 0 - private var columnCounter = 0 - private val styles = new util.HashMap[String, CellStyle]() - private var isFlush = true - private val os = new ByteArrayOutputStream() - private var is: ByteArrayInputStream = _ + protected var workBook: SXSSFWorkbook = _ + protected var sheet: SXSSFSheet = _ + protected var format: DataFormat = _ + protected var types: Array[DataType] = _ + protected var rowPoint = 0 + protected var columnCounter = 0 + protected val styles = new util.HashMap[String, CellStyle]() + protected var isFlush = true + protected val os = new ByteArrayOutputStream() + protected var is: ByteArrayInputStream = _ def init = { workBook = new SXSSFWorkbook() diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageMultiExcelWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageMultiExcelWriter.scala new file mode 100644 index 0000000000..e962ce0744 --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/excel/StorageMultiExcelWriter.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.excel + +import java.io.OutputStream + +import org.apache.poi.xssf.streaming.SXSSFWorkbook + +class StorageMultiExcelWriter(override val outputStream: OutputStream) + extends StorageExcelWriter(null, null, null, outputStream) { + + private var sheetIndex = 0 + + + override def init = { + if (workBook == null) workBook = new SXSSFWorkbook() + //1.让表自适应列宽 + if (sheet != null) { + sheet.trackAllColumnsForAutoSizing() + 0 to columnCounter foreach (sheet.autoSizeColumn) + } + //2.重置参数 + //2.1 columnCounter 归0 + columnCounter = 0 + //2.2 创建新sheet + sheet = workBook.createSheet(s"resultset$sheetIndex") + //2.3 sheetIndex自增 + sheetIndex += 1 + //2.4 types 置空 + types = null + //2.5 rowPoint 归0 记录行数 + rowPoint = 0 + //2.6 styles 清空 + styles.clear() + } +} diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOClient.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOClient.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOClient.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOClient.scala diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOMethodInterceptorCreator.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOMethodInterceptorCreator.scala new file mode 100644 index 0000000000..e5ad50787a --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/io/IOMethodInterceptorCreator.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.io + +import com.webank.wedatasphere.linkis.storage.exception.StorageErrorException +import net.sf.cglib.proxy.MethodInterceptor + + +trait IOMethodInterceptorCreator { + + def createIOMethodInterceptor(fsName: String): MethodInterceptor +} + +object IOMethodInterceptorCreator { + + var interceptorCreator: IOMethodInterceptorCreator = null + + + /** + * This method is called when ioClient is initialized. + * ioClient初始化时会调用该方法 + * + * @param interceptorCreator + */ + def register(interceptorCreator: IOMethodInterceptorCreator): Unit = { + this.interceptorCreator = interceptorCreator + } + + def getIOMethodInterceptor(fsName: String): MethodInterceptor = { + if (interceptorCreator == null) throw new StorageErrorException(52004, "You must register IOMethodInterceptorCreator before you can use proxy mode.(必须先注册IOMethodInterceptorCreator,才能使用代理模式)") + interceptorCreator.createIOMethodInterceptor(fsName) + } +} \ No newline at end of file diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/DefaultResultSetFactory.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/DefaultResultSetFactory.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/DefaultResultSetFactory.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/DefaultResultSetFactory.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultMetaData.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultMetaData.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultMetaData.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultMetaData.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultRecord.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultRecord.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultRecord.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultRecord.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala similarity index 93% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala index ced4c6f739..7b0c90ab83 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetFactory.scala @@ -22,9 +22,6 @@ import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} import scala.collection.mutable -/** - * Created by johnnwang on 10/16/18. - */ trait ResultSetFactory extends scala.AnyRef { def getResultSetByType(resultSetType : scala.Predef.String) :ResultSet[_ <: MetaData, _ <: Record] @@ -55,7 +52,7 @@ object ResultSetFactory { val HTML_TYPE = "5" /** - * Result set corresponding type record(结果集对应类型记录) + * TODO 修改为注册形式,并修改ResultSet的getResultType逻辑 Result set corresponding type record(结果集对应类型记录) */ val resultSetType = mutable.LinkedHashMap[String, String](TEXT_TYPE -> "TEXT", TABLE_TYPE -> "TABLE" , diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala similarity index 98% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala index 8aa6afcc41..e7125b09b9 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetReader.scala @@ -24,9 +24,7 @@ import com.webank.wedatasphere.linkis.storage.FSFactory import com.webank.wedatasphere.linkis.storage.exception.StorageErrorException import com.webank.wedatasphere.linkis.storage.resultset.table.{TableMetaData, TableRecord, TableResultSet} -/** - * Created by johnnwang on 10/18/18. - */ + object ResultSetReader { def getResultSetReader[K <: MetaData, V <: Record](resultSet: ResultSet[K, V], inputStream: InputStream): ResultSetReader[K, V] = { diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala similarity index 97% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala index bfd6e2d004..e7de74874e 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/ResultSetWriter.scala @@ -21,9 +21,7 @@ import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} import scala.collection.mutable.ArrayBuffer -/** - * Created by johnnwang on 10/18/18. - */ + object ResultSetWriter { def getResultSetWriter[K <: MetaData, V <: Record](resultSet: ResultSet[K,V], maxCacheSize: Long, storePath: FsPath):ResultSetWriter[K, V] = new StorageResultSetWriter[K, V](resultSet, maxCacheSize, storePath) diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala similarity index 87% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala index ca8f708df5..edab43e36a 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSet.scala @@ -22,9 +22,7 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.storage.domain.Dolphin import com.webank.wedatasphere.linkis.storage.utils.StorageConfiguration -/** - * Created by johnnwang on 10/20/18. - */ + abstract class StorageResultSet[K <: MetaData, V <: Record] extends ResultSet[K, V] with Logging{ val resultHeaderBytes = Dolphin.MAGIC_BYTES ++ Dolphin.getIntBytes(resultSetType().toInt) @@ -33,10 +31,10 @@ abstract class StorageResultSet[K <: MetaData, V <: Record] extends ResultSet[K, override def getResultSetPath(parentDir: FsPath, fileName: String): FsPath = { - val path = if(parentDir.getSchemaPath.endsWith("/")) - parentDir.getSchemaPath + fileName + Dolphin.DOLPHIN_FILE_SUFFIX + val path = if(parentDir.getPath.endsWith("/")) + parentDir.toPath + fileName + Dolphin.DOLPHIN_FILE_SUFFIX else - parentDir.getSchemaPath + "/" + fileName + Dolphin.DOLPHIN_FILE_SUFFIX + parentDir.toPath + "/" + fileName + Dolphin.DOLPHIN_FILE_SUFFIX new FsPath(path) } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala similarity index 83% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala index b5f9218539..c950fe7da2 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/StorageResultSetWriter.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,9 +24,7 @@ import com.webank.wedatasphere.linkis.storage.utils.{FileSystemUtils, StorageUti import scala.collection.mutable.ArrayBuffer -/** - * Created by johnnwang on 10/17/18. - */ + class StorageResultSetWriter[K <: MetaData, V <: Record](resultSet: ResultSet[K,V], maxCacheSize: Long, storePath: FsPath) extends ResultSetWriter[K,V](resultSet = resultSet, maxCacheSize = maxCacheSize, storePath = storePath) with Logging{ @@ -51,35 +46,35 @@ class StorageResultSetWriter[K <: MetaData, V <: Record](resultSet: ResultSet[K, private var rMetaData: MetaData = _ - private var proxyUser:String = StorageUtils.getJvmUser + private var proxyUser: String = StorageUtils.getJvmUser def getMetaData: MetaData = rMetaData - def setProxyUser(proxyUser:String): Unit = { + def setProxyUser(proxyUser: String): Unit = { this.proxyUser = proxyUser } - def isEmpty:Boolean = { - rMetaData == null && buffer.length <= Dolphin.FILE_EMPTY + def isEmpty: Boolean = { + rMetaData == null && buffer.length <= Dolphin.FILE_EMPTY } def init(): Unit = { - writeLine(resultSet.getResultSetHeader) + writeLine(resultSet.getResultSetHeader, true) } def createNewFile: Unit = { - if(storePath != null && outputStream == null){ - fs = FSFactory.getFsByProxyUser(storePath,proxyUser) + if (storePath != null && outputStream == null) { + fs = FSFactory.getFsByProxyUser(storePath, proxyUser) fs.init(null) - FileSystemUtils.createNewFile(storePath, proxyUser,true) + FileSystemUtils.createNewFile(storePath, proxyUser, true) outputStream = fs.write(storePath, true) info(s"Succeed to create a new file:$storePath") } } - def writeLine(bytes: Array[Byte]): Unit = { - if(buffer.length > maxCacheSize) { - if(outputStream == null) { + def writeLine(bytes: Array[Byte], cache: Boolean = false): Unit = { + if (buffer.length > maxCacheSize && !cache) { + if (outputStream == null) { createNewFile } flush() @@ -88,12 +83,13 @@ class StorageResultSetWriter[K <: MetaData, V <: Record](resultSet: ResultSet[K, buffer.appendAll(bytes) } } + override def toString: String = { if(outputStream == null){ if(isEmpty) return "" new String(buffer.toArray,Dolphin.CHAR_SET) } else { - storePath.getSchemaPath + storePath.getSchemaPath } } @@ -115,7 +111,7 @@ class StorageResultSetWriter[K <: MetaData, V <: Record](resultSet: ResultSet[K, { rMetaData = metaData init() - writeLine(serializer.metaDataToBytes(metaData)) + writeLine(serializer.metaDataToBytes(metaData), true) } moveToWriteRow = true } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/html/HtmlResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/html/HtmlResultSet.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/html/HtmlResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/html/HtmlResultSet.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOMetaData.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOMetaData.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOMetaData.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOMetaData.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IORecord.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IORecord.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IORecord.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IORecord.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultDeserializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultDeserializer.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultDeserializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultDeserializer.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSerializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSerializer.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSerializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSerializer.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSet.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/io/IOResultSet.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala similarity index 94% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala index ce8c4ec1f1..9e50258119 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/picture/PictureResultSet.scala @@ -21,10 +21,8 @@ import com.webank.wedatasphere.linkis.storage.resultset.txt.{TextResultDeseriali import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, StorageResultSet} import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} -/** - * Created by johnnwang on 2018/12/10. - */ -class PictureResultSet extends StorageResultSet[LineMetaData, LineRecord] with Serializable{ + +class PictureResultSet extends StorageResultSet[LineMetaData, LineRecord] with Serializable { override def resultSetType(): String = ResultSetFactory.PICTURE_TYPE diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableMetaData.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableMetaData.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableMetaData.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableMetaData.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala similarity index 80% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala index 90c163efce..ec8766f295 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableRecord.scala @@ -18,12 +18,19 @@ package com.webank.wedatasphere.linkis.storage.resultset.table import com.webank.wedatasphere.linkis.common.io.Record import com.webank.wedatasphere.linkis.storage.resultset.ResultRecord +import com.webank.wedatasphere.linkis.storage.utils.StorageUtils + -/** - * Created by johnnwang on 10/16/18. - */ class TableRecord(val row:Array[Any]) extends ResultRecord{ + override def cloneRecord(): Record = { new TableRecord(row) } + + def tableRecordToString(nullValue:String = "NULL"):Array[String] = { + row.map{ col => + StorageUtils.colToString(col,nullValue) + } + } + } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultDeserializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultDeserializer.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultDeserializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultDeserializer.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSerializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSerializer.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSerializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSerializer.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSet.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/table/TableResultSet.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala similarity index 96% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala index 63b2114aca..f488e057a2 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultDeserializer.scala @@ -20,9 +20,7 @@ import com.webank.wedatasphere.linkis.common.io.resultset.ResultDeserializer import com.webank.wedatasphere.linkis.storage.domain.Dolphin import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} -/** - * Created by johnnwang on 10/20/18. - */ + class TextResultDeserializer extends ResultDeserializer[LineMetaData, LineRecord]{ override def createMetaData(bytes: Array[Byte]): LineMetaData = { new LineMetaData(Dolphin.getString(bytes, 0, bytes.length)) diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSerializer.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSerializer.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSerializer.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSerializer.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSet.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSet.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/resultset/txt/TextResultSet.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsReader.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsReader.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala similarity index 96% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala index f53fbfb652..2653f127c7 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/ScriptFsWriter.scala @@ -44,7 +44,7 @@ object ParserFactory { } object Compaction { - def listCompactions(): Array[Compaction] = Array(PYScriptCompaction(),QLScriptCompaction(),ScalaScriptCompaction(),ShellScriptCompaction()) + def listCompactions(): Array[Compaction] = Array(PYScriptCompaction(), QLScriptCompaction(), ScalaScriptCompaction(),ShellScriptCompaction()) } trait Parser { diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala similarity index 90% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala index 0ff6250d95..ba39658aab 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/VariableParser.scala @@ -40,14 +40,21 @@ object VariableParser { params.getOrDefault(CONFIGURATION, new util.HashMap[String, Object]) .asInstanceOf[util.Map[String, Object]] .foreach { - f => f._2.asInstanceOf[util.Map[String, Object]].filter(_._2 != null).foreach(p => p._2 match { - case e: util.Map[String, Object] => e.foreach(s => variables += Variable(f._1, p._1, s._1, s._2.toString)) + f => f._2.asInstanceOf[util.Map[String, Object]].filter(s => ! isContextIDINFO(s._1)).foreach(p => p._2 match { + case e: util.Map[String, Object] => { + e.filter(s => ! isContextIDINFO(s._1)).foreach(s => variables += Variable(f._1, p._1, s._1, s._2.toString)) + } case _ => variables += Variable(CONFIGURATION, f._1, p._1, p._2.toString) }) } variables.toArray } + //TODO need delete 20200321 update by peaceWong + def isContextIDINFO(key : String): Boolean ={ + "contextID".equalsIgnoreCase(key) || "nodeName".equalsIgnoreCase(key) + } + def getMap(variables: Array[Variable]): util.Map[String, Object] = { import scala.collection.JavaConversions._ val vars = new util.HashMap[String, String] @@ -72,7 +79,7 @@ object VariableParser { } val params = new util.HashMap[String, Object] if(vars.size() >0)params += VARIABLE -> vars - if(confs.size() >0)params += CONFIGURATION -> confs + if(vars.size() >0)params += CONFIGURATION -> confs params } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/CommonScriptCompaction.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/CommonScriptCompaction.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/CommonScriptCompaction.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/CommonScriptCompaction.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/PYScriptCompaction.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/PYScriptCompaction.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/PYScriptCompaction.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/PYScriptCompaction.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala similarity index 93% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala index a9c0f7a340..6ed790ea6e 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/QLScriptCompaction.scala @@ -16,16 +16,13 @@ package com.webank.wedatasphere.linkis.storage.script.compaction -/** - * Created by johnnwang on 2018/10/24. - */ + class QLScriptCompaction private extends CommonScriptCompaction{ override def belongTo(suffix: String): Boolean = { suffix match { case "sql" => true case "hql" => true - case "jdbc" => true case _ => false } } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ScalaScriptCompaction.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ScalaScriptCompaction.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ScalaScriptCompaction.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ScalaScriptCompaction.scala diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ShellScriptCompaction.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ShellScriptCompaction.scala new file mode 100644 index 0000000000..ab2fe4c934 --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/compaction/ShellScriptCompaction.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.script.compaction + + +class ShellScriptCompaction private extends CommonScriptCompaction{ + override def prefixConf: String = "#conf@set" + + override def prefix: String = "#@set" + + override def belongTo(suffix: String): Boolean ={ + suffix match { + case "sh"=>true + case _=>false + } + } +} +object ShellScriptCompaction{ + val shellScriptCompaction:ShellScriptCompaction=new ShellScriptCompaction + + def apply(): CommonScriptCompaction = shellScriptCompaction +} diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala similarity index 97% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala index a3b7268867..51968ec5e6 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/CommonScriptParser.scala @@ -20,9 +20,7 @@ import com.webank.wedatasphere.linkis.storage.exception.StorageErrorException import com.webank.wedatasphere.linkis.storage.script.{Parser, Variable, VariableParser} -/** - * Created by johnnwang on 2018/10/23. - */ + abstract class CommonScriptParser extends Parser { @scala.throws[StorageErrorException] diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/PYScriptParser.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/PYScriptParser.scala similarity index 100% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/PYScriptParser.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/PYScriptParser.scala diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala similarity index 94% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala index a310031f41..f27ad2995c 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/QLScriptParser.scala @@ -17,7 +17,6 @@ package com.webank.wedatasphere.linkis.storage.script.parser /** - * Created by johnnwang on 2018/10/23. * Parser for .sql and .hql scripts(.sql 和.hql脚本的解析器) */ class QLScriptParser private extends CommonScriptParser { @@ -27,7 +26,6 @@ class QLScriptParser private extends CommonScriptParser { suffix match { case "sql" => true case "hql" => true - case "jdbc" => true case _ => false } } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala similarity index 95% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala index 766537a0ec..ab7f2123cc 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/parser/ScalaScriptParser.scala @@ -16,9 +16,7 @@ package com.webank.wedatasphere.linkis.storage.script.parser -/** - * Created by johnnwang on 2018/11/7. - */ + class ScalaScriptParser private extends CommonScriptParser { //todo To be determined(待定) override def prefix: String = "//@set" diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala similarity index 98% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala index f12675340c..02ac9f5fa9 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/reader/StorageScriptFsReader.scala @@ -26,9 +26,7 @@ import org.apache.commons.io.IOUtils import scala.collection.mutable.ArrayBuffer -/** - * Created by johnnwang on 2018/10/23. - */ + class StorageScriptFsReader(val path: FsPath, val charset: String, val inputStream: InputStream) extends ScriptFsReader { private var inputStreamReader: InputStreamReader = _ diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala similarity index 98% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala index d506944b10..2838b0965e 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/script/writer/StorageScriptFsWriter.scala @@ -25,9 +25,7 @@ import com.webank.wedatasphere.linkis.storage.script.{Compaction, ScriptFsWriter import com.webank.wedatasphere.linkis.storage.utils.{StorageConfiguration, StorageUtils} import org.apache.commons.io.IOUtils -/** - * Created by johnnwang on 2018/10/23. - */ + class StorageScriptFsWriter(val path: FsPath, val charset: String, outputStream: OutputStream = null) extends ScriptFsWriter { private val stringBuilder = new StringBuilder diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/AbstractFileSource.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/AbstractFileSource.scala new file mode 100644 index 0000000000..5f0c8f5169 --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/AbstractFileSource.scala @@ -0,0 +1,64 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.source + +import java.util + +import com.webank.wedatasphere.linkis.common.io.{FsWriter, MetaData, Record} +import org.apache.commons.io.IOUtils +import org.apache.commons.math3.util.Pair + +import scala.collection.JavaConversions._ + + +abstract class AbstractFileSource(var fileSplits: Array[FileSplit]) extends FileSource { + + override def shuffle(s: Record => Record): FileSource = { + fileSplits.foreach(_.shuffler = s) + this + } + + override def page(page: Int, pageSize: Int): FileSource = { + fileSplits.foreach(_.page(page, pageSize)) + this + } + + override def addParams(params: util.Map[String, String]): FileSource = { + fileSplits.foreach(_.addParams(params)) + this + } + + override def addParams(key: String, value: String): FileSource = { + fileSplits.foreach(_.addParams(key, value)) + this + } + + override def getFileSplits: Array[FileSplit] = this.fileSplits + + override def getParams: util.Map[String, String] = fileSplits.map(_.params).foldLeft(Map[String, String]())(_ ++ _) + + override def write[K <: MetaData, V <: Record](fsWriter: FsWriter[K, V]): Unit = fileSplits.foreach(_.write(fsWriter)) + + override def close(): Unit = this.fileSplits.foreach(IOUtils.closeQuietly) + + override def collect(): Array[Pair[Object, util.ArrayList[Array[String]]]] = fileSplits.map(_.collect()) + + override def getTotalLine: Int = this.fileSplits.map(_.totalLine).sum + + override def getTypes: Array[String] = this.fileSplits.map(_.`type`) + +} diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSource.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSource.scala new file mode 100644 index 0000000000..91e3a8c989 --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSource.scala @@ -0,0 +1,120 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.source + +import java.io.{Closeable, InputStream} +import java.util + +import com.webank.wedatasphere.linkis.common.io._ +import com.webank.wedatasphere.linkis.storage.exception.StorageErrorException +import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetReader} +import com.webank.wedatasphere.linkis.storage.script.ScriptFsReader +import com.webank.wedatasphere.linkis.storage.utils.StorageConfiguration +import org.apache.commons.math3.util.Pair + + +trait FileSource extends Closeable { + + def shuffle(s: Record => Record): FileSource + + def page(page: Int, pageSize: Int): FileSource + + def collect(): Array[Pair[Object, util.ArrayList[Array[String]]]] + + def write[K <: MetaData, V <: Record](fsWriter: FsWriter[K, V]): Unit + + def addParams(params: util.Map[String, String]): FileSource + + def addParams(key: String, value: String): FileSource + + def getParams: util.Map[String, String] + + def getTotalLine: Int + + def getTypes: Array[String] + + def getFileSplits: Array[FileSplit] +} + +object FileSource { + + private val fileType = Array("dolphin", "sql", "scala", "py", "hql", "python", "out", "log", "text", "sh", "jdbc") + + private val suffixPredicate = (path: String, suffix: String) => path.endsWith(s".$suffix") + + def isResultSet(path: String): Boolean = { + suffixPredicate(path, fileType.head) + } + + def isResultSet(fsPath: FsPath): Boolean = { + isResultSet(fsPath.getPath) + } + + /** + * 目前只支持table多结果集 + * + * @param fsPaths + * @param fs + * @return + */ + def create(fsPaths: Array[FsPath], fs: Fs): FileSource = { + //非table结果集的过滤掉 + val fileSplits = fsPaths.map(createResultSetFileSplit(_, fs)).filter(isTableResultSet) + new ResultsetFileSource(fileSplits) + } + + private def isTableResultSet(fileSplit: FileSplit): Boolean = fileSplit.`type`.equals(ResultSetFactory.TABLE_TYPE) + + def isTableResultSet(fileSource: FileSource): Boolean = { + //分片中全部为table结果集才返回true + fileSource.getFileSplits.forall(isTableResultSet) + } + + def create(fsPath: FsPath, fs: Fs): FileSource = { + create(fsPath, fs.read(fsPath)) + } + + def create(fsPath: FsPath, is: InputStream): FileSource = { + if (!canRead(fsPath.getPath)) throw new StorageErrorException(54001, "不支持打开的文件类型") + if (isResultSet(fsPath)) { + new ResultsetFileSource(Array(createResultSetFileSplit(fsPath, is))) + } else { + new TextFileSource(Array(createTextFileSplit(fsPath, is))) + } + } + + private def createResultSetFileSplit(fsPath: FsPath, fs: Fs): FileSplit = { + createResultSetFileSplit(fsPath, fs.read(fsPath)) + } + + private def createResultSetFileSplit(fsPath: FsPath, is: InputStream): FileSplit = { + val resultset = ResultSetFactory.getInstance.getResultSetByPath(fsPath) + val resultsetReader = ResultSetReader.getResultSetReader(resultset, is) + new FileSplit(resultsetReader, resultset.resultSetType()) + } + + private def createTextFileSplit(fsPath: FsPath, is: InputStream): FileSplit = { + val scriptFsReader = ScriptFsReader.getScriptFsReader(fsPath, StorageConfiguration.STORAGE_RS_FILE_TYPE.getValue, is) + new FileSplit(scriptFsReader) + } + + private def canRead(path: String): Boolean = { + fileType.exists(suffixPredicate(path, _)) + } + +} + diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSplit.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSplit.scala new file mode 100644 index 0000000000..92e4069fba --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/FileSplit.scala @@ -0,0 +1,117 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.source + +import java.io.Closeable +import java.util + +import com.webank.wedatasphere.linkis.common.io.{FsReader, FsWriter, MetaData, Record} +import com.webank.wedatasphere.linkis.storage.domain.Column +import com.webank.wedatasphere.linkis.storage.resultset.table.{TableMetaData, TableRecord} +import com.webank.wedatasphere.linkis.storage.script.{ScriptMetaData, VariableParser} +import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} +import org.apache.commons.io.IOUtils +import org.apache.commons.math3.util.Pair + +import scala.collection.JavaConversions._ + +/** + * 文件分片..按文件数进行 + */ +class FileSplit(var fsReader: FsReader[_ <: MetaData, _ <: Record], var `type`: String = "script/text") extends Closeable { + + var start: Int = 0 + + var end: Int = -1 + + var count: Int = 0 + + var totalLine = 0 + + var shuffler: Record => Record = r => r + + var pageTrigger: Boolean = false + + var params: util.Map[String, String] = new util.HashMap[String, String] + + def page(page: Int, pageSize: Int): Unit = { + if (!pageTrigger) { + start = (page - 1) * pageSize + end = pageSize * page - 1 + pageTrigger = true + } + } + + def addParams(params: util.Map[String, String]): Unit = { + this.params.putAll(params) + } + + def addParams(key: String, value: String): Unit = { + this.params += key -> value + } + + def `while`[M](m: MetaData => M, r: Record => Unit): M = { + val metaData = fsReader.getMetaData + val t = m(metaData) + while (fsReader.hasNext && ifContinueRead) { + if (ifStartRead) { + r(shuffler(fsReader.getRecord)) + totalLine += 1 + } + count += 1 + } + t + } + + def write[K <: MetaData, V <: Record](fsWriter: FsWriter[K, V]): Unit = { + `while`(fsWriter.addMetaData, fsWriter.addRecord) + } + + def collect(): Pair[Object, util.ArrayList[Array[String]]] = { + val record = new util.ArrayList[Array[String]] + val metaData = `while`(collectMetaData, r => record.add(collectRecord(r))) + new Pair(metaData, record) + } + + def collectRecord(record: Record): Array[String] = { + record match { + case t: TableRecord => t.row.map(_.toString) + case l: LineRecord => Array(l.getLine) + } + } + + def collectMetaData(metaData: MetaData): Object = { + //script/text ,tableResultset,lineResultSet + metaData match { + case s: ScriptMetaData => VariableParser.getMap(s.getMetaData) + case l: LineMetaData => l.getMetaData + case t: TableMetaData => t.columns.map(ColumnToMap) + } + } + + private def ColumnToMap(column: Column): java.util.Map[String, String] = { + Map[String, String]("columnName" -> column.columnName, "comment" -> column.comment, "dataType" -> column.dataType.typeName) + } + + //如果不分页,则一直读,如果分页,则 count需要小于count + def ifContinueRead: Boolean = !pageTrigger || count <= end + + def ifStartRead: Boolean = !pageTrigger || count >= start + + override def close(): Unit = IOUtils.closeQuietly(fsReader) + +} diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala similarity index 83% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala index 4e237e9eb9..942137ca55 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/ResultsetFileSource.scala @@ -19,18 +19,16 @@ package com.webank.wedatasphere.linkis.storage.source import com.webank.wedatasphere.linkis.storage.resultset.table.TableRecord import com.webank.wedatasphere.linkis.storage.utils.StorageUtils -/** - * Created by johnnwang on 2020/1/15. - */ -class ResultsetFileSource extends AbstractFileSource { - shuffler = { +class ResultsetFileSource(fileSplits: Array[FileSplit]) extends AbstractFileSource(fileSplits) { + + shuffle({ case t: TableRecord => new TableRecord(t.row.map { - case null => params.getOrDefault("nullValue", "NULL") + case null | "NULL" | "" => getParams.getOrDefault("nullValue", "NULL") case value: Double => StorageUtils.doubleToString(value) case r => r }) case record => record - } + }) } diff --git a/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/TextFileSource.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/TextFileSource.scala new file mode 100644 index 0000000000..1b97ce9cb1 --- /dev/null +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/source/TextFileSource.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.storage.source + +import java.util + +import com.webank.wedatasphere.linkis.storage.LineRecord +import com.webank.wedatasphere.linkis.storage.script.ScriptRecord +import org.apache.commons.math3.util.Pair + +import scala.collection.JavaConversions._ + + +class TextFileSource(fileSplits: Array[FileSplit]) extends AbstractFileSource(fileSplits) { + + shuffle({ + case s: ScriptRecord if "".equals(s.getLine) => new LineRecord("\n") + case record => record + }) + + override def collect(): Array[Pair[Object, util.ArrayList[Array[String]]]] = { + val collects: Array[Pair[Object, util.ArrayList[Array[String]]]] = super.collect() + if (!getParams.getOrDefault("ifMerge", "true").toBoolean) return collects + val snds: Array[util.ArrayList[Array[String]]] = collects.map(_.getSecond) + snds.foreach { snd => + val str = new StringBuilder + snd.foreach { + case Array("\n") => str.append("\n") + case Array(y) => str.append(y).append("\n") + } + snd.clear() + snd.add(Array(str.toString())) + } + collects + } + +} diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala similarity index 87% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala index 75bd156b95..a9e12d2aaa 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/FileSystemUtils.scala @@ -25,11 +25,23 @@ import com.webank.wedatasphere.linkis.storage.FSFactory import com.webank.wedatasphere.linkis.storage.fs.FileSystem import com.webank.wedatasphere.linkis.storage.fs.impl.LocalFileSystem -/** - * Created by johnnwang on 2018/11/2. - */ + object FileSystemUtils extends Logging{ + def copyFile(filePath: FsPath, origin: FsPath, user: String): Unit = { + val fileSystem = FSFactory.getFsByProxyUser(filePath,user).asInstanceOf[FileSystem] + Utils.tryFinally { + fileSystem.init(null) + if (!fileSystem.exists(filePath)) { + if (!fileSystem.exists(filePath.getParent)) { + fileSystem.mkdirs(filePath.getParent) + } + fileSystem.createNewFile(filePath) + } + fileSystem.copyFile(origin, filePath) + }(Utils.tryQuietly(fileSystem.close())) + } + /** * Create a new file(创建新文件) * @param filePath diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala similarity index 86% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala index c49ae2af18..4456abf2d9 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageConfiguration.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,9 +15,7 @@ package com.webank.wedatasphere.linkis.storage.utils import com.webank.wedatasphere.linkis.common.conf.{ByteType, CommonVars} -/** - * Created by johnnwang on 10/15/18. - */ + object StorageConfiguration { val PROXY_USER = CommonVars("wds.linkis.storage.proxy.user", "${UM}") @@ -48,8 +43,8 @@ object StorageConfiguration { val IO_USER = CommonVars("wds.linkis.storage.io.user", "root") val IO_FS_EXPIRE_TIME = CommonVars("wds.linkis.storage.io.fs.num", 1000*60*10) - val IO_PROXY_READ_FETCH_SIZE = CommonVars("wds.linkis.storage.io.read.fetch.size", new ByteType("100k")) - val IO_PROXY_WRITE_CACHE_SIZE = CommonVars("wds.linkis.storage.io.write.cache.size", new ByteType("64k")) + val IO_PROXY_READ_FETCH_SIZE = CommonVars("wds.linkis.storage.io.read.fetch.size", new ByteType("100k")) + val IO_PROXY_WRITE_CACHE_SIZE = CommonVars("wds.linkis.storage.io.write.cache.size", new ByteType("64k")) val IO_DEFAULT_CREATOR = CommonVars("wds.linkis.storage.io.default.creator", "ujes") val IO_FS_RE_INIT = CommonVars("wds.linkis.storage.io.fs.re.init", "re-init") @@ -59,4 +54,9 @@ object StorageConfiguration { val STORAGE_HDFS_GROUP = CommonVars("wds.linkis.storage.fileSystem.hdfs.group", "hadoop") val DOUBLE_FRACTION_LEN = CommonVars[Int]("wds.linkis.double.fraction.length", 30) + + val HDFS_PATH_PREFIX_CHECK_ON = CommonVars[Boolean]("wds.linkis.storage.hdfs.prefix_check.enable", true) + + val HDFS_PATH_PREFIX_REMOVE = CommonVars[Boolean]("wds.linkis.storage.hdfs.prefxi.remove", true) + } diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala similarity index 97% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala index c4b2f1555c..aea30c535a 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageHelper.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,9 +17,7 @@ import com.webank.wedatasphere.linkis.storage.FSFactory import com.webank.wedatasphere.linkis.storage.resultset.table.{TableMetaData, TableRecord} import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetReader} -/** - * Created by johnnwang on 2019/3/7. - */ + object StorageHelper { def main(args: Array[String]): Unit = { @@ -41,7 +36,8 @@ object StorageHelper { /** * Get the number of table result set file lines(获得表格结果集文件行数) - * @param path + * + * @param args */ def getTableResLines(args: Array[String]) = { val resPath = StorageUtils.getFsPath(args(0)) diff --git a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala similarity index 94% rename from storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala rename to linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala index 5a57a051f5..e6d620e48d 100644 --- a/storage/storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala +++ b/linkis-commons/linkis-storage/src/main/scala/com/webank/wedatasphere/linkis/storage/utils/StorageUtils.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,9 +17,9 @@ import java.io.{Closeable, File, InputStream, OutputStream} import java.lang.reflect.Method import java.text.NumberFormat -import com.webank.wedatasphere.linkis.common.conf.Configuration import com.webank.wedatasphere.linkis.common.io.{Fs, FsPath} import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.hadoop.common.conf.HadoopConf import com.webank.wedatasphere.linkis.storage.exception.StorageFatalException import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetReader, ResultSetWriter} import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} @@ -30,14 +27,10 @@ import org.apache.commons.lang.StringUtils import scala.collection.mutable -/** - * Created by johnnwang on 10/17/18. - */ object StorageUtils extends Logging{ val HDFS = "hdfs" val FILE = "file" - val FIXED_INSTANCE = "fixedInstance" val FILE_SCHEMA = "file://" val HDFS_SCHEMA = "hdfs://" @@ -170,7 +163,7 @@ object StorageUtils extends Logging{ def getJvmUser:String = System.getProperty("user.name") def isHDFSNode:Boolean = { - val confPath = new File(Configuration.hadoopConfDir) + val confPath = new File(HadoopConf.hadoopConfDir) //TODO IO-client mode need return false if(!confPath.exists() || confPath.isFile) throw new StorageFatalException(50001, "HDFS configuration was not read, please configure hadoop.config.dir or add env:HADOOP_CONF_DIR") @@ -201,4 +194,15 @@ object StorageUtils extends Logging{ count } + def colToString(col:Any,nullValue:String = "NULL"):String ={ + if(null == col) nullValue + else { + col match { + case value:Double => doubleToString(value) + case "NULL" | "" => nullValue + case _ => col.toString + } + } + } + } diff --git a/linkis-commons/pom.xml b/linkis-commons/pom.xml new file mode 100644 index 0000000000..2386704c59 --- /dev/null +++ b/linkis-commons/pom.xml @@ -0,0 +1,29 @@ + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../pom.xml + + + 4.0.0 + + linkis-commons + pom + + linkis-common + linkis-hadoop-common + linkis-httpclient + linkis-protocol + linkis-scheduler + linkis-module + linkis-mybatis + linkis-rpc + linkis-message-scheduler + linkis-storage + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-client/pom.xml b/linkis-computation-governance/linkis-computation-client/pom.xml new file mode 100644 index 0000000000..32fd07fcc5 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/pom.xml @@ -0,0 +1,90 @@ + + + + + 4.0.0 + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + linkis-computation-client + + + + com.webank.wedatasphere.linkis + linkis-gateway-httpclient-support + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + + + com.google.code.gson + gson + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + **/*.yml + **/*.properties + **/*.sh + **/log4j2.xml + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + \ No newline at end of file diff --git a/eurekaServer/src/main/resources/log4j.properties b/linkis-computation-governance/linkis-computation-client/src/main/resources/log4j.properties similarity index 100% rename from eurekaServer/src/main/resources/log4j.properties rename to linkis-computation-governance/linkis-computation-client/src/main/resources/log4j.properties diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala similarity index 87% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala index 243d57de87..9f058f64b2 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClient.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client import java.io.Closeable @@ -31,13 +27,12 @@ import com.webank.wedatasphere.linkis.ujes.client.request.JobExecIdAction.JobSer import com.webank.wedatasphere.linkis.ujes.client.request._ import com.webank.wedatasphere.linkis.ujes.client.response._ -/** - * created by cooperyang on 2019/5/23. - */ abstract class UJESClient extends Closeable { def execute(jobExecuteAction: JobExecuteAction): JobExecuteResult = executeUJESJob(jobExecuteAction).asInstanceOf[JobExecuteResult] + def submit(jobSubmitAction: JobSubmitAction): JobSubmitResult = executeUJESJob(jobSubmitAction).asInstanceOf[JobSubmitResult] + protected[client] def executeUJESJob(ujesJobAction: UJESJobAction): Result private def executeJobExecIdAction[T](jobExecuteResult: JobExecuteResult, jobServiceType: JobServiceType.JobServiceType): T = { @@ -65,8 +60,6 @@ abstract class UJESClient extends Closeable { def kill(jobExecuteResult: JobExecuteResult): JobKillResult = executeJobExecIdAction(jobExecuteResult, JobServiceType.JobKill) - - def pause(jobExecuteResult: JobExecuteResult): JobPauseResult = executeJobExecIdAction(jobExecuteResult, JobServiceType.JobPause) def getJobInfo(jobExecuteResult: JobExecuteResult): JobInfoResult = { @@ -76,6 +69,19 @@ abstract class UJESClient extends Closeable { def resultSet(resultSetAction: ResultSetAction): ResultSetResult = executeUJESJob(resultSetAction).asInstanceOf[ResultSetResult] + + def getDBS(getDBSAction: GetDBSAction): GetDBSResult = { + executeUJESJob(getDBSAction).asInstanceOf[GetDBSResult] + } + + def getTables(getTableAction: GetTablesAction): GetTablesResult = { + executeUJESJob(getTableAction).asInstanceOf[GetTablesResult] + } + + def getColumns(getColumnsAction: GetColumnsAction): GetColumnsResult = { + executeUJESJob(getColumnsAction).asInstanceOf[GetColumnsResult] + } + } object UJESClient { def apply(clientConfig: DWSClientConfig): UJESClient = new UJESClientImpl(clientConfig) @@ -87,7 +93,7 @@ object UJESClient { def apply(serverUrl: String, readTimeout: Int, maxConnection: Int, authenticationStrategy: AuthenticationStrategy, dwsVersion: String): UJESClient = { - val clientConfig = DWSClientConfigBuilder.newBuilder().addUJESServerUrl(serverUrl) + val clientConfig = DWSClientConfigBuilder.newBuilder().addServerUrl(serverUrl) .connectionTimeout(30000).discoveryEnabled(false) .loadbalancerEnabled(false).maxConnectionSize(maxConnection) .retryEnabled(false).readTimeout(readTimeout) @@ -103,7 +109,7 @@ object UJESClient { def getDiscoveryClient(serverUrl: String, readTimeout: Int, maxConnection: Int, authenticationStrategy: AuthenticationStrategy, dwsVersion: String): UJESClient = { - val clientConfig = DWSClientConfigBuilder.newBuilder().addUJESServerUrl(serverUrl) + val clientConfig = DWSClientConfigBuilder.newBuilder().addServerUrl(serverUrl) .connectionTimeout(30000).discoveryEnabled(true) .discoveryFrequency(1, TimeUnit.MINUTES) .loadbalancerEnabled(true).maxConnectionSize(maxConnection) diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala similarity index 93% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala index ea8707e81c..f2e609fa47 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/UJESClientImpl.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client import com.webank.wedatasphere.linkis.httpclient.dws.DWSHttpClient import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfig @@ -25,9 +21,6 @@ import com.webank.wedatasphere.linkis.httpclient.request.Action import com.webank.wedatasphere.linkis.httpclient.response.Result import com.webank.wedatasphere.linkis.ujes.client.request.UJESJobAction -/** - * created by cooperyang on 2019/5/23. - */ class UJESClientImpl(clientConfig: DWSClientConfig) extends UJESClient { private val dwsHttpClient = new DWSHttpClient(clientConfig, "UJES-Job-Execution-Thread") override protected[client] def executeUJESJob(ujesJobAction: UJESJobAction): Result = ujesJobAction match { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala similarity index 90% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala index 15ce6e608d..cc03cde92b 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/exception/UJESClientBuilderException.scala @@ -14,17 +14,10 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by cooperyang on 2019/5/23. - */ class UJESClientBuilderException(errorDesc: String) extends ErrorException(47000, errorDesc) class UJESJobException(errorCode: Int, errorDesc: String) extends ErrorException(errorCode, errorDesc) { def this(errorDesc: String) = this(47001, errorDesc) diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetColumnsAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetColumnsAction.scala new file mode 100644 index 0000000000..5cc633f2bf --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetColumnsAction.scala @@ -0,0 +1,62 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.request + +import com.webank.wedatasphere.linkis.httpclient.request.GetAction +import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException + +class GetColumnsAction extends GetAction with UJESJobAction { + override def suffixURLs: Array[String] = Array("datasource", "columns") +} +object GetColumnsAction { + def builder(): Builder = new Builder + class Builder private[GetColumnsAction]() { + + private var user: String = _ + + private var database: String = _ + + private var table: String = _ + + def setUser(user: String): Builder = { + this.user = user + this + } + + def setDatabase(database: String): Builder = { + this.database = database + this + } + + def setTable(table: String): Builder = { + this.table = table + this + } + + def build(): GetColumnsAction = { + if(user == null) throw new UJESClientBuilderException("user is needed!") + if(database == null) throw new UJESClientBuilderException("database is needed!") + val getColumnsAction = new GetColumnsAction + getColumnsAction.setUser(user) + getColumnsAction.setParameter("database", database) + getColumnsAction.setParameter("table", table) + getColumnsAction + } + } +} + + diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetDBSAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetDBSAction.scala new file mode 100644 index 0000000000..5242396fa8 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetDBSAction.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.request + +import com.webank.wedatasphere.linkis.httpclient.request.GetAction +import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException + +class GetDBSAction extends GetAction with UJESJobAction { + override def suffixURLs: Array[String] = Array("datasource", "dbs") +} +object GetDBSAction { + def builder(): Builder = new Builder + class Builder private[GetDBSAction]() { + private var user: String = _ + + def setUser(user: String): Builder = { + this.user = user + this + } + + + def build(): GetDBSAction = { + if(user == null) throw new UJESClientBuilderException("user is needed!") + val getDBSAction = new GetDBSAction + getDBSAction.setUser(user) + getDBSAction + } + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetTablesAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetTablesAction.scala new file mode 100644 index 0000000000..c244aa91bd --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/GetTablesAction.scala @@ -0,0 +1,55 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.request + +import com.webank.wedatasphere.linkis.httpclient.request.GetAction +import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException + +class GetTablesAction extends GetAction with UJESJobAction { + override def suffixURLs: Array[String] = Array("datasource", "tables") +} + +object GetTablesAction { + def builder(): Builder = new Builder + class Builder private[GetTablesAction]() { + + private var user: String = _ + + private var database: String = _ + + def setUser(user: String): Builder = { + this.user = user + this + } + + def setDatabase(database: String): Builder = { + this.database = database + this + } + + + def build(): GetTablesAction = { + if(user == null) throw new UJESClientBuilderException("user is needed!") + if(database == null) throw new UJESClientBuilderException("database is needed!") + val getTableAction = new GetTablesAction + getTableAction.setUser(user) + getTableAction.setParameter("database", database) + getTableAction + } + + } +} diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala similarity index 96% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala index 982e8cf080..9587c96c80 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecIdAction.scala @@ -14,18 +14,11 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import com.webank.wedatasphere.linkis.httpclient.request.GetAction import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException -/** - * created by cooperyang on 2019/5/23. - */ class JobExecIdAction private() extends GetAction with UJESJobAction { private var execId: String = _ diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala similarity index 92% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala index e9f02f514c..ccdacbbe48 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobExecuteAction.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import java.util @@ -29,9 +25,6 @@ import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException import org.apache.commons.lang.StringUtils -/** - * created by cooperyang on 2019/5/23. - */ class JobExecuteAction private() extends POSTAction with UJESJobAction { override def suffixURLs: Array[String] = Array("entrance", "execute") override def getRequestPayload: String = DWSHttpClient.jacksonJson.writeValueAsString(getRequestPayloads) @@ -125,15 +118,6 @@ object JobExecuteAction { TaskUtils.addSpecialMap(this.params, specialMap) this } - - def setDatasourceParams(datasourceMap: util.Map[String, Any]): Builder = { - if(this.params == null) this synchronized { - if(this.params == null) this.params = new util.HashMap[String, Any] - } - var runtimeMap:util.Map[String, Any] = TaskUtils.getRuntimeMap(this.params) - TaskUtils.addDatasourceMap(runtimeMap, datasourceMap) - this - } def setVariableMap(variableMap: util.Map[String, Any]): Builder = { if(this.params == null) this synchronized { if(this.params == null) this.params = new util.HashMap[String, Any] @@ -163,8 +147,11 @@ object JobExecuteAction { if(formatCode) executeAction.addRequestPayload(TaskConstant.FORMATCODE, true) if(StringUtils.isBlank(creator)) throw new UJESClientBuilderException("creator is needed!") executeAction.addRequestPayload(TaskConstant.REQUESTAPPLICATIONNAME, creator) - if(StringUtils.isEmpty(scriptPath) && StringUtils.isEmpty(executeCode)) + if(StringUtils.isEmpty(scriptPath) && StringUtils.isEmpty(executeCode) && params == null) throw new UJESClientBuilderException("scriptPath or executeCode is needed!") + if(StringUtils.isEmpty(scriptPath) && StringUtils.isEmpty(executeCode)) { + addExecuteCode(params.toString) + } executeAction.addRequestPayload(TaskConstant.EXECUTIONCODE, executeCode) executeAction.addRequestPayload(TaskConstant.SCRIPTPATH, scriptPath) if(params == null) params = new util.HashMap[String, Any]() @@ -216,12 +203,13 @@ object JobExecuteAction { } override def getDefaultRunType: RunType = PY } - val JDBC = new EngineType{ + + val JDBC = new EngineType { override val toString: String = "jdbc" - val JC = new RunType { + val JDBC_RunType = new RunType { override val toString: String = "jdbc" } - override def getDefaultRunType: RunType = JC + override def getDefaultRunType: RunType = JDBC_RunType } } } diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala similarity index 95% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala index 2366d40a9d..1ea1911579 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobInfoAction.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import com.webank.wedatasphere.linkis.httpclient.request.GetAction @@ -25,9 +21,6 @@ import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderExc import com.webank.wedatasphere.linkis.ujes.client.response.JobExecuteResult import org.apache.commons.lang.StringUtils -/** - * created by cooperyang on 2019/5/23. - */ class JobInfoAction extends GetAction with UJESJobAction { private var taskId: String = _ override def suffixURLs: Array[String] = Array("jobhistory", taskId, "get") diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala similarity index 95% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala index 71224b4b8d..7a406874d2 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobLogAction.scala @@ -14,19 +14,12 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import com.webank.wedatasphere.linkis.httpclient.request.GetAction import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException import com.webank.wedatasphere.linkis.ujes.client.response.JobLogResult -/** - * created by cooperyang on 2019/5/23. - */ class JobLogAction private() extends GetAction with UJESJobAction { private var execId: String = _ diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobSubmitAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobSubmitAction.scala new file mode 100644 index 0000000000..7a5ce20b8d --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/JobSubmitAction.scala @@ -0,0 +1,152 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.request + +import java.util + +import com.webank.wedatasphere.linkis.httpclient.dws.DWSHttpClient +import com.webank.wedatasphere.linkis.httpclient.request.POSTAction +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException +import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.{Builder, RunType} + +class JobSubmitAction private() extends POSTAction with UJESJobAction { + override def suffixURLs: Array[String] = Array("entrance", "submit") + + override def getRequestPayload: String = DWSHttpClient.jacksonJson.writeValueAsString(getRequestPayloads) +} + +object JobSubmitAction { + def builder(): Builder = new Builder + + class Builder private[JobSubmitAction]() { + private var user: String = _ + + private var executeUser: String = _ + + private var executionContent: util.Map[String, Any] = _ + + private var formatCode: Boolean = false + + private var labels: util.Map[String, Any] = _ + + private var params: util.Map[String, Any] = _ + + private var source: util.Map[String, Any] = _ + + def addExecuteCode(executeCode: String): Builder = { + if ( null == executionContent ) executionContent = new util.HashMap[String, Any]() + executionContent.put("code", executeCode) + this + } + + def setRunTypeStr(runTypeStr: String): Builder = { + if ( null == executionContent ) executionContent = new util.HashMap[String, Any]() + executionContent.put("runType", runTypeStr) + this + } + + def setUser(user: String): Builder = { + this.user = user + this + } + + def addExecuteUser(executeUser: String): Builder = { + this.executeUser = executeUser + this + } + + def enableFormatCode(): Builder = { + this.formatCode = true + this + } + + def setExecutionContent(executionContent: util.Map[String, Any]): Builder = { + this.executionContent = executionContent + this + } + + def setLabels(labels: util.Map[String, Any]): Builder = { + this.labels = labels + this + } + + def setParams(params: util.Map[String, Any]): Builder = { + this.synchronized(this.params = params) + this + } + + def setSource(source: util.Map[String, Any]): Builder = { + this.synchronized(this.source = source) + this + } + + def setStartupParams(startupMap: util.Map[String, Any]): Builder = { + if (this.params == null) this synchronized { + if (this.params == null) this.params = new util.HashMap[String, Any] + } + TaskUtils.addStartupMap(this.params, startupMap) + this + } + + def setRuntimeParams(runtimeMap: util.Map[String, Any]): Builder = { + if (this.params == null) this synchronized { + if (this.params == null) this.params = new util.HashMap[String, Any] + } + TaskUtils.addRuntimeMap(this.params, runtimeMap) + this + } + + def setSpecialParams(specialMap: util.Map[String, Any]): Builder = { + if (this.params == null) this synchronized { + if (this.params == null) this.params = new util.HashMap[String, Any] + } + TaskUtils.addSpecialMap(this.params, specialMap) + this + } + + def setVariableMap(variableMap: util.Map[String, Any]): Builder = { + if (this.params == null) this synchronized { + if (this.params == null) this.params = new util.HashMap[String, Any] + } + TaskUtils.addSpecialMap(this.params, variableMap) + this + } + + + def build(): JobSubmitAction = { + val submitAction = new JobSubmitAction + submitAction.setUser(user) + submitAction.addRequestPayload(TaskConstant.EXECUTE_USER, executeUser) + if (formatCode) submitAction.addRequestPayload(TaskConstant.FORMATCODE, true) + if (executionContent == null && params == null) + throw new UJESClientBuilderException("executionContent is needed!") + submitAction.addRequestPayload(TaskConstant.EXECUTION_CONTENT, executionContent) + if (params == null) params = new util.HashMap[String, Any]() + submitAction.addRequestPayload(TaskConstant.PARAMS, params) + if (this.source == null) this.source = new util.HashMap[String, Any]() + submitAction.addRequestPayload(TaskConstant.SOURCE, this.source) + + if (this.labels == null) this.labels = new util.HashMap[String, Any]() + submitAction.addRequestPayload(TaskConstant.LABELS, this.labels) + submitAction + } + } + +} + diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala similarity index 95% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala index 9fd9b1e1ce..9862f343e7 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetAction.scala @@ -14,19 +14,12 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import com.webank.wedatasphere.linkis.common.conf.Configuration import com.webank.wedatasphere.linkis.httpclient.request.GetAction import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException -/** - * created by cooperyang on 2019/5/23. - */ class ResultSetAction private() extends GetAction with UJESJobAction { override def suffixURLs: Array[String] = Array("filesystem", "openFile") } diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala similarity index 95% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala index 3c8871d632..b549038406 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/ResultSetListAction.scala @@ -14,9 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ package com.webank.wedatasphere.linkis.ujes.client.request @@ -24,9 +21,6 @@ import com.webank.wedatasphere.linkis.httpclient.request.GetAction import com.webank.wedatasphere.linkis.ujes.client.exception.UJESClientBuilderException import com.webank.wedatasphere.linkis.ujes.client.response.JobInfoResult -/** - * created by cooperyang on 2019/5/23. - */ class ResultSetListAction extends GetAction with UJESJobAction { override def suffixURLs: Array[String] = Array("filesystem", "getDirFileTrees") } diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala similarity index 88% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala index 246f124a03..a402be05e3 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UJESJobAction.scala @@ -14,15 +14,8 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request import com.webank.wedatasphere.linkis.httpclient.dws.request.DWSHttpAction -/** - * created by cooperyang on 2019/5/23. - */ trait UJESJobAction extends DWSHttpAction with UserAction diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala similarity index 89% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala index a53b43af93..0542e16a7c 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/request/UserAction.scala @@ -14,15 +14,8 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.request -/** - * created by cooperyang on 2019/5/23. - */ trait UserAction extends com.webank.wedatasphere.linkis.httpclient.request.UserAction { private var user: String = _ diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetColumnsResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetColumnsResult.scala new file mode 100644 index 0000000000..9d69105235 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetColumnsResult.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.response + +import java.util + +import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult +import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult +import com.webank.wedatasphere.linkis.ujes.client.request.UserAction + +import scala.beans.BeanProperty + +@DWSHttpMessageResult("/api/rest_j/v\\d+/datasource/columns") +class GetColumnsResult extends DWSResult with UserAction { + @BeanProperty var columns: util.List[util.Map[String, Object]] = _ +} diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetDBSResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetDBSResult.scala new file mode 100644 index 0000000000..4ff78538d6 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetDBSResult.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.response + +import java.util + +import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult +import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult +import com.webank.wedatasphere.linkis.ujes.client.request.UserAction +import org.apache.commons.collections.CollectionUtils + +import scala.beans.BeanProperty +import scala.collection.JavaConversions._ + +@DWSHttpMessageResult("/api/rest_j/v\\d+/datasource/dbs") +class GetDBSResult extends DWSResult with UserAction { + @BeanProperty var dbs: util.List[util.Map[String, String]] = _ + + def getDBSName(): util.List[String] = { + val dbsList = new util.ArrayList[String]() + if (CollectionUtils.isNotEmpty(dbs)) { + dbs.foreach { db => + dbsList.add(db.get("dbName")) + } + } + dbsList + } +} diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetTablesResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetTablesResult.scala new file mode 100644 index 0000000000..aea26ee4cf --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/GetTablesResult.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.response + +import java.util + +import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult +import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult +import com.webank.wedatasphere.linkis.ujes.client.request.UserAction + +import scala.beans.BeanProperty + +@DWSHttpMessageResult("/api/rest_j/v\\d+/datasource/tables") +class GetTablesResult extends DWSResult with UserAction { + @BeanProperty var tables: util.List[util.Map[String, Object]] = _ +} diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala similarity index 90% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala index 5e7292b44a..8ea9cdade5 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobExecuteResult.scala @@ -14,19 +14,12 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult import scala.beans.BeanProperty -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/execute") class JobExecuteResult extends UJESJobResult { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala similarity index 94% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala index 61c84b19df..81eac591ed 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobInfoResult.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -14,9 +11,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ package com.webank.wedatasphere.linkis.ujes.client.response @@ -24,17 +18,14 @@ import java.util import java.util.Date import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.ujes.client.UJESClient import com.webank.wedatasphere.linkis.ujes.client.exception.UJESJobException import com.webank.wedatasphere.linkis.ujes.client.request.{ResultSetListAction, UserAction} import org.apache.commons.beanutils.BeanUtils -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/jobhistory/\\S+/get") class JobInfoResult extends DWSResult with UserAction with Status { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala similarity index 89% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala index d90f726e48..5ed0f9ff3e 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobKillResult.scala @@ -14,16 +14,9 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/(\\S+)/kill") class JobKillResult extends UJESJobResult diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala similarity index 91% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala index 8a7d34865a..b37dfab256 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobLogResult.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import java.util @@ -26,9 +22,6 @@ import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageRe import scala.beans.BeanProperty -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/(\\S+)/log") class JobLogResult extends UJESJobResult { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala similarity index 89% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala index 01d782175b..3faf136fad 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobPauseResult.scala @@ -14,16 +14,9 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/(\\S+)/pause") class JobPauseResult extends UJESJobResult diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala similarity index 94% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala index b6988eb729..7e9ab4e204 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobProgressResult.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import java.util.{List, Map} @@ -29,9 +25,6 @@ import org.json4s.jackson.Serialization._ import scala.collection.JavaConversions._ -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/(\\S+)/progress") class JobProgressResult extends UJESJobResult { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala similarity index 93% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala index 2384ddaadd..88eadc87d1 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobStatusResult.scala @@ -14,17 +14,10 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/(\\S+)/status") class JobStatusResult extends UJESJobResult with Status { diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobSubmitResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobSubmitResult.scala new file mode 100644 index 0000000000..02089d60df --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/JobSubmitResult.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.webank.wedatasphere.linkis.ujes.client.response + +import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult + +import scala.beans.BeanProperty + +@DWSHttpMessageResult("/api/rest_j/v\\d+/entrance/submit") +class JobSubmitResult extends JobExecuteResult { + + +} diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala similarity index 93% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala index a02b78b549..27d5300951 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetListResult.scala @@ -14,24 +14,18 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ package com.webank.wedatasphere.linkis.ujes.client.response -import scala.beans.BeanProperty import java.util import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult import com.webank.wedatasphere.linkis.ujes.client.request.UserAction +import scala.beans.BeanProperty import scala.collection.JavaConversions._ -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/filesystem/getDirFileTrees") class ResultSetListResult extends DWSResult with UserAction { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala similarity index 93% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala index 444acc51a1..8ad8a5d8ab 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/ResultSetResult.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.annotation.DWSHttpMessageResult @@ -26,9 +22,6 @@ import com.webank.wedatasphere.linkis.ujes.client.request.UserAction import scala.beans.BeanProperty -/** - * created by cooperyang on 2019/5/23. - */ @DWSHttpMessageResult("/api/rest_j/v\\d+/filesystem/openFile") class ResultSetResult extends DWSResult with UserAction { diff --git a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala similarity index 91% rename from ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala rename to linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala index bf2493ff28..ebcc6ea652 100644 --- a/ujes/client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/response/UJESJobResult.scala @@ -14,18 +14,11 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client.response import com.webank.wedatasphere.linkis.httpclient.dws.response.DWSResult import com.webank.wedatasphere.linkis.ujes.client.request.UserAction -/** - * created by cooperyang on 2019/5/23. - */ trait UJESJobResult extends DWSResult with UserAction { private var execID: String = _ diff --git a/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/utils/UJESClientUtils.scala b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/utils/UJESClientUtils.scala new file mode 100644 index 0000000000..6b79e9a61d --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/main/scala/com/webank/wedatasphere/linkis/ujes/client/utils/UJESClientUtils.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.client.utils + +import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.{EngineType, RunType} + +object UJESClientUtils { + def toEngineType(engineType: String): EngineType = engineType match { + case "spark" => EngineType.SPARK + case "hive" => EngineType.HIVE + case "shell" => EngineType.SHELL + case "python" => EngineType.PYTHON + case _ => EngineType.SPARK + } + + /** + * TODO At first Judge engine type + * @param runType + * @param engineType + * @return + */ + def toRunType(runType:String, engineType: EngineType) : RunType = runType match { + case "sql" => EngineType.SPARK.SQL + case "pyspark" => EngineType.SPARK.PYSPARK + case "scala" => EngineType.SPARK.SCALA + case "r" => EngineType.SPARK.R + case "hql" => EngineType.HIVE.HQL + case "shell" => EngineType.SHELL.SH + case "python" => EngineType.PYTHON.PY + case _ => EngineType.SPARK.SQL + } + +} diff --git a/ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTest.scala b/linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTest.scala similarity index 92% rename from ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTest.scala rename to linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTest.scala index db1f3b21e1..74c271385f 100644 --- a/ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTest.scala +++ b/linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTest.scala @@ -14,10 +14,6 @@ * limitations under the License. */ -/* - * created by cooperyang on 2019/07/24. - */ - package com.webank.wedatasphere.linkis.ujes.client import java.util.concurrent.TimeUnit @@ -29,12 +25,9 @@ import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.Engin import com.webank.wedatasphere.linkis.ujes.client.request.{JobExecuteAction, ResultSetAction} import org.apache.commons.io.IOUtils -/** - * created by cooperyang on 2019/5/23. - */ object UJESClientImplTest extends App { - val clientConfig = DWSClientConfigBuilder.newBuilder().addUJESServerUrl("http://localhost:port") + val clientConfig = DWSClientConfigBuilder.newBuilder().addServerUrl("http://localhost:port") .connectionTimeout(30000).discoveryEnabled(true) .discoveryFrequency(1, TimeUnit.MINUTES) .loadbalancerEnabled(true).maxConnectionSize(5) diff --git a/ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTestJ.java b/linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTestJ.java similarity index 92% rename from ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTestJ.java rename to linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTestJ.java index 3c9319c021..bd302e7b9b 100644 --- a/ujes/client/src/test/java/com/webank/bdp/dataworkcloud/ujes/client/UJESClientImplTestJ.java +++ b/linkis-computation-governance/linkis-computation-client/src/test/java/com/webank/wedatasphere/linkis/ujes/client/UJESClientImplTestJ.java @@ -14,14 +14,12 @@ * limitations under the License. */ -package com.webank.bdp.dataworkcloud.ujes.client; +package com.webank.wedatasphere.linkis.ujes.client; import com.webank.wedatasphere.linkis.common.utils.Utils; import com.webank.wedatasphere.linkis.httpclient.dws.authentication.StaticAuthenticationStrategy; import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfig; import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfigBuilder; -import com.webank.wedatasphere.linkis.ujes.client.UJESClient; -import com.webank.wedatasphere.linkis.ujes.client.UJESClientImpl; import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction; import com.webank.wedatasphere.linkis.ujes.client.request.ResultSetAction; import com.webank.wedatasphere.linkis.ujes.client.response.JobExecuteResult; @@ -35,7 +33,7 @@ public class UJESClientImplTestJ{ public static void main(String[] args){ - DWSClientConfig clientConfig = ((DWSClientConfigBuilder) (DWSClientConfigBuilder.newBuilder().addUJESServerUrl("http://localhost:port") + DWSClientConfig clientConfig = ((DWSClientConfigBuilder) (DWSClientConfigBuilder.newBuilder().addServerUrl("http://localhost:port") .connectionTimeout(30000).discoveryEnabled(true) .discoveryFrequency(1, TimeUnit.MINUTES) .loadbalancerEnabled(true).maxConnectionSize(5) diff --git a/linkis-computation-governance/linkis-computation-client/src/test/scala/com/webank/wedatasphere/linkis/ujes/UJESClientImplBigResultSetDemo.scala b/linkis-computation-governance/linkis-computation-client/src/test/scala/com/webank/wedatasphere/linkis/ujes/UJESClientImplBigResultSetDemo.scala new file mode 100644 index 0000000000..99513176cc --- /dev/null +++ b/linkis-computation-governance/linkis-computation-client/src/test/scala/com/webank/wedatasphere/linkis/ujes/UJESClientImplBigResultSetDemo.scala @@ -0,0 +1,193 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes + +import java.util.concurrent.TimeUnit + +import com.google.gson.Gson +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.httpclient.dws.authentication.TokenAuthenticationStrategy +import com.webank.wedatasphere.linkis.httpclient.dws.config.{DWSClientConfig, DWSClientConfigBuilder} +import com.webank.wedatasphere.linkis.ujes.client.UJESClient +import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.EngineType +import com.webank.wedatasphere.linkis.ujes.client.request.{JobExecuteAction, ResultSetAction} +import com.webank.wedatasphere.linkis.ujes.client.response.JobExecuteResult +import org.apache.commons.io.IOUtils + + +object UJESClientImplBigResultSetDemo { + + + def main(args: Array[String]): Unit = { + +// var executeCode = "--set ide.engine.no.limit.allow=true; \n use ai_caixin_ads_ods_mask; \n select * from caixin_click_from_mysql limit 60000;" +// var executeCode = "--set ide.engine.no.limit.allow=true; \n use hduser02db; \n select zjyilush from t_history_kaps_zjyils limit 1001;" + var executeCode = "show tables" +// var user = "jianfuzhang" + var user = "hadoop" + + if (args.length > 2) { + helpPrint(user, executeCode) + return Unit + } else if (args.length > 1) { + user = args(0) + executeCode = args(1) + } else if (args.length > 0) { + user = args(0) + } + + val startTime = System.currentTimeMillis() + val clientConfig = buildConfig() + + // 2. 通过DWSClientConfig获取一个UJESClient + val client = UJESClient(clientConfig) + + val jobExecuteResult = executeJob(client, user, executeCode) + if (null == jobExecuteResult) { + IOUtils.closeQuietly(client) + } + getResult(client, jobExecuteResult, startTime) + + } + + def helpPrint(user : String, code : String, fullPrint : Boolean = false) = { + println("Usage: java demo.jar user [sql code] , only accept less than two params.") + if (fullPrint) println("user is : " + user + " , code : [" + code + "]") + } + + val COMMON_AUTH_KEY : String = "Validation-Code" + + private def buildConfig() : DWSClientConfig = { + // 1. 配置DWSClientBuilder,通过DWSClientBuilder获取一个DWSClientConfig + val clientConfig = DWSClientConfigBuilder.newBuilder() + .addServerUrl("http://127.0.0.1:9001") //指定ServerUrl,Linkis服务器端网关的地址,如http://{ip}:{port} + // .addUJESServerUrl("http://127.0.0.1:9001") //指定ServerUrl,Linkis服务器端网关的地址,如http://{ip}:{port} + .connectionTimeout(30000) //connectionTimeOut 客户端连接超时时间 + .discoveryEnabled(false).discoveryFrequency(1, TimeUnit.MINUTES) //是否启用注册发现,如果启用,会自动发现新启动的Gateway + .loadbalancerEnabled(true) // 是否启用负载均衡,如果不启用注册发现,则负载均衡没有意义 + .maxConnectionSize(5) //指定最大连接数,即最大并发数 + .retryEnabled(false).readTimeout(30000) //执行失败,是否允许重试 + .setAuthenticationStrategy(new TokenAuthenticationStrategy()) //AuthenticationStrategy Linkis认证方式 +// .setAuthTokenKey("jianfuzhang").setAuthTokenValue("fcg123456") //认证key,一般为用户名; 认证value,一般为用户名对应的密码 + .setAuthTokenKey(COMMON_AUTH_KEY).setAuthTokenValue("BML-AUTH") //认证key,一般为用户名; 认证value,一般为用户名对应的密码 + .setDWSVersion("v1").build() //Linkis后台协议的版本,当前版本为v1 + clientConfig + } + + + // 3. 开始执行代码 + def executeJob(client: UJESClient, user : String, code : String) : JobExecuteResult = { + println("user : " + user + ", code : [" + code + "]") + val startupMap = new java.util.HashMap[String, Any]() +// startupMap.put("wds.linkis.rm.yarnqueue", "default") + startupMap.put("wds.linkis.yarnqueue", "dws") + try { + val jobExecuteResult = client.execute(JobExecuteAction.builder() + .setCreator("LinkisClient-Test") //creator,请求Linkis的客户端的系统名,用于做系统级隔离 + .addExecuteCode(code) //ExecutionCode 请求执行的代码 + .setEngineType(EngineType.SPARK) // 希望请求的Linkis的执行引擎类型,如Spark hive等 +// .setUser("hduser2203").build()) //User,请求用户;用于做用户级多租户隔离 + .setStartupParams(startupMap) + .setUser(user).build()) //User,请求用户;用于做用户级多租户隔离 + println("execId: " + jobExecuteResult.getExecID + ", taskId: " + jobExecuteResult.taskID) + return jobExecuteResult + } catch { + case e : Exception => { + e.printStackTrace() + } + } + null.asInstanceOf[JobExecuteResult] + } + + + private def getResult(client: UJESClient, jobExecuteResult: JobExecuteResult, startTime: Long): Unit = { + + var executeTime = 0l + try { + // 4. 获取脚本的执行状态 + var jobInfoResult = client.getJobInfo(jobExecuteResult) + val sleepTimeMills : Int = 1000 + var sleepTime = 0.0 + while (!jobInfoResult.isCompleted) { + // 5. 获取脚本的执行进度 ***这里是新接口*** + val progress = client.progress(jobExecuteResult) + val progressInfo = if (progress.getProgressInfo != null) progress.getProgressInfo.toList else List.empty + Utils.sleepQuietly(sleepTimeMills) + sleepTime = sleepTime + sleepTimeMills / 1000.0 + println("progress: " + progress.getProgress + ", progressInfo: " + progressInfo + ", time : " + sleepTime + "s") + jobInfoResult = client.getJobInfo(jobExecuteResult) + } + if (!jobInfoResult.isSucceed) { + println("Failed to execute job: " + new Gson().toJson(jobInfoResult)) + IOUtils.closeQuietly(client) + return +// throw new Exception(jobInfoResult.getMessage) + } + + executeTime = System.currentTimeMillis() + // 6. 获取脚本的Job信息 + val jobInfo = client.getJobInfo(jobExecuteResult) + // 7. 获取结果集列表(如果用户一次提交多个SQL,会产生多个结果集) + val resultSetList = jobInfoResult.getResultSetList(client) + println("All result set list:") + resultSetList.foreach(println) + val oneResultSet = jobInfo.getResultSetList(client).head + // 8. 通过一个结果集信息,获取具体的结果集 +// val pageSize = 5000 + val pageSize = 300 + var page = 1 + var onePageResultSet = client.resultSet(ResultSetAction.builder() + .setPath(oneResultSet).setUser(jobExecuteResult.getUser) + .setPage(page).setPageSize(pageSize) + .build()) + + //// fetch context + println(onePageResultSet.getFileContent) + println("totalLine : " + onePageResultSet.totalLine) + var lineCount = 0 + while (onePageResultSet.totalLine > 0 && onePageResultSet.totalLine <= pageSize) { + page = page + 1 + lineCount = lineCount + onePageResultSet.totalLine + onePageResultSet = client.resultSet(ResultSetAction.builder() + .setPath(oneResultSet).setUser(jobExecuteResult.getUser) + .setPage(page).setPageSize(pageSize) + .build()) + println("line num : " + onePageResultSet.totalLine) + println("total page : " + onePageResultSet.totalPage) + /// fetch num + println(onePageResultSet.getFileContent) + } + println(new Gson().toJson(onePageResultSet)) +// val fileContents = resultSet.getFileContent +// println("First fileContents: ") +// println(fileContents) + println("total lines : " + lineCount) + } catch { + case e: Exception => { + e.printStackTrace() + IOUtils.closeQuietly(client) + } + } + IOUtils.closeQuietly(client) + val getresultTime = System.currentTimeMillis() + println("executeTime : " + (executeTime - startTime) / 1000.0 + "s") + println("getresultTime : " + (getresultTime - executeTime) / 1000.0 + "s") + } + + +} + diff --git a/linkis-computation-governance/linkis-computation-governance-common/pom.xml b/linkis-computation-governance/linkis-computation-governance-common/pom.xml new file mode 100644 index 0000000000..2db276f6c7 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/pom.xml @@ -0,0 +1,79 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-computation-governance-common + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-label-common + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/ExecutionNodeStatus.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/ExecutionNodeStatus.java new file mode 100644 index 0000000000..a39db797ff --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/ExecutionNodeStatus.java @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.entity; + +public enum ExecutionNodeStatus { + + Inited, WaitForRetry, Scheduled, Running, Succeed, Failed, Cancelled, Timeout; + + public static boolean isRunning(ExecutionNodeStatus eventStatus) { + return eventStatus == Running; + } + + public static boolean isScheduled(ExecutionNodeStatus eventStatus) { + return eventStatus != Inited; + } + + public static boolean isCompleted(ExecutionNodeStatus eventStatus) { + switch (eventStatus) { + case Inited: + case Scheduled: + case Running: + case WaitForRetry: + return false; + default: + return true; + } + } + + public static boolean isSucceed(ExecutionNodeStatus eventStatus) { + return Succeed == eventStatus; + } + + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/NodeExistStatus.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/NodeExistStatus.java new file mode 100644 index 0000000000..166b21c7c0 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/NodeExistStatus.java @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.entity; + +public enum NodeExistStatus { + + Exist, + UnExist, + Unknown // only used in internal + +} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestInsertTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestInsertTask.java similarity index 83% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestInsertTask.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestInsertTask.java index 200136b33b..a5f3294b14 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestInsertTask.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestInsertTask.java @@ -14,12 +14,10 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; -/** - * Created by enjoyyin on 2018/9/30. - */ public class RequestInsertTask extends RequestPersistTask implements QueryProtocol { } diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestOneTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestOneTask.java new file mode 100644 index 0000000000..29afb23731 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestOneTask.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.entity.task; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + +import java.util.Date; + +public class RequestOneTask extends RequestPersistTask implements QueryProtocol { + private Date startTime; + private Date endTime; + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } +} diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestPersistTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestPersistTask.java similarity index 89% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestPersistTask.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestPersistTask.java index a3f2ff4855..ada90d4898 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestPersistTask.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestPersistTask.java @@ -14,19 +14,19 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; import com.webank.wedatasphere.linkis.protocol.task.Task; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.Date; +import java.util.List; import java.util.Map; -/** - * Created by enjoyyin on 2018/9/30. - */ public class RequestPersistTask implements Task { + private Long taskID; /** * instance 是指该task所在的统一入口的实例 ip + port @@ -34,6 +34,9 @@ public class RequestPersistTask implements Task { private String instance; private String execId; private String umUser; + private String submitUser; + + /** * engineInstance 是指task执行所请求的engine的实例信息,ip+port */ @@ -59,17 +62,25 @@ public class RequestPersistTask implements Task { /** * source 存放脚本来源,scriptPath是其中一个参数用户采用传入执行脚本的方式,scriptPath就是脚本的存储地址 */ - private Map source; + private java.util.Map source; /** * runType需要和executeApplicationName结合使用,如用户选择了Spark做为服务,他还需要指明使用哪种执行方式,比如pySpark RSpark等 - * runType和engineType是同一个属性,为了兼容以前的代码 + * runType和runType是同一个属性,为了兼容以前的代码 */ private String runType; private String engineType; - private Map params; + private java.util.Map params; private Date engineStartTime; + private List> labels; + + + private String createService; + + private String description; + + public String getEngineType() { return engineType; } @@ -256,6 +267,38 @@ public void setTaskResource(String taskResource) { this.taskResource = taskResource; } + public String getSubmitUser() { + return submitUser; + } + + public void setSubmitUser(String submitUser) { + this.submitUser = submitUser; + } + + public List> getLabels() { + return labels; + } + + public void setLabels(List> labels) { + this.labels = labels; + } + + public String getCreateService() { + return createService; + } + + public void setCreateService(String createService) { + this.createService = createService; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + @Override public String toString() { return "RequestPersistTask{" + diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestQueryTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestQueryTask.java similarity index 85% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestQueryTask.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestQueryTask.java index d5323a4d12..08d0059a59 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestQueryTask.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestQueryTask.java @@ -14,11 +14,12 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + /** - * Created by enjoyyin on 2018/9/30. * Need to inherit the relationship, to fill in the rest of the query module restful code * 需要继承关系,方便query模块restful代码的填写 */ diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestReadAllTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestReadAllTask.java similarity index 86% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestReadAllTask.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestReadAllTask.java index 886b75ca65..ad82d48b87 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestReadAllTask.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestReadAllTask.java @@ -14,12 +14,10 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; + +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; -/** - * created by enjoyyin on 2018/10/9 - * Description: - */ public class RequestReadAllTask implements QueryProtocol { /** * Instance of microservices, through this example, we can take all the tasks below this instance from the database @@ -27,7 +25,7 @@ public class RequestReadAllTask implements QueryProtocol { */ private String instance; - public RequestReadAllTask(String instance){ + public RequestReadAllTask(String instance) { super(); this.instance = instance; } diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestUpdateTask.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestUpdateTask.java similarity index 82% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestUpdateTask.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestUpdateTask.java index 216001a7e4..1fcb54b03b 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/RequestUpdateTask.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/RequestUpdateTask.java @@ -14,11 +14,10 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; -/** - * Created by enjoyyin on 2018/9/30. - */ +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; + public class RequestUpdateTask extends RequestPersistTask implements QueryProtocol { } diff --git a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/ResponsePersist.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/ResponsePersist.java similarity index 94% rename from core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/ResponsePersist.java rename to linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/ResponsePersist.java index 39dde90f0c..ab3e1c7991 100644 --- a/core/cloudProtocol/src/main/java/com/webank/wedatasphere/linkis/protocol/query/ResponsePersist.java +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/java/com/webank/wedatasphere/linkis/governance/common/entity/task/ResponsePersist.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.query; +package com.webank.wedatasphere.linkis.governance.common.entity.task; +import com.webank.wedatasphere.linkis.protocol.query.QueryProtocol; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.Map; /** - * Created by enjoyyin on 2018/9/30. * Description: ResponsePersist is the content type returned by the query module to the entity * Description: ResponsePersist 是query模块向entrance返回的内容类型 */ diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/conf/GovernaceCommonConf.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/conf/GovernaceCommonConf.scala new file mode 100644 index 0000000000..0dd39014d3 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/conf/GovernaceCommonConf.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.conf + +import com.webank.wedatasphere.linkis.common.conf.CommonVars + +object GovernanceCommonConf { + + val CONF_FILTER_RM = "wds.linkis.rm" + + val SPARK_ENGINE_VERSION = CommonVars("wds.linkis.spark.engine.version", "2.4.3") + + val HIVE_ENGINE_VERSION = CommonVars("wds.linkis.hive.engine.version", "1.2.1") + + val PYTHON_ENGINE_VERSION = CommonVars("wds.linkis.python.engine.version", "python2") + + val ENGINE_CONN_SPRING_NAME = CommonVars("wds.linkis.engineconn.name", "EngineConn") + + val ENGINE_CONN_MANAGER_SPRING_NAME = CommonVars("wds.linkis.engineconn.manager.name", "linkis-cg-engineconnmanager") + + val MANAGER_SPRING_NAME = CommonVars("wds.linkis.engineconn.manager.name", "linkis-cg-linkismanager") + + val ENTRANCE_SPRING_NAME = CommonVars("wds.linkis.entrance.name", "linkis-cg-entrance") + + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/DWCJobRetryException.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/DWCJobRetryException.scala new file mode 100644 index 0000000000..6f12d2f914 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/DWCJobRetryException.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.exception + +import com.webank.wedatasphere.linkis.common.exception.DWCRetryException + +class DWCJobRetryException(desc: String) extends DWCRetryException(DWCJobRetryException.JOB_RETRY_ERROR_CODE, desc) + +object DWCJobRetryException { + val JOB_RETRY_ERROR_CODE = 25000 +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorCode.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorCode.java new file mode 100644 index 0000000000..41317efe25 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorCode.java @@ -0,0 +1,39 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.exception.engineconn; + +/** + * ErrorCode of Engine start with 40000 + * + */ +public class EngineConnExecutorErrorCode { + + public static final int INVALID_ENGINE_TYPE = 40100; + + public static final int INVALID_METHOD = 40101; + + public static final int INVALID_PARAMS = 40102; + + public static final int INVALID_LOCK = 40103; + + public static final int INVALID_TASK = 40104; + + public static final int SEND_TO_ENTRANCE_ERROR = 40105; + + public static final int INIT_EXECUTOR_FAILED = 40106; + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java new file mode 100644 index 0000000000..78a8a07cb8 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.exception.engineconn; + +import com.webank.wedatasphere.linkis.common.exception.ErrorException; + +public class EngineConnExecutorErrorException extends ErrorException { + + public EngineConnExecutorErrorException(int errCode, String desc) { + super(errCode, desc); + } + + public EngineConnExecutorErrorException(int errCode, String desc, String ip, int port, String serviceKind) { + super(errCode, desc, ip, port, serviceKind); + } + + public EngineConnExecutorErrorException(int errCode, String desc, Throwable e) { + this(errCode, desc); + initCause(e); + } + + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala new file mode 100644 index 0000000000..f525297c02 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.conf + +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.protocol.{CacheableProtocol, RetryableProtocol} + +trait ConfigProtocol + +case class RequestQueryGlobalConfig(username: String) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestQueryEngineConfig(userCreatorLabel: UserCreatorLabel, engineTypeLabel: EngineTypeLabel, filter: String = null) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestQueryEngineTypeDefault(engineTypeLabel: EngineTypeLabel) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestConfigByLabel(labels: java.util.List[Label[_]], isMerge: Boolean = true) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + + diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala similarity index 89% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala rename to linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala index 2b9129eb0d..50c6c3c8c5 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala @@ -14,13 +14,10 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.config +package com.webank.wedatasphere.linkis.governance.common.protocol.conf import java.util -/** - * Created by enjoyyin on 2018/10/17. - */ class ResponseQueryConfig extends ConfigProtocol { private var keyAndValue: util.Map[String, String] = _ def getKeyAndValue :util.Map[String, String] = keyAndValue diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala new file mode 100644 index 0000000000..8cdbfbc5bd --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.engineconn + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.NodeExistStatus +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + +import java.util + +case class RequestEngineStatusBatch(engineList: util.List[ServiceInstance]) extends RequestProtocol + +case class ResponseEngineStatusBatch(engineStatus: util.Map[ServiceInstance, NodeExistStatus], msg: String) + diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala new file mode 100644 index 0000000000..6666d56474 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala @@ -0,0 +1,86 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import java.util + +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + +trait RequestTask { + def getCode: String + def setCode(code: String): Unit + def getLock: String + def setLock(lock: String): Unit + def getProperties: util.Map[String, Object] + def setProperties(properties: util.Map[String, Object]) + def data(key: String, value: Object): Unit + def getLabels: util.List[Label[_]] + def setLabels(labels: util.List[Label[_]]) +} +object RequestTask { + private val header = "#rt_" + val RESULT_SET_STORE_PATH = header + "rs_store_path" +} +class RequestTaskExecute extends RequestTask with RequestProtocol { + private var code: String = _ + private var lock: String = _ + private var properties: util.Map[String, Object] = new util.HashMap[String, Object] + + private var labels: util.List[Label[_]] = new util.ArrayList[Label[_]](4) + + override def getCode: String = code + + override def setCode(code: String): Unit = this.code = code + + override def getLock: String = lock + + override def setLock(lock: String): Unit = this.lock = lock + + override def getProperties: util.Map[String, Object] = properties + + override def setProperties(properties: util.Map[String, Object]): Unit = this.properties = properties + + override def data(key: String, value: Object): Unit = { + if(properties == null) properties = new util.HashMap[String, Object] + properties.put(key, value) + } + + + + override def getLabels: util.List[Label[_]] = labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels +} + +trait TaskState extends RequestProtocol {} + +case class RequestTaskPause(execId: String) extends TaskState +case class RequestTaskResume(execId: String) extends TaskState +case class RequestTaskKill(execId: String) extends TaskState + + +/** + * The status of requesting job execution, mainly used for: + * 1. If the engine has not sent information to the entity for a long time, the enumeration periodically requests status information + * 2. If the entance of the request engine is hanged, the newly taken entity first requests the status of the job from the engine, the engine maintains the new sender information, + * and then sends log information to the sender. + * 请求Job执行的状态,主要用于: + * 1. 如果engine很久没有给entrance发送信息,entrance定时请求一次状态信息 + * 2. 如果请求engine的entrance挂掉了,新接手的entrance第一次向engine请求Job的状态,engine维系新的sender信息,后续向该sender发送日志信息 + */ +case class RequestTaskStatus(execId: String) extends TaskState \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala new file mode 100644 index 0000000000..1fa8400949 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.protocol.RetryableProtocol +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + + +/** + * + * @param pid + */ +case class ResponseEngineConnPid(serviceInstance: ServiceInstance, pid: String, ticketId: String) extends RetryableProtocol with RequestProtocol + + + diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala new file mode 100644 index 0000000000..248fb82d93 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import java.util + +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.protocol.{BroadcastProtocol, RetryableProtocol} + +case class ResponseTaskExecute(execId: String) + +case class ResponseTaskProgress(execId: String, progress: Float, progressInfo: Array[JobProgressInfo]) extends RetryableProtocol with RequestProtocol + +case class ResponseEngineLock(lock: String) + +case class EngineConcurrentInfo(runningTasks: Int, pendingTasks: Int, succeedTasks: Int, failedTasks: Int) +case class EngineOverloadInfo(maxMemory: Long, usedMemory: Long, systemCPUUsed: Float) + +case class ResponseEngineStatusChanged(instance: String, fromStatus: ExecutionNodeStatus, toStatus: ExecutionNodeStatus, + overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo) + extends BroadcastProtocol + +case class ResponseEngineInfo(createEntranceInstance: String, creator: String, user: String, properties: util.Map[String, String]) + +case class ResponseEngineStatus(instance: String, status: ExecutionNodeStatus, overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo, + engineInfo: ResponseEngineInfo) + +case class ResponseTaskLog(execId: String, log: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskError(execId: String, errorMsg: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskStatus(execId: String, status: ExecutionNodeStatus) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskResultSet(execId: String, output: String, alias: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskResultSize(execId: String, resultSize: Int) extends RetryableProtocol with RequestProtocol \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala new file mode 100644 index 0000000000..e54827aa1b --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala @@ -0,0 +1,144 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.utils + +import org.apache.commons.lang.StringUtils + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + +trait EngineConnArguments { + + def getSpringConfMap: Map[String, String] + + def getEngineConnConfMap: Map[String, String] + +} + +trait EngineConnArgumentsBuilder { + + def addSpringConf(confMap: Map[String, String]): EngineConnArgumentsBuilder + + def addSpringConf(key: String, value: String): EngineConnArgumentsBuilder + + def addEngineConnConf(confMap: Map[String, String]): EngineConnArgumentsBuilder + + def addEngineConnConf(key: String, value: String): EngineConnArgumentsBuilder + + def build(): EngineConnArguments + +} + +object EngineConnArgumentsBuilder { + def newBuilder(): EngineConnArgumentsBuilder = new DefaultEngineConnArgumentsBuilder +} + +class DefaultEngineConnArgumentsBuilder extends EngineConnArgumentsBuilder { + + private val engineConnOptionMap = new mutable.HashMap[String, String]() + private val springOptionMap = new mutable.HashMap[String, String]() + + override def addSpringConf(confMap: Map[String, String]): EngineConnArgumentsBuilder = { + springOptionMap ++= confMap + this + } + + override def addSpringConf(key: String, value: String): EngineConnArgumentsBuilder = { + springOptionMap += key -> value + this + } + + override def addEngineConnConf(confMap: Map[String, String]): EngineConnArgumentsBuilder = { + engineConnOptionMap ++= confMap + this + } + + override def addEngineConnConf(key: String, value: String): EngineConnArgumentsBuilder = { + engineConnOptionMap += key -> value + this + } + + override def build(): EngineConnArguments = new EngineConnArguments { + override def getSpringConfMap: Map[String, String] = springOptionMap.toMap + override def getEngineConnConfMap: Map[String, String] = engineConnOptionMap.toMap + } +} + +trait EngineConnArgumentsParser { + + def parseToObj(args: Array[String]): EngineConnArguments + + def parseToArgs(engineConnArguments: EngineConnArguments): Array[String] + +} +object EngineConnArgumentsParser { + + val LABEL_PREFIX = "label." + + private val parser = new DefaultEngineConnArgumentsParser + + def getEngineConnArgumentsParser: EngineConnArgumentsParser = parser +} + +class DefaultEngineConnArgumentsParser extends EngineConnArgumentsParser { + + protected val ENGINE_CONN_CONF = "--engineconn-conf" + protected val SPRING_CONF = "--spring-conf" + + protected val keyValueRegex = "([^=]+)=(.+)".r + + override def parseToObj(args: Array[String]): EngineConnArguments = { + var i = 0 + val argumentsBuilder = new DefaultEngineConnArgumentsBuilder + while(i < args.length) { + args(i) match { + case ENGINE_CONN_CONF => + addKeyValue(args(i + 1), (key, value) => { + argumentsBuilder.addEngineConnConf(key, value) + i += 1 + }) + case SPRING_CONF => + addKeyValue(args(i + 1), (key, value) => { + argumentsBuilder.addSpringConf(key, value) + i += 1 + }) + case _ => throw new IllegalArgumentException(s"illegal command line, ${args(i)} cannot recognize.") + } + i += 1 + } + argumentsBuilder.build() + } + + private def addKeyValue(keyValue: String, argumentsBuilder: (String, String) => Unit): Unit = keyValue match { + case keyValueRegex(key, value) => + argumentsBuilder(key, value) + case _ => throw new IllegalArgumentException("illegal command line, format: --conf key=value.") + } + + override def parseToArgs(engineConnArguments: EngineConnArguments): Array[String] = { + val options = ArrayBuffer[String]() + def write(confMap: Map[String, String], optionType: String): Unit = confMap.foreach { case (key, value) => + if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) { + options += optionType + options += (key + "=" + value) + } + } + write(engineConnArguments.getEngineConnConfMap, ENGINE_CONN_CONF) + write(engineConnArguments.getSpringConfMap, SPRING_CONF) + options.toArray + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala new file mode 100644 index 0000000000..a64e6db06d --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.utils + +object GovernanceConstant { + + val TASK_SOURCE_MAP_KEY = "source" + + val TASK_RESOURCES_STR = "resources" + + val TASK_RESOURCE_ID_STR = "resourceId" + + val TASK_RESOURCE_VERSION_STR = "version" + + val TASK_RESOURCE_FILE_NAME_STR = "fileName" + + val REQUEST_ENGINE_STATUS_BATCH_LIMIT = 500 +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml new file mode 100644 index 0000000000..4a1411e937 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml @@ -0,0 +1,70 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-linux-launch + + + + com.webank.wedatasphere.linkis + linkis-engineconn-manager-core + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala new file mode 100644 index 0000000000..1782faa255 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.linux.launch + +import com.webank.wedatasphere.linkis.ecm.core.launch.ProcessEngineConnLaunch + + + +class LinuxProcessEngineConnLaunch extends ProcessEngineConnLaunch { + + override protected def execFile: Array[String] = Array("sh", getPreparedExecFile) + + override protected def sudoCommand(user: String, command: String): Array[String] = + Array("sudo", "su", "-", user, "-c", command) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml new file mode 100644 index 0000000000..6a2fdead19 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml @@ -0,0 +1,85 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-engineconn-manager-core + + + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-plugin-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala new file mode 100644 index 0000000000..df8b71f7d8 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + +import java.io.Closeable +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.ecm.core.launch.{EngineConnLaunchRunner, EngineConnManagerEnv} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnCreationDesc +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineConn extends Closeable { + + def getTickedId: String + + def setTickedId(tickedId: String) + + def getServiceInstance: ServiceInstance + + def setServiceInstance(serviceInstance: ServiceInstance): Unit + + def getResource: NodeResource + + def setResource(resource: NodeResource): Unit + + def getLabels: util.List[Label[_]] + + def setLabels(labels: util.List[Label[_]]): Unit + + def getStatus: NodeStatus + + def setStatus(status: NodeStatus): Unit + + def getCreationDesc: EngineConnCreationDesc + + def setCreationDesc(desc: EngineConnCreationDesc): Unit + + def getEngineConnInfo: EngineConnInfo + + def setEngineConnInfo(engineConnInfo: EngineConnInfo): Unit + + def getEngineConnManagerEnv: EngineConnManagerEnv + + def setEngineConnManagerEnv(env: EngineConnManagerEnv): Unit + + def getEngineConnLaunchRunner: EngineConnLaunchRunner + + def setEngineConnLaunchRunner(runner: EngineConnLaunchRunner): Unit + + def setPid(pid: String): Unit + + def getPid: String + + override def close(): Unit = {} +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala new file mode 100644 index 0000000000..e2fcd4a81c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + + +class EngineConnInfo { + + private var errorCode: Int = 0 + private var errorMsg: String = _ + + def setErrorCode(errorCode: Int): Unit = this.errorCode = errorCode + + def getErrorCode: Int = errorCode + + def setErrorMsg(errorMsg: String): Unit = this.errorMsg = errorMsg + + def getErrorMsg: String = errorMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala new file mode 100644 index 0000000000..2a31060f39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + + +trait YarnEngineConn extends EngineConn { + + def getApplicationId: String + + def setApplicationId(applicationId: String): Unit + + def getApplicationURL: String + + def setApplicationURL(applicationURL: String): Unit + + def getYarnMode: String + + def setYarnMode(yarnMode: String): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala new file mode 100644 index 0000000000..dafe19cc94 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.util + +import scala.collection.JavaConversions._ + + +trait DiscoveryMsgGenerator { + + def generate(engineConnManagerEnv: EngineConnManagerEnv): java.util.Map[String, String] + +} + +class EurekaDiscoveryMsgGenerator extends DiscoveryMsgGenerator { + override def generate(engineConnManagerEnv: EngineConnManagerEnv): util.Map[String, String] = + engineConnManagerEnv.properties.get("eureka.client.serviceUrl.defaultZone") + .map(v => Map("eureka.client.serviceUrl.defaultZone" -> v)).getOrElse[Map[String,String]](Map.empty) +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala new file mode 100644 index 0000000000..e2973b61df --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest + + + +trait EngineConnLaunch { + + def setEngineConnLaunchRequest(request: EngineConnLaunchRequest): Unit + + def setEngineConnManagerEnv(engineConnManagerEnv: EngineConnManagerEnv): Unit + + def launch(): Unit + + def kill(): Unit + + def isAlive: Boolean + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala new file mode 100644 index 0000000000..bf81c3ac39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + + +trait EngineConnLaunchRunner extends Runnable { + + /** + * + * @param launch + */ + def setEngineConnLaunch(launch: EngineConnLaunch): Unit + + def getEngineConnLaunch: EngineConnLaunch + + def stop(): Unit + +} +class EngineConnLaunchRunnerImpl extends EngineConnLaunchRunner { + + private var launch: EngineConnLaunch = _ + /** + * + * @param launch + */ + override def setEngineConnLaunch(launch: EngineConnLaunch): Unit = this.launch = launch + + override def getEngineConnLaunch: EngineConnLaunch = launch + + override def stop(): Unit = launch.kill() + + override def run(): Unit = { + launch.launch() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala new file mode 100644 index 0000000000..71ef80222a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + + +trait EngineConnManagerEnv { + + val engineConnManagerHomeDir: String + val engineConnWorkDir: String + val engineConnLogDirs: String + val engineConnTempDirs: String + val engineConnManagerHost: String + val engineConnManagerPort: String + val linkDirs: Map[String, String] + val properties: Map[String, String] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala new file mode 100644 index 0000000000..1f851a6e92 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala @@ -0,0 +1,91 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.OutputStream + +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.LaunchConstants +import org.apache.commons.io.IOUtils + + +trait ProcessEngineCommandBuilder { + + def setCommand(command: Array[String]): Unit + + def setEnv(key: String, value: String): Unit + + def newLine(command: Array[String]) + + def link(fromPath: String, toPath: String) + + def mkdir(dir: String): Unit + + def writeTo(output: OutputStream): Unit + + def replaceExpansionMarker(value: String): String + +} + +abstract class ShellProcessEngineCommandBuilder extends ProcessEngineCommandBuilder { + + private val LINE_SEPARATOR = System.getProperty("line.separator") + private val sb = new StringBuilder + + def newLine(command: String): Unit = newLine(Array(command)) + + override def newLine(command: Array[String]): Unit = { + command.foreach(sb ++= _) + sb ++= LINE_SEPARATOR + } + + def writeTo(output: OutputStream): Unit = { + IOUtils.write(sb, output) + } + + override def replaceExpansionMarker(value: String): String = value.replaceAll(LaunchConstants.EXPANSION_MARKER_LEFT, "\\${") + .replaceAll(LaunchConstants.EXPANSION_MARKER_RIGHT, "}") +} + +class UnixProcessEngineCommandBuilder extends ShellProcessEngineCommandBuilder { + + newLine("#!/bin/bash") + + private def addErrorCheck(): Unit = { + newLine("linkis_engineconn_errorcode=$?") + newLine("if [ $linkis_engineconn_errorcode -ne 0 ]") + newLine("then") + newLine(" exit $linkis_engineconn_errorcode") + newLine("fi") + } + + override def setCommand(command: Array[String]): Unit = { + newLine(Array(s"exec /bin/bash -c ${"\""}${command.mkString(" ")}${"\""}")) + addErrorCheck() + } + + override def setEnv(key: String, value: String): Unit = newLine(Array("export ", key, "=\"", value, "\"")) + + override def link(fromPath: String, toPath: String): Unit = { + newLine(Array("ln -sf \"", fromPath, "\" \"", toPath, "\"")) + addErrorCheck() + } + + override def mkdir(dir: String): Unit = { + newLine(Array("mkdir -p ", dir)) + addErrorCheck() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala new file mode 100644 index 0000000000..fbc1724603 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.File +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging + + +trait ProcessEngineCommandExec { + + def execute(): Unit + + def getProcess: Process + +} + +class ShellProcessEngineCommandExec(command: Array[String], baseDir: String, + environment: util.Map[String, String], timeout: Long) extends + ProcessEngineCommandExec with Logging { + + private var process: Process = _ + + def this(command: Array[String], baseDir: String) = this(command, baseDir, null, 0) + + def this(command: Array[String]) = this(command, null) + + override def execute(): Unit = { + + info(s"Invoke subProcess, base dir ${this.baseDir} cmd is: ${command.mkString}") + val builder = new ProcessBuilder(command: _*) + if (environment != null) builder.environment.putAll(this.environment) + if (baseDir != null) builder.directory(new File(this.baseDir)) + builder.redirectErrorStream(true) + process = builder.start + } + + override def getProcess: Process = process +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala new file mode 100644 index 0000000000..9146b56618 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala @@ -0,0 +1,171 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.{File, InputStream, OutputStream} +import java.net.ServerSocket + +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.exception.ErrorException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.utils.{EngineConnArgumentsBuilder, EngineConnArgumentsParser} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.conf.EnvConfiguration +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.Environment._ +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.LaunchConstants._ +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.{Environment, ProcessEngineConnLaunchRequest} +import org.apache.commons.io.{FileUtils, IOUtils} +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +trait ProcessEngineConnLaunch extends EngineConnLaunch with Logging { + + private var request: ProcessEngineConnLaunchRequest = _ + private var engineConnManagerEnv: EngineConnManagerEnv = _ + private var discoveryMsgGenerator: DiscoveryMsgGenerator = _ + private var processBuilder: ProcessEngineCommandBuilder = _ + private var preparedExecFile: String = _ + private var process: Process = _ + + private var engineConnPort: String = _ + + protected def newProcessEngineConnCommandBuilder(): ProcessEngineCommandBuilder = new UnixProcessEngineCommandBuilder + + protected def newProcessEngineConnCommandExec(command: Array[String], workDir: String): ProcessEngineCommandExec = + new ShellProcessEngineCommandExec(command, workDir) + + override def setEngineConnLaunchRequest(request: EngineConnLaunchRequest): Unit = request match { + case processEngineConnLaunchRequest: ProcessEngineConnLaunchRequest => + this.request = processEngineConnLaunchRequest + case _ => //TODO exception + } + + override def setEngineConnManagerEnv(engineConnManagerEnv: EngineConnManagerEnv): Unit = this.engineConnManagerEnv = engineConnManagerEnv + + def setDiscoveryMsgGenerator(discoveryMsgGenerator: DiscoveryMsgGenerator): Unit = this.discoveryMsgGenerator = discoveryMsgGenerator + + def getEngineConnLaunchRequest: EngineConnLaunchRequest = request + + private def initializeEnv(): Unit = { + val environment = request.environment + def putIfExists(enum: Environment): Unit = { + val key = enum.toString + val conf = CommonVars.apply(key, "") + if(StringUtils.isNotBlank(conf.getValue)) environment.put(key, conf.getValue) + } + Environment.values foreach { + case USER => environment.put(USER.toString, request.user) + case ECM_HOME => environment.put(ECM_HOME.toString, engineConnManagerEnv.engineConnManagerHomeDir) + case PWD => environment.put(PWD.toString, engineConnManagerEnv.engineConnWorkDir) + case LOG_DIRS => environment.put(LOG_DIRS.toString, engineConnManagerEnv.engineConnLogDirs) + case TEMP_DIRS => environment.put(TEMP_DIRS.toString, engineConnManagerEnv.engineConnTempDirs) + case ECM_HOST => environment.put(ECM_HOST.toString, engineConnManagerEnv.engineConnManagerHost) + case ECM_PORT => environment.put(ECM_PORT.toString, engineConnManagerEnv.engineConnManagerPort) + case HADOOP_HOME => putIfExists(HADOOP_HOME) + case HADOOP_CONF_DIR => putIfExists(HADOOP_CONF_DIR) + case HIVE_CONF_DIR => putIfExists(HIVE_CONF_DIR) + case RANDOM_PORT => environment.put(RANDOM_PORT.toString, findAvailPort().toString) + case _ => + } + } + + private def findAvailPort(): Int = { + val socket = new ServerSocket(0) + Utils.tryFinally(socket.getLocalPort)(IOUtils.closeQuietly(socket)) + } + + private def addAvailPort(value: String): String = { + var existsRandomPort = value.contains(CLASS_PATH_SEPARATOR) + var newValue = value + while(existsRandomPort) { + newValue = value.replaceFirst(CLASS_PATH_SEPARATOR, findAvailPort().toString) + existsRandomPort = value.contains(CLASS_PATH_SEPARATOR) + } + newValue + } + + override def launch(): Unit = { + request.necessaryEnvironments.foreach{e => + val env = CommonVars(e, "") + if(StringUtils.isEmpty(env.getValue)) + throw new ErrorException(30000, s"Necessary environment $e is not exists!(必须的环境变量 $e 不存在!)") //TODO exception + else request.environment.put(e, env.getValue) + } + prepareCommand() + val exec = newProcessEngineConnCommandExec(sudoCommand(request.user, execFile.mkString(" ")), engineConnManagerEnv.engineConnWorkDir) + exec.execute() + process = exec.getProcess + } + + protected def execFile: Array[String] + + def getEngineConnPort: String = engineConnPort + + protected def getCommandArgs: Array[String] = { + if (request.creationDesc.properties.exists { case (k, v) => k.contains(" ") || (v != null && v.contains(" ")) }) + throw new ErrorException(30000, "Startup parameters contain spaces!(启动参数中包含空格!)") //TODO exception + val arguments = EngineConnArgumentsBuilder.newBuilder() + engineConnPort = findAvailPort().toString + var springConf = Map("spring.application.name" -> GovernanceCommonConf.ENGINE_CONN_SPRING_NAME.getValue, + "server.port" -> engineConnPort, "spring.profiles.active" -> "engineconn", + "logging.config" -> s"classpath:${EnvConfiguration.LOG4J2_XML_FILE.getValue}") ++: discoveryMsgGenerator.generate(engineConnManagerEnv) + request.creationDesc.properties.filter(_._1.startsWith("spring.")).foreach { case (k, v) => + springConf = springConf += (k -> v) + } + arguments.addSpringConf(springConf.toMap) + var engineConnConf = Map("ticketId" -> request.ticketId, "user" -> request.user) + engineConnConf = engineConnConf ++: request.labels.map(l => EngineConnArgumentsParser.LABEL_PREFIX + l.getLabelKey -> l.getStringValue).toMap + engineConnConf = engineConnConf ++: request.creationDesc.properties.filterNot(_._1.startsWith("spring.")).toMap + arguments.addEngineConnConf(engineConnConf) + EngineConnArgumentsParser.getEngineConnArgumentsParser.parseToArgs(arguments.build()) + } + + override def kill(): Unit = process.destroy() + + override def isAlive: Boolean = process.isAlive + + protected def prepareCommand(): Unit = { + processBuilder = newProcessEngineConnCommandBuilder() + engineConnManagerEnv.linkDirs.foreach{case (k, v) => processBuilder.link(k, v)} + initializeEnv() + request.environment.foreach{ case (k, v) => + var value = v.replaceAll(CLASS_PATH_SEPARATOR, File.pathSeparator) + value = addAvailPort(value) + processBuilder.setEnv(k, processBuilder.replaceExpansionMarker(value)) + } + val execCommand = request.commands.map(processBuilder.replaceExpansionMarker(_)).map(addAvailPort) ++ getCommandArgs + //execCommand = sudoCommand(request.user, execCommand.mkString(" ")) + processBuilder.setCommand(execCommand) + preparedExecFile = new File(engineConnManagerEnv.engineConnWorkDir, "engineConnExec.sh").getPath + val output = getFileOutputStream + Utils.tryFinally(processBuilder.writeTo(output))(output.close()) + } + + protected def sudoCommand(user: String, command: String): Array[String] + + protected def getFileOutputStream: OutputStream = FileUtils.openOutputStream(new File(preparedExecFile)) + + protected def getPreparedExecFile: String = preparedExecFile + + def getProcessInputStream:InputStream = process.getInputStream + + def processWaitFor:Int =process.waitFor + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala new file mode 100644 index 0000000000..fc13ec07de --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerEventBus + + +class ECMAsyncListenerBus(capacity: Int, name: String) + (consumerThreadSize: Int, threadMaxFreeTime: Long) + extends ListenerEventBus[ECMEventListener, ECMEvent](capacity, name)(consumerThreadSize, threadMaxFreeTime) { + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: ECMEventListener, event: ECMEvent): Unit = listener.onEvent(event) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java new file mode 100644 index 0000000000..011137d69a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener; + +import com.webank.wedatasphere.linkis.common.listener.Event; + + +public interface ECMEvent extends Event { +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala new file mode 100644 index 0000000000..242972feb1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.{Event, EventListener} +import com.webank.wedatasphere.linkis.common.utils.Logging + + +trait ECMEventListener extends EventListener with Logging { + + def onEvent(event: ECMEvent) + + override def onEventError(event: Event, t: Throwable): Unit = { + error(s"async message invoke failed ${event.toString}", t) + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala new file mode 100644 index 0000000000..208fe6fd68 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerBus + +class ECMSyncListenerBus extends ListenerBus[ECMEventListener, ECMEvent] { + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: ECMEventListener, event: ECMEvent): Unit = listener.onEvent(event) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala new file mode 100644 index 0000000000..6245c57b5e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.metrics + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn + + + +trait ECMMetrics { + + def getStartingEngineConns: Array[_ <: EngineConn] + + def getRunningEngineConns: Array[EngineConn] + + def getSucceedEngineConns: Array[EngineConn] + + def getFailedEngineConns: Array[EngineConn] + + def increaseStartingEngineConn(engineConn: EngineConn): Unit + + def increaseRunningEngineConn(engineConn: EngineConn): Unit + + def increaseSuccessEngineConn(engineConn: EngineConn): Unit + + def increaseFailedEngineConn(engineConn: EngineConn): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala new file mode 100644 index 0000000000..44fef7ce3a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.report + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +trait ECMHealthReport extends NodeHealthReport { + + def setProtectedResource(protectedResource: Resource): Unit + + def getProtectResource: Resource + + def setOverload(nodeOverLoadInfo: NodeOverLoadInfo): Unit + + def getOverload: NodeOverLoadInfo + + def setRunningEngineConns(runningEngines: Array[EngineConn]) + + def getRunningEngineConns: Array[EngineConn] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala new file mode 100644 index 0000000000..ebd7c87a22 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.report + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +trait NodeHealthReport { + + def getReportTime: Long + + def setReportTime(reportTime: Long): Unit + + def getNodeStatus: NodeStatus + + def setNodeStatus(nodeStatus: NodeStatus): Unit + + def setNodeMsg(msg: String): Unit + + def getNodeMsg: String + + def getUsedResource: Resource + + def setUsedResource(resource: Resource): Unit + + def getTotalResource: Resource + + def setTotalResource(resource: Resource): Unit + + def setNodeId(nodeId: String): Unit + + def getNodeId: String + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml new file mode 100644 index 0000000000..06b7609354 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml @@ -0,0 +1,141 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-engineconn-manager-server + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-manager-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-linux-launch + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + provided + + + + + com.webank.wedatasphere.linkis + linkis-bml-client + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + org.json4s + json4s-jackson_${scala.binary.version} + ${json4s.version} + provided + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + false + + + make-assembly + package + + single + + + + src/main/assembly/distribution.xml + + + + + + false + out + false + false + + src/main/assembly/distribution.xml + + + + + + + ${basedir}/src/main/resources + + **/*.properties + **/*.xml + **/*.yml + + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml new file mode 100644 index 0000000000..ef1578ec9c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml @@ -0,0 +1,73 @@ + + + + linkis-engineconn-manager + + dir + + false + linkis-engineconn-manager + + + + + + lib + true + true + false + true + true + + + + + + + + ${basedir}/src/main/resources + + * + + 0777 + conf + unix + + + + + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java new file mode 100644 index 0000000000..9e38ce8793 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java @@ -0,0 +1,122 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import com.webank.wedatasphere.linkis.common.ServiceInstance; +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMAsyncListenerBus; +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMSyncListenerBus; +import com.webank.wedatasphere.linkis.ecm.server.context.ECMContext; +import com.webank.wedatasphere.linkis.ecm.server.listener.ECMClosedEvent; +import com.webank.wedatasphere.linkis.ecm.server.listener.ECMReadyEvent; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.EventListener; + +import static com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.ECM_ASYNC_BUS_WAITTOEMPTY_TIME; + + +public class ECMApplication extends DataWorkCloudApplication { + + private static ECMContext ecmContext; + + private volatile static boolean ready; + + private static ServiceInstance ecmServiceInstance; + + private static String[] parmas; + + public static void main(String[] args) throws ReflectiveOperationException { + parmas = args; + DataWorkCloudApplication.main(args); + } + + public static ECMContext getContext() { + return ecmContext; + } + + public static void setContext(ECMContext context) { + ecmContext = context; + } + + public static ServiceInstance getECMServiceInstance() { + return ecmServiceInstance; + } + + public static void setECMServiceInstance(ServiceInstance serviceInstance) { + ecmServiceInstance = serviceInstance; + } + + public static boolean isReady() { + return ready; + } + + public static void setReady(boolean applicationReady) { + ready = applicationReady; + } + + public static String[] getParmas() { + return parmas; + } +} + + +@Configuration +class ECMApplicationListener { + + private final Log logger = LogFactory.getLog(this.getClass()); + + @EventListener + public void onApplicationReady(ApplicationReadyEvent event) { + ServiceInstance serviceInstance = DataWorkCloudApplication.getServiceInstance(); + ECMApplication.setECMServiceInstance(serviceInstance); + ECMContext context = event.getApplicationContext().getBean(ECMContext.class); + ECMApplication.setContext(context); + ECMAsyncListenerBus emAsyncListenerBus = context.getECMAsyncListenerBus(); + ECMSyncListenerBus emSyncListenerBus = context.getECMSyncListenerBus(); + emAsyncListenerBus.start(); + ECMReadyEvent ecmReadyEvent = new ECMReadyEvent(ECMApplication.getParmas()); + emAsyncListenerBus.postToAll(ecmReadyEvent); + emSyncListenerBus.postToAll(ecmReadyEvent); + ECMApplication.setReady(true); + logger.info(String.format("ECM:%s is ready", serviceInstance)); + } + + @EventListener + public void onApplicationClosed(ContextClosedEvent contextClosedEvent) { + ServiceInstance serviceInstance = DataWorkCloudApplication.getServiceInstance(); + ECMApplication.setReady(false); + ECMClosedEvent ecmClosedEvent = new ECMClosedEvent(); + ECMApplication.getContext().getECMSyncListenerBus().postToAll(ecmClosedEvent); + ECMAsyncListenerBus ecmAsyncListenerBus = ECMApplication.getContext().getECMAsyncListenerBus(); + ecmAsyncListenerBus.postToAll(ecmClosedEvent); + logger.info(String.format("wait ECM:%s asyncBus empty", serviceInstance)); + try { + ecmAsyncListenerBus.waitUntilEmpty(ECM_ASYNC_BUS_WAITTOEMPTY_TIME()); + } catch (Throwable e) { + logger.error("wait ECM asyncBus empty failed", e); + } + logger.info("ECM asyncBus is empty"); + ecmAsyncListenerBus.stop(); + logger.info("ECM is closed"); + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml new file mode 100644 index 0000000000..b644f75f86 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml @@ -0,0 +1,29 @@ +server: + port: 9102 +spring: + application: + name: linkis-cg-engineconnmanager + + +eureka: + client: + serviceUrl: + defaultZone: http://127.0.0.1:20303/eureka/ + instance: + metadata-map: + test: wedatasphere + +management: + endpoints: + web: + exposure: + include: refresh,info + health: + db: + enabled: false +logging: + config: classpath:log4j2.xml + +ribbon: + ReadTimeout: 60000 + ConnectTimeout: 60000 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties new file mode 100644 index 0000000000..6c12e6aa27 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties @@ -0,0 +1,18 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +##restful +wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.em.restful + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..0f19fc3c17 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala new file mode 100644 index 0000000000..3ad3d73796 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala @@ -0,0 +1,75 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.conf + +import java.io.File +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} +import com.webank.wedatasphere.linkis.common.utils.ByteTimeUtils +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf + +import scala.concurrent.duration.Duration + + +object ECMConfiguration { + + //listenerbus + val ECM_ASYNC_BUS_CAPACITY: Int = CommonVars("wds.linkis.ecm.async.bus.capacity", 500).getValue + val ECM_ASYNC_BUS_NAME: String = CommonVars("wds.linkis.ecm.async.bus.name", "em_async_bus").getValue + val ECM_ASYNC_BUS_CONSUMER_SIZE: Int = CommonVars("wds.linkis.ecm.async.bus.consumer.size", 30).getValue + val ECM_ASYNC_BUS_THREAD_MAX_FREE_TIME: Long = CommonVars("wds.linkis.ecm.async.bus.max.free.time", ByteTimeUtils.timeStringAsMs("2m")).getValue + val ECM_ASYNC_BUS_WAITTOEMPTY_TIME: Long = CommonVars("wds.linkis.ecm.async.bus.waittoempty.time", 5000L).getValue + + //resource + val ECM_MAX_MEMORY_AVAILABLE: Long = CommonVars[Long]("wds.linkis.ecm.memory.max", ByteTimeUtils.byteStringAsBytes("80g")).getValue + val ECM_MAX_CORES_AVAILABLE: Int = CommonVars[Integer]("wds.linkis.ecm.cores.max", 50).getValue + val ECM_MAX_CREATE_INSTANCES: Int = CommonVars[Integer]("wds.linkis.ecm.engineconn.instances.max", 50).getValue + + val ECM_PROTECTED_MEMORY: Long = CommonVars[Long]("wds.linkis.ecm.protected.memory", ByteTimeUtils.byteStringAsBytes("4g")).getValue + val ECM_PROTECTED_CORES: Int = CommonVars[Integer]("wds.linkis.ecm.protected.cores.max", 2).getValue + val ECM_PROTECTED_INSTANCES: Int = CommonVars[Integer]("wds.linkis.ecm.protected.engine.instances", 2).getValue + + val MANAGER_SPRING_NAME: String = GovernanceCommonConf.MANAGER_SPRING_NAME.getValue + + val ENGINE_CONN_MANAGER_SPRING_NAME: String = GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue + + val ECM_HEALTH_REPORT_PERIOD: Long = CommonVars("wds.linkis.ecm.health.report.period", 5).getValue + + val ECM_HEALTH_REPORT_DELAY: Long = CommonVars("wds.linkis.ecm.health.report.delay", 10).getValue + + val ENGINECONN_SPRING_NAME: String = CommonVars("wds.linkis.engineconn.spring.name", "linkis-cg-engineplugin").getValue + + val ECM_HOME_DIR: String = CommonVars("wds.linkis.ecm.home.dir", this.getClass.getResource("/").getPath).getValue + + val ENGINECONN_ROOT_DIR: String = CommonVars("wds.linkis.engineconn.root.dir", s"${ECM_HOME_DIR}engineConnRootDir").getValue + + val ENGINECONN_PUBLIC_DIR: String = CommonVars("wds.linkis.engineconn.public.dir", s"$ENGINECONN_ROOT_DIR${File.separator}engineConnPublickDir").getValue + + val ECM_LAUNCH_MAX_THREAD_SIZE: Int = CommonVars("wds.linkis.ecm.launch.max.thread.size", 100).getValue + + val ECM_EUREKA_DEFAULTZONE: String = CommonVars("wds.linkis.eureka.defaultZone", "http://127.0.0.1:20303/eureka/").getValue + + /** + * engineconn创建时间,如果为0,则使用ms中默认的 + */ + val ENGINECONN_CREATE_DURATION: Duration = Duration(CommonVars("wds.linkis.ecm.engineconn.create.duration", 0).getValue, TimeUnit.MILLISECONDS) + + val WAIT_ENGINECONN_PID = CommonVars("wds.linkis.engineconn.wait.callback.pid", new TimeType("3s")) + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala new file mode 100644 index 0000000000..226c0a4048 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.context + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMAsyncListenerBus, ECMSyncListenerBus} +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.metrics.DefaultECMMetrics +import org.springframework.stereotype.Component + + +@Component +class DefaultECMContext extends ECMContext { + + private val emSyncListenerBus = new ECMSyncListenerBus + + private val emAsyncListenerBus = new ECMAsyncListenerBus(ECM_ASYNC_BUS_CAPACITY, ECM_ASYNC_BUS_NAME)(ECM_ASYNC_BUS_CONSUMER_SIZE, ECM_ASYNC_BUS_THREAD_MAX_FREE_TIME) + + private val metrics = new DefaultECMMetrics + + + override def getECMAsyncListenerBus: ECMAsyncListenerBus = emAsyncListenerBus + + override def getECMSyncListenerBus: ECMSyncListenerBus = emSyncListenerBus + + override def getECMMetrics: ECMMetrics = metrics +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala new file mode 100644 index 0000000000..42312ff750 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.context + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMAsyncListenerBus, ECMSyncListenerBus} +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics + + +trait ECMContext { + + def getECMAsyncListenerBus: ECMAsyncListenerBus + + def getECMSyncListenerBus: ECMSyncListenerBus + + def getECMMetrics:ECMMetrics + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala new file mode 100644 index 0000000000..ebdec3affb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.converter + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, YarnEngineConn} +import com.webank.wedatasphere.linkis.ecm.server.engineConn.DefaultYarnEngineConn +import org.springframework.beans.BeanUtils + + +object ECMEngineConverter { + + def engineConn2YarnEngineConn(engineConn: EngineConn)(implicit updateFunction: YarnEngineConn => Unit): YarnEngineConn = { + val conn = new DefaultYarnEngineConn + BeanUtils.copyProperties(engineConn, conn) + updateFunction(conn) + conn + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala new file mode 100644 index 0000000000..620eed4b8a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala @@ -0,0 +1,99 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.engineConn + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, EngineConnInfo} +import com.webank.wedatasphere.linkis.ecm.core.launch.{EngineConnLaunchRunner, EngineConnManagerEnv} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnCreationDesc +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +class DefaultEngineConn extends EngineConn { + + /** + * starting :初始状态 + * success:成功启动并且安全退出 + * Failed:启动失败 + * Running:容器运行中 + */ + @volatile private var status: NodeStatus = _ + + private var tickedId: String = _ + + private var resource: NodeResource = _ + + private var labels: util.List[Label[_]] = _ + + private var engineConnCreationDesc: EngineConnCreationDesc = _ + + private var engineConnInfo: EngineConnInfo = _ + + private var ecmEnv: EngineConnManagerEnv = _ + + private var engineConnLaunchRunner: EngineConnLaunchRunner = _ + + private var instance: ServiceInstance = _ + + private var pid: String = _ + + override def getResource: NodeResource = resource + + override def setResource(resource: NodeResource): Unit = this.resource = resource + + override def getLabels: util.List[Label[_]] = labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels + + override def getStatus: NodeStatus = status + + override def getCreationDesc: EngineConnCreationDesc = engineConnCreationDesc + + override def getEngineConnInfo: EngineConnInfo = engineConnInfo + + override def getEngineConnLaunchRunner: EngineConnLaunchRunner = engineConnLaunchRunner + + override def setEngineConnLaunchRunner(runner: EngineConnLaunchRunner): Unit = this.engineConnLaunchRunner = runner + + override def setEngineConnInfo(engineConnInfo: EngineConnInfo): Unit = this.engineConnInfo = engineConnInfo + + override def getTickedId: String = tickedId + + override def setTickedId(tickedId: String): Unit = this.tickedId = tickedId + + override def setStatus(status: NodeStatus): Unit = this.status = status + + override def setCreationDesc(engineConnCreationDesc: EngineConnCreationDesc): Unit = this.engineConnCreationDesc = engineConnCreationDesc + + override def getServiceInstance: ServiceInstance = instance + + override def setServiceInstance(instance: ServiceInstance): Unit = this.instance = instance + + override def getPid: String = pid + + override def setPid(pid: String): Unit = this.pid = pid + + override def getEngineConnManagerEnv: EngineConnManagerEnv = ecmEnv + + override def setEngineConnManagerEnv(env: EngineConnManagerEnv): Unit = this.ecmEnv = env + + override def toString = s"DefaultEngineConn($status, $tickedId, $resource, $labels, $engineConnCreationDesc, $engineConnInfo, $ecmEnv, $engineConnLaunchRunner, $instance, $pid)" +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala new file mode 100644 index 0000000000..001361d4e2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.engineConn + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.YarnEngineConn + + +class DefaultYarnEngineConn extends DefaultEngineConn with YarnEngineConn { + + var applicationId: String = _ + + var applicationURL: String = _ + + var yarnMode: String = _ + + override def getApplicationId: String = applicationId + + override def setApplicationId(applicationId: String): Unit = this.applicationId = applicationId + + override def getApplicationURL: String = applicationURL + + override def setApplicationURL(applicationURL: String): Unit = this.applicationURL = applicationURL + + override def getYarnMode: String = yarnMode + + override def setYarnMode(yarnMode: String): Unit = this.yarnMode = yarnMode + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala new file mode 100644 index 0000000000..03f6b9a4ec --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.exception + +import com.webank.wedatasphere.linkis.common.exception.{ErrorException, WarnException} + + +class ECMErrorException(errorCode: Int, desc: String) extends ErrorException(errorCode, desc) { + def this(errorCode: Int, desc: String, t: Throwable) { + this(errorCode, desc) + this.initCause(t) + } +} + +class ECMWarnException(errCode: Int, desc: String) extends WarnException(errCode, desc) + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala new file mode 100644 index 0000000000..ba6fa5c628 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.listener + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMEvent +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +case class ECMReadyEvent(params: Array[String]) extends ECMEvent + +case class ECMClosedEvent() extends ECMEvent + +case class EngineConnStatusChageEvent(from: NodeStatus, to: NodeStatus) extends ECMEvent + +case class YarnAppIdCallbackEvent(protocol: YarnAPPIdCallbackProtocol) extends ECMEvent + +case class YarnInfoCallbackEvent(protocol: YarnInfoCallbackProtocol) extends ECMEvent + +case class EngineConnPidCallbackEvent(protocol: ResponseEngineConnPid) extends ECMEvent + +case class EngineConnAddEvent(conn: EngineConn) extends ECMEvent + +case class EngineConnStatusChangeEvent(tickedId: String, updateStatus: NodeStatus) extends ECMEvent + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala new file mode 100644 index 0000000000..5b24a7d8b2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala @@ -0,0 +1,106 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.metrics + + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus._ + +import scala.collection.JavaConversions._ + + +class DefaultECMMetrics extends ECMMetrics { + + + private val startingEngineConnCount = new AtomicInteger(0) + + private val runningEngineConnCount = new AtomicInteger(0) + + private val successEngineConnCount = new AtomicInteger(0) + + private val failedEngineConnCount = new AtomicInteger(0) + + private val startingEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val runningEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val successEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val failedEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + override def getStartingEngineConns: Array[EngineConn] = getEngineConns(startingEngineConnMap) + + override def getRunningEngineConns: Array[EngineConn] = getEngineConns(runningEngineConnMap) + + override def getSucceedEngineConns: Array[EngineConn] = getEngineConns(successEngineConnMap) + + override def getFailedEngineConns: Array[EngineConn] = getEngineConns(failedEngineConnMap) + + private val getEngineConns = (map: ConcurrentHashMap[String, EngineConn]) => map.values().toSeq.toArray + + private val decreaseEngineConnMetric = (engineConn: EngineConn, map: ConcurrentHashMap[String, EngineConn], count: AtomicInteger) => { + val conn = map.remove(engineConn.getTickedId) + if (conn != null) { + count.decrementAndGet() + } + } + + private val increaseEngineConnMetric = (engineConn: EngineConn, map: ConcurrentHashMap[String, EngineConn], count: AtomicInteger, status: NodeStatus) => { + if (engineConn.getStatus.equals(status)) { + count.incrementAndGet() + map.put(engineConn.getTickedId, engineConn) + } + } + + override def increaseStartingEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, startingEngineConnMap, startingEngineConnCount, Starting) + } + + def decreseStartingEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, startingEngineConnMap, startingEngineConnCount) + } + + override def increaseRunningEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, runningEngineConnMap, runningEngineConnCount, Running) + } + + def decreseRunningEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, runningEngineConnMap, runningEngineConnCount) + } + + override def increaseSuccessEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, successEngineConnMap, successEngineConnCount, Success) + } + + def decreaseSuccessEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, successEngineConnMap, successEngineConnCount) + } + + override def increaseFailedEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, failedEngineConnMap, failedEngineConnCount, Failed) + } + + def decreaseFailedEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, failedEngineConnMap, failedEngineConnCount) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala new file mode 100644 index 0000000000..de3e6e75d4 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.report + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +class DefaultECMHealthReport extends ECMHealthReport { + + private var protectedResource: Resource = _ + + private var totalResource: Resource = _ + + private var usedResource: Resource = _ + + private var overload: NodeOverLoadInfo = _ + + private var runningEngineConns: Array[EngineConn] = _ + + private var reportTime: Long = _ + + private var nodeStatus: NodeStatus = _ + + private var nodeMsg: String = _ + + private var nodeId: String = _ + + override def setProtectedResource(protectedResource: Resource): Unit = this.protectedResource = protectedResource + + override def getProtectResource: Resource = protectedResource + + override def setOverload(overload: NodeOverLoadInfo): Unit = this.overload = overload + + override def getOverload: NodeOverLoadInfo = overload + + override def setRunningEngineConns(runningEngines: Array[EngineConn]): Unit = this.runningEngineConns = runningEngineConns + + override def getRunningEngineConns: Array[EngineConn] = runningEngineConns + + override def getReportTime: Long = reportTime + + override def setReportTime(reportTime: Long): Unit = this.reportTime = reportTime + + override def getNodeStatus: NodeStatus = nodeStatus + + override def setNodeStatus(nodeStatus: NodeStatus): Unit = this.nodeStatus = nodeStatus + + override def setNodeMsg(nodeMsg: String): Unit = this.nodeMsg = nodeMsg + + override def getNodeMsg: String = nodeMsg + + override def getUsedResource: Resource = usedResource + + override def setUsedResource(usedResource: Resource): Unit = this.usedResource = usedResource + + override def getTotalResource: Resource = totalResource + + override def setTotalResource(totalResource: Resource): Unit = this.totalResource = totalResource + + override def setNodeId(nodeId: String): Unit = this.nodeId = nodeId + + override def getNodeId: String = nodeId +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala new file mode 100644 index 0000000000..2df4e9d45a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} + + +trait ECMHealthService{ + + def getLastEMHealthReport: ECMHealthReport + + def reportHealth(report: ECMHealthReport): Unit + + def generateHealthReport(reportTime:Long): ECMHealthReport + + def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala new file mode 100644 index 0000000000..408bf25c62 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + + +trait ECMMetricsService { + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala new file mode 100644 index 0000000000..2ade991a79 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.em.{RegisterEMRequest, StopEMRequest} + + +trait ECMRegisterService { + + def registerECM(event: RegisterEMRequest): Unit + + def unRegisterECM(event: StopEMRequest): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala new file mode 100644 index 0000000000..de7c5b8528 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineStopRequest, EngineStopResponse} + + +trait EngineConnKillService { + + def dealEngineConnStop(engineStopRequest: EngineStopRequest): EngineStopResponse + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala new file mode 100644 index 0000000000..c98801d374 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.entity.node.EngineNode +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.{EngineConnBuildRequest, EngineConnLaunchRequest} + + + +trait EngineConnLaunchService { + /** + * launchEngine启动一个引擎的方法 + * + * @param engineConnBuildRequest 封装了引擎启动的参数 + */ + def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest): EngineNode + + def launchEngineConn(engineConnLaunchRequest: EngineConnLaunchRequest, duration: Long): EngineNode + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala new file mode 100644 index 0000000000..bfb7ef8942 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import java.util + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnLaunchRunner +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +/** + * The enginelistservice interface manages the interface started by the engine + * The most important submit method is to put the thread that starts the engine into the thread pool to start + * EngineListService接口管理引擎启动的接口 + * 最重要的submit方法是将启动引擎的线程放入到线程池中进行启动 + */ +trait EngineConnListService { + + def init(): Unit + + def getEngineConn(engineConnId: String): Option[EngineConn] + + def getEngineConns: util.List[EngineConn] + + def addEngineConn(engineConn: EngineConn): Unit + + def killEngineConn(engineConnId: String): Unit + + def getUsedResources: Resource + + def submit(runner: EngineConnLaunchRunner): Option[EngineConn] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala new file mode 100644 index 0000000000..4d751de00b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid + + +trait EngineConnPidCallbackService { + + + def dealPid(protocol: ResponseEngineConnPid): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala new file mode 100644 index 0000000000..8e234ded25 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallback + + +trait EngineConnStatusCallbackService { + + def dealEngineConnStatusCallback(protocol: EngineConnStatusCallback): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala new file mode 100644 index 0000000000..6ff1b35092 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + + +trait LocalDirsHandleService { + + def getEngineConnManagerHomeDir: String + + def getEngineConnWorkDir(user: String, ticketId: String): String + + def getEngineConnPublicDir: String + + def getEngineConnLogDir(user: String, ticketId: String): String + + def getEngineConnTmpDir(user: String, ticketId: String): String + + def cleanup(): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala new file mode 100644 index 0000000000..74f829d20d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.protocol.callback.LogCallbackProtocol + + + +trait LogCallbackService { + + def dealLog(protocol: LogCallbackProtocol): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala new file mode 100644 index 0000000000..0a74ea8dcf --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest + + +trait ResourceLocalizationService { + + def handleInitEngineConnResources(request: EngineConnLaunchRequest, engineConn: EngineConn): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala new file mode 100644 index 0000000000..4ed8ecf75f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +trait YarnCallbackService { + + def dealApplicationId(protocol: YarnAPPIdCallbackProtocol): Unit + + def dealApplicationURI(protocol: YarnInfoCallbackProtocol): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala new file mode 100644 index 0000000000..7a0e7d4335 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala @@ -0,0 +1,134 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, EngineConnInfo} +import com.webank.wedatasphere.linkis.ecm.core.launch._ +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.engineConn.DefaultEngineConn +import com.webank.wedatasphere.linkis.ecm.server.listener.{EngineConnAddEvent, EngineConnStatusChangeEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.{EngineConnLaunchService, ResourceLocalizationService} +import com.webank.wedatasphere.linkis.ecm.server.util.ECMUtils +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus.Failed +import com.webank.wedatasphere.linkis.manager.common.entity.node.{AMEngineNode, EngineNode} +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallbackToAM +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.rpc.Sender +import org.apache.commons.lang.exception.ExceptionUtils + +import scala.concurrent.duration.Duration +import scala.concurrent.{Await, ExecutionContextExecutorService, Future} +import scala.util.{Failure, Success} + + +abstract class AbstractEngineConnLaunchService extends EngineConnLaunchService with Logging { + + + protected implicit val executor: ExecutionContextExecutorService = Utils.newCachedExecutionContext(ECM_LAUNCH_MAX_THREAD_SIZE, "EngineConn-Manager-Thread-") + + protected var resourceLocalizationService: ResourceLocalizationService = _ + + def setResourceLocalizationService(service: ResourceLocalizationService): Unit = this.resourceLocalizationService = service + + + def beforeLaunch(conn: EngineConn, duration: Long): Unit = {} + + def afterLaunch(conn: EngineConn, duration: Long): Unit = {} + + override def launchEngineConn(request: EngineConnLaunchRequest, duration: Long): EngineNode = { + //1.创建engineConn和runner,launch 并设置基础属性 + val conn = createEngineConn + val runner = createEngineConnLaunchRunner + val launch = createEngineConnLaunch + launch.setEngineConnLaunchRequest(request) + runner.setEngineConnLaunch(launch) + conn.setEngineConnLaunchRunner(runner) + conn.setLabels(request.labels) + conn.setCreationDesc(request.creationDesc) + conn.setResource(request.nodeResource) + conn.setTickedId(request.ticketId) + conn.setStatus(NodeStatus.Starting) + conn.setEngineConnInfo(new EngineConnInfo) + //2.资源本地化,并且设置ecm的env环境信息 + getResourceLocalizationServie.handleInitEngineConnResources(request, conn) + //3.添加到list + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnAddEvent(conn)) + //4.run + try { + beforeLaunch(conn, duration) + runner.run() + launch match { + case pro: ProcessEngineConnLaunch => + val serviceInstance = ServiceInstance(GovernanceCommonConf.ENGINE_CONN_SPRING_NAME.getValue, ECMUtils.getInstanceByPort(pro.getEngineConnPort)) + conn.setServiceInstance(serviceInstance) + case _ => + } + + val future = Future { + afterLaunch(conn, duration) + } + + future onComplete { + case Failure(t) => + throw t + case Success(_) => + info(s"init ${conn.getServiceInstance} succeed.") + } + //超时忽略,如果状态翻转了则直接返回 + Utils.tryQuietly(Await.result(future, Duration(WAIT_ENGINECONN_PID.getValue.toLong, TimeUnit.MILLISECONDS))) + } catch { + //failed,1.被ms打断,2.超时,3.普通错误,比如process + case t: Throwable => + error(s"init ${conn.getServiceInstance} failed, now stop and delete it. message: ${t.getMessage}") + conn.getEngineConnLaunchRunner.stop() + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(conn.getServiceInstance, + NodeStatus.ShuttingDown, " wait init failed , reason " + ExceptionUtils.getRootCauseMessage(t))) + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(conn.getTickedId, Failed)) + throw t + } + val engineNode = new AMEngineNode() + engineNode.setLabels(conn.getLabels) + + engineNode.setServiceInstance(conn.getServiceInstance) + engineNode.setOwner(request.user) + engineNode.setMark("process") + engineNode + } + + def createEngineConn: EngineConn = new DefaultEngineConn + + + def createEngineConnLaunchRunner: EngineConnLaunchRunner = new EngineConnLaunchRunnerImpl + + + def createEngineConnLaunch: EngineConnLaunch + + + def getResourceLocalizationServie: ResourceLocalizationService = { + // TODO: null 抛出异常 + this.resourceLocalizationService + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala new file mode 100644 index 0000000000..d8c292c02a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala @@ -0,0 +1,131 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.io.File +import java.nio.file.Paths + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.{Utils, ZipUtils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnManagerEnv +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.service.{LocalDirsHandleService, ResourceLocalizationService} +import com.webank.wedatasphere.linkis.ecm.server.util.ECMUtils +import com.webank.wedatasphere.linkis.manager.common.protocol.bml.BmlResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.ProcessEngineConnLaunchRequest +import com.webank.wedatasphere.linkis.storage.FSFactory +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import com.webank.wedatasphere.linkis.storage.utils.{FileSystemUtils, StorageUtils} + +import scala.collection.JavaConversions._ +import scala.collection.mutable + + +class BmlResourceLocalizationService extends ResourceLocalizationService { + + private implicit val fs: FileSystem = FSFactory.getFs(StorageUtils.FILE).asInstanceOf[FileSystem] + + fs.init(null) + + private val seperator = File.separator + + private val schema = StorageUtils.FILE_SCHEMA + + private var localDirsHandleService: LocalDirsHandleService = _ + + def setLocalDirsHandleService(localDirsHandleService: LocalDirsHandleService): Unit = this.localDirsHandleService = localDirsHandleService + + override def handleInitEngineConnResources(request: EngineConnLaunchRequest, engineConn: EngineConn): Unit = { + // TODO: engineType判断是否下载到本地 unzip + //engine_type resourceId version判断是否更新,或者重新下载,将path给到properties + request match { + case request: ProcessEngineConnLaunchRequest => + val files = request.bmlResources + val linkDirsP = new mutable.HashMap[String, String] + val user = request.user + val ticketId = request.ticketId + val workDir = createDirIfNotExit(localDirsHandleService.getEngineConnWorkDir(user, ticketId)) + val emHomeDir = createDirIfNotExit(localDirsHandleService.getEngineConnManagerHomeDir) + val logDirs = createDirIfNotExit(localDirsHandleService.getEngineConnLogDir(user, ticketId)) + val tmpDirs = createDirIfNotExit(localDirsHandleService.getEngineConnTmpDir(user, ticketId)) + files.foreach(downloadBmlResource(request, linkDirsP, _, workDir)) + engineConn.getEngineConnLaunchRunner.getEngineConnLaunch.setEngineConnManagerEnv(new EngineConnManagerEnv { + override val engineConnManagerHomeDir: String = emHomeDir + override val engineConnWorkDir: String = workDir + override val engineConnLogDirs: String = logDirs + override val engineConnTempDirs: String = tmpDirs + override val engineConnManagerHost: String = Utils.getComputerName + override val engineConnManagerPort: String = DataWorkCloudApplication.getApplicationContext.getEnvironment.getProperty("server.port") + override val linkDirs: Map[String, String] = linkDirsP.toMap + // TODO: 注册发现信息的配置化 + override val properties: Map[String, String] = Map("eureka.client.serviceUrl.defaultZone" -> ECM_EUREKA_DEFAULTZONE) + }) + case _ => + } + } + + + private val bmlResourceSuffix = ".zip" + + private def createDirIfNotExit(noSchemaPath: String): String = { + val fsPath = new FsPath(schema + noSchemaPath) + if (!fs.exists(fsPath)) { + FileSystemUtils.mkdirs(fs, fsPath, Utils.getJvmUser) + fs.setPermission(fsPath, "rwxrwx---") + } + noSchemaPath + } + + def downloadBmlResource(request: ProcessEngineConnLaunchRequest, linkDirs: mutable.HashMap[String, String], resource: BmlResource, workDir: String): Unit = { + val resourceId = resource.getResourceId + val version = resource.getVersion + val user = request.user + resource.getVisibility match { + case BmlResource.BmlResourceVisibility.Public => + val publicDir = localDirsHandleService.getEngineConnPublicDir + val bmlResourceDir = schema + Paths.get(publicDir, resourceId, version).toFile.getPath + val fsPath = new FsPath(bmlResourceDir) + if (!fs.exists(fsPath)) { + ECMUtils.downLoadBmlResourceToLocal(resource, user, fsPath.getPath) + val unzipDir = fsPath.getSchemaPath + File.separator + resource.getFileName.substring(0, resource.getFileName.lastIndexOf(".")) + FileSystemUtils.mkdirs(fs, new FsPath(unzipDir), Utils.getJvmUser) + ZipUtils.unzip(bmlResourceDir + File.separator + resource.getFileName, unzipDir) + fs.delete(new FsPath(bmlResourceDir + File.separator + resource.getFileName)) + } + //2.软连,并且添加到map + val dirAndFileList = fs.listPathWithError(fsPath) + dirAndFileList.getFsPaths.foreach { + case path: FsPath => + val name = new File(path.getPath).getName + linkDirs.put(path.getPath, workDir + seperator + name) + } + case BmlResource.BmlResourceVisibility.Private => + val fsPath = new FsPath(schema + workDir) + if (!fs.exists(fsPath)) { + FileSystemUtils.mkdirs(fs, fsPath, Utils.getJvmUser) + ECMUtils.downLoadBmlResourceToLocal(resource, user, fsPath.getPath) + ZipUtils.unzip(schema + workDir + File.separator + resource.getFileName, fsPath.getSchemaPath) + fs.delete(new FsPath(schema + workDir + File.separator + resource.getFileName)) + } + case BmlResource.BmlResourceVisibility.Label => + } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala new file mode 100644 index 0000000000..feb5cb1074 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala @@ -0,0 +1,137 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.Date +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.listener.{ECMClosedEvent, ECMReadyEvent} +import com.webank.wedatasphere.linkis.ecm.server.report.DefaultECMHealthReport +import com.webank.wedatasphere.linkis.ecm.server.service.{ECMHealthService, EngineConnListService} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.{NodeHealthy, NodeStatus} +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.{NodeHealthyInfo, NodeOverLoadInfo} +import com.webank.wedatasphere.linkis.manager.common.entity.resource.{CommonNodeResource, LoadInstanceResource} +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import org.springframework.beans.factory.annotation.Autowired + + +class DefaultECMHealthService extends ECMHealthService with ECMEventListener { + + val maxResource = new LoadInstanceResource(ECM_MAX_MEMORY_AVAILABLE, ECM_MAX_CORES_AVAILABLE, ECM_MAX_CREATE_INSTANCES) + val minResource = new LoadInstanceResource(ECM_PROTECTED_MEMORY, ECM_PROTECTED_CORES, ECM_PROTECTED_INSTANCES) + private val runtime: Runtime = Runtime.getRuntime + + private val future = Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = { + if (ECMApplication.isReady) { + reportHealth(getLastEMHealthReport) + } + } + }, ECM_HEALTH_REPORT_DELAY, ECM_HEALTH_REPORT_PERIOD, TimeUnit.SECONDS) + + @Autowired + private var engineConnListService: EngineConnListService = _ + + override def getLastEMHealthReport: ECMHealthReport = { + val report = new DefaultECMHealthReport + report.setNodeId(ECMApplication.getECMServiceInstance.toString) + report.setNodeStatus(NodeStatus.Running) + report.setTotalResource(maxResource) + report.setProtectedResource(minResource) + report.setUsedResource(engineConnListService.getUsedResources) + report.setReportTime(new Date().getTime) + report.setRunningEngineConns(ECMApplication.getContext.getECMMetrics.getRunningEngineConns) + val info = new NodeOverLoadInfo + info.setMaxMemory(runtime.maxMemory()) + info.setUsedMemory(runtime.totalMemory() - runtime.freeMemory()) + // TODO: 根据系统获取当前操作系统负载 + report.setOverload(info) + report + } + + // TODO: 可能还需要个判断health状态的方法 + + override def reportHealth(report: ECMHealthReport): Unit = { + val heartbeat: NodeHeartbeatMsg = transferECMHealthReportToNodeHeartbeatMsg(report) + Sender.getSender(MANAGER_SPRING_NAME).send(heartbeat) + } + + private def transferECMHealthReportToNodeHeartbeatMsg(report: ECMHealthReport) = { + val heartbeat = new NodeHeartbeatMsg + heartbeat.setOverLoadInfo(report.getOverload) + heartbeat.setStatus(report.getNodeStatus) + heartbeat.setServiceInstance(ECMApplication.getECMServiceInstance) + val resource = new CommonNodeResource + resource.setMaxResource(maxResource) + resource.setMinResource(minResource) + resource.setUsedResource(resource.getUsedResource) + heartbeat.setNodeResource(resource) + heartbeat.setHeartBeatMsg("") + val nodeHealthyInfo = new NodeHealthyInfo + nodeHealthyInfo.setMsg("") + nodeHealthyInfo.setNodeHealthy(NodeHealthy.Healthy) + heartbeat.setHealthyInfo(nodeHealthyInfo) + heartbeat + } + + override def generateHealthReport(reportTime: Long): ECMHealthReport = { + // TODO: 历史查询 + null + } + + private def emShutdownHealthReport(event: ECMClosedEvent): Unit = { + val report = getLastEMHealthReport + report.setNodeStatus(NodeStatus.ShuttingDown) + reportHealth(report) + } + + private def emReadyHealthReport(event: ECMReadyEvent): Unit = reportHealth(getLastEMHealthReport) + + + override def onEvent(event: ECMEvent): Unit = event match { + case event: ECMReadyEvent => + emReadyHealthReport(event) + case event: ECMClosedEvent => + cancelHealthReportThread(event) + emShutdownHealthReport(event) + presistenceLeftReports(event) + case _ => + } + + private def cancelHealthReportThread(event: ECMClosedEvent): Unit = { + + } + + private def presistenceLeftReports(event: ECMClosedEvent): Unit = { + // TODO: 持久化 剩余的reports + } + + @Receiver + override def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg = { + val hearlthReport = getLastEMHealthReport + transferECMHealthReportToNodeHeartbeatMsg(hearlthReport) + } + + + } diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala new file mode 100644 index 0000000000..9185b63055 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.service.ECMMetricsService + + +class DefaultECMMetricsService extends ECMMetricsService with ECMEventListener{ + override def onEvent(event: ECMEvent): Unit = ??? +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala new file mode 100644 index 0000000000..7607230a65 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala @@ -0,0 +1,99 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util +import java.util.Collections + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.listener.{ECMClosedEvent, ECMReadyEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.ECMRegisterService +import com.webank.wedatasphere.linkis.manager.common.entity.resource._ +import com.webank.wedatasphere.linkis.manager.common.protocol.em.{RegisterEMRequest, StopEMRequest} +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant +import com.webank.wedatasphere.linkis.rpc.Sender + + +class DefaultECMRegisterService extends ECMRegisterService with ECMEventListener with Logging { + + private implicit def readyEvent2RegisterECMRequest(event: ECMReadyEvent): RegisterEMRequest = { + val request = new RegisterEMRequest + val instance = Sender.getThisServiceInstance + request.setUser(Utils.getJvmUser) + request.setServiceInstance(instance) + request.setAlias(instance.getApplicationName) + request.setLabels(getLabelsFromArgs(event.params)) + request.setNodeResource(getEMRegiterResourceFromConfiguration) + request + } + + private def getLabelsFromArgs(params: Array[String]): util.Map[String, AnyRef] = { + import scala.collection.JavaConversions._ + val labelRegex = """label\.(.+)\.(.+)=(.+)""".r + val labels = new util.HashMap[String, AnyRef]() + // TODO: magic + labels += LabelKeyConstant.SERVER_ALIAS_KEY -> Collections.singletonMap("alias", ENGINE_CONN_MANAGER_SPRING_NAME) + // TODO: group by key + /* params.foreach { + case labelRegex(key, valueKey, valueContent) => labels += key -> (valueKey, valueContent) + case _ => + }*/ + labels + } + + private def getEMRegiterResourceFromConfiguration: NodeResource = { + val maxResource = new LoadInstanceResource(ECM_MAX_MEMORY_AVAILABLE, ECM_MAX_CORES_AVAILABLE, ECM_MAX_CREATE_INSTANCES) + val minResource = new LoadInstanceResource(ECM_PROTECTED_MEMORY, ECM_PROTECTED_CORES, ECM_PROTECTED_INSTANCES) + val nodeResource = new CommonNodeResource + nodeResource.setResourceType(ResourceType.LoadInstance) + nodeResource.setExpectedResource(Resource.getZeroResource(maxResource)) + nodeResource.setLeftResource(maxResource) + nodeResource.setLockedResource(Resource.getZeroResource(maxResource)) + nodeResource.setMaxResource(maxResource) + nodeResource.setMinResource(minResource) + nodeResource.setUsedResource(Resource.getZeroResource(maxResource)) + nodeResource + } + + override def onEvent(event: ECMEvent): Unit = event match { + case event: ECMReadyEvent => registerECM(event) + case event: ECMClosedEvent => unRegisterECM(event) + case _ => + } + + private implicit def closeEvent2StopECMRequest(event: ECMClosedEvent): StopEMRequest = { + val request = new StopEMRequest + val instance = Sender.getThisServiceInstance + request.setUser(Utils.getJvmUser) + request.setEm(instance) + request + } + + override def registerECM(request: RegisterEMRequest): Unit = { + info("start register ecm") + Sender.getSender(MANAGER_SPRING_NAME).send(request) + } + + override def unRegisterECM(request: StopEMRequest): Unit = { + info("start unRegister ecm") + Sender.getSender(MANAGER_SPRING_NAME).send(request) + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java new file mode 100644 index 0000000000..bb139669a7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java @@ -0,0 +1,139 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; +import com.webank.wedatasphere.linkis.common.utils.Utils; +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn; +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnKillService; +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnListService; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineStopRequest; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineStopResponse; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineSuicideRequest; +import com.webank.wedatasphere.linkis.message.annotation.Receiver; +import com.webank.wedatasphere.linkis.rpc.Sender; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + + +public class DefaultEngineConnKillService implements EngineConnKillService { + + private static final Logger logger = LoggerFactory.getLogger(DefaultEngineConnKillService.class); + + private EngineConnListService engineConnListService; + + public void setEngineConnListService(EngineConnListService engineConnListService) { + this.engineConnListService = engineConnListService; + } + + @Override + @Receiver + public EngineStopResponse dealEngineConnStop(EngineStopRequest engineStopRequest) { + EngineConn engineConn = getEngineConnByServiceInstance(engineStopRequest.getServiceInstance()); + EngineStopResponse response = new EngineStopResponse(); + if (null != engineConn) { + if(!killEngineConnByPid(engineConn)) { + response.setStopStatus(false); + response.setMsg("Kill engine " + engineConn.getServiceInstance().toString() + " failed."); + } else { + response.setStopStatus(true); + response.setMsg("Kill engine " + engineConn.getServiceInstance().toString() + " succeed."); + } + } else { + logger.warn("Cannot find engineconn : " + engineStopRequest.getServiceInstance().toString() + " in this engineConnManager engineConn list, cannot kill."); + response.setStopStatus(false); + response.setMsg("EngineConn " + engineStopRequest.getServiceInstance().toString() + " was not found in this engineConnManager."); + } + if (!response.getStopStatus()) { + EngineSuicideRequest request = new EngineSuicideRequest(engineStopRequest.getServiceInstance(), engineStopRequest.getUser()); + try { + Sender.getSender(engineStopRequest.getServiceInstance()).send(request); + response.setStopStatus(true); + response.setMsg(response.getMsg() + " Now send suicide request to engine."); + } catch (Exception e) { + response.setMsg(response.getMsg() + " Sended suicide request to engine error, " + e.getMessage()); + } + } + return response; + } + + private EngineConn getEngineConnByServiceInstance(ServiceInstance serviceInstance) { + if (null == serviceInstance) { + return null; + } + List engineConnList = engineConnListService.getEngineConns(); + for (EngineConn engineConn : engineConnList) { + if (engineConn.getServiceInstance().equals(serviceInstance)) { + return engineConn; + } + } + return null; + } + + private boolean killEngineConnByPid(EngineConn engineConn) { + logger.info("try to kill {} toString with pid({}).", engineConn.getServiceInstance().toString(), engineConn.getPid()); + if (StringUtils.isNotBlank(engineConn.getPid())) { + String k15cmd = "sudo kill " + engineConn.getPid(); + String k9cmd = "sudo kill -9 " + engineConn.getPid(); + int tryNum = 1; + try { + while (isProcessAlive(engineConn.getPid()) && tryNum <= 3) { + logger.info("{} still alive with pid({}), use shell command to kill it. try {}++", engineConn.getServiceInstance().toString(), engineConn.getPid(), tryNum++); + if (tryNum < 3) { + Utils.exec(k15cmd.split(" "), 3000L); + } else { + Utils.exec(k9cmd.split(" "), 3000L); + } + Thread.sleep(3000); + } + } catch (InterruptedException e) { + logger.error("Interrupted while killing engine {} with pid({})." + engineConn.getServiceInstance().toString(), engineConn.getPid()); + } + if (isProcessAlive(engineConn.getPid())) { + return false; + } else { + return true; + } + } else { + logger.warn("cannot kill {} with empty pid.", engineConn.getServiceInstance().toString()); + return false; + } + } + + private boolean isProcessAlive(String pid) { + String findCmd = "\"ps -ef | grep " + pid + " | grep EngineConnServer | awk '{print \\\"exists_\\\"$2}' | grep " + pid + " \""; + List cmdList = new ArrayList<>(); + cmdList.add("sudo"); + cmdList.add("-S"); + cmdList.add("bash"); + cmdList.add("-c"); + cmdList.add(findCmd); + try { + // todo + String rs = Utils.exec(cmdList.toArray(new String[0]), 5000L); + return null != rs && rs.contains("exists_" + pid); + } catch (Exception e) { + logger.error("Method isProcessAlive failed, " + e.getMessage()); + } + return true; + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala new file mode 100644 index 0000000000..04d20229c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala @@ -0,0 +1,124 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util +import java.util.concurrent.ConcurrentHashMap + +import com.google.common.collect.Interners +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, YarnEngineConn} +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnLaunchRunner +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.converter.ECMEngineConverter +import com.webank.wedatasphere.linkis.ecm.server.listener._ +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnListService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.{Resource, ResourceType} + +import scala.collection.JavaConversions._ + + +class DefaultEngineConnListService extends EngineConnListService with ECMEventListener with Logging { + /** + * key:tickedId,value :engineConn + */ + private val engineConnMap = new ConcurrentHashMap[String, EngineConn] + + val lock = Interners.newWeakInterner[String] + + override def init(): Unit = {} + + override def getEngineConn(engineConnId: String): Option[EngineConn] = Option(engineConnMap.get(engineConnId)) + + override def getEngineConns: util.List[EngineConn] = engineConnMap.values().toList + + override def addEngineConn(engineConn: EngineConn): Unit = { + if (ECMApplication.isReady) + engineConnMap.put(engineConn.getTickedId, engineConn) + } + + override def killEngineConn(engineConnId: String): Unit = { + val conn = engineConnMap.remove(engineConnId) + if (conn != null) { + Utils.tryAndWarn{ + conn.close() + info(s"engineconn ${conn.getPid} was closed.") + } + } + } + + override def getUsedResources: Resource = engineConnMap.values().map(_.getResource.getMinResource).fold(Resource.initResource(ResourceType.Default))(_ + _) + + override def submit(runner: EngineConnLaunchRunner): Option[EngineConn] = ??? + + def updateYarnAppId(event: YarnAppIdCallbackEvent): Unit = { + updateYarnEngineConn(x => x.setApplicationId(event.protocol.applicationId), event.protocol.nodeId) + } + + def updateYarnEngineConn(implicit updateFunction: YarnEngineConn => Unit, nodeId: String): Unit = { + lock.intern(nodeId) synchronized { + engineConnMap.get(nodeId) match { + case e: YarnEngineConn => updateFunction(e) + case e: EngineConn => + engineConnMap.put(nodeId, ECMEngineConverter.engineConn2YarnEngineConn(e)) + } + } + } + + def updateEngineConn(updateFunction: EngineConn => Unit, nodeId: String): Unit = { + lock.intern(nodeId) synchronized { + engineConnMap.get(nodeId) match { + case e: EngineConn => updateFunction(e) + } + } + } + + def updateYarnInfo(event: YarnInfoCallbackEvent): Unit = { + updateYarnEngineConn(x => x.setApplicationURL(event.protocol.uri), event.protocol.nodeId) + } + + def updatePid(event: EngineConnPidCallbackEvent): Unit = { + updateEngineConn(x => { + x.setPid(event.protocol.pid) + x.setServiceInstance(event.protocol.serviceInstance) + }, event.protocol.ticketId) + } + + def updateEngineConnStatus(tickedId: String, updateStatus: NodeStatus): Unit = { + updateEngineConn(x => x.setStatus(updateStatus), tickedId) + } + + override def onEvent(event: ECMEvent): Unit = { + info(s"Deal event $event") + event match { + case event: ECMClosedEvent => shutdownEngineConns(event) + case event: YarnAppIdCallbackEvent => updateYarnAppId(event) + case event: YarnInfoCallbackEvent => updateYarnInfo(event) + case event: EngineConnPidCallbackEvent => updatePid(event) + case EngineConnAddEvent(engineConn) => addEngineConn(engineConn) + case EngineConnStatusChangeEvent(tickedId, updateStatus) => updateEngineConnStatus(tickedId, updateStatus) + case _ => + } + } + + private def shutdownEngineConns(event: ECMClosedEvent): Unit = { + engineConnMap.keys().foreach(killEngineConn) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala new file mode 100644 index 0000000000..1f0a6b3002 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnPidCallbackEvent +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnPidCallbackService +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.message.annotation.Receiver + + +class DefaultEngineConnPidCallbackService extends EngineConnPidCallbackService with Logging { + + @Receiver + override def dealPid(protocol: ResponseEngineConnPid): Unit = { + //1.设置pid + //2.设置serviceInstance + //3.状态为running + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnPidCallbackEvent(protocol)) + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala new file mode 100644 index 0000000000..bea04016bd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.MANAGER_SPRING_NAME +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnStatusChangeEvent +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnStatusCallbackService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus.{Failed, Running} +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineConnStatusCallback, EngineConnStatusCallbackToAM} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import org.springframework.stereotype.Service + + +@Service +class DefaultEngineConnStatusCallbackService extends EngineConnStatusCallbackService with Logging { + + @Receiver + override def dealEngineConnStatusCallback(protocol: EngineConnStatusCallback): Unit = { + info(s"Start to deal EngineConnStatusCallback $protocol") + + if (NodeStatus.isAvailable(protocol.status)) { + + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(protocol.ticketId, Running)) + } else { + + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(protocol.serviceInstance, + protocol.status, protocol.initErrorMsg)) + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(protocol.ticketId, Failed)) + } + + info(s"Finished to deal EngineConnStatusCallback $protocol") + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala new file mode 100644 index 0000000000..039a58f84e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.io.File +import java.nio.file.Paths + +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.service.LocalDirsHandleService + + +class DefaultLocalDirsHandleService extends LocalDirsHandleService { + + // TODO: 检测当前磁盘的健康状态,如果目录满了,需要上报am + + override def cleanup(): Unit = ??? + + + override def getEngineConnManagerHomeDir: String = ECM_HOME_DIR + + override def getEngineConnWorkDir(user: String, ticketId: String): String = new FsPath(Paths.get(ENGINECONN_ROOT_DIR, user, "workDir", ticketId).toFile.getPath).getPath + + override def getEngineConnPublicDir: String = ENGINECONN_PUBLIC_DIR + + override def getEngineConnLogDir(user: String, ticketId: String): String = s"${getEngineConnWorkDir(user, ticketId)}${File.separator}logs" + + override def getEngineConnTmpDir(user: String, ticketId: String): String = s"${getEngineConnWorkDir(user, ticketId)}${File.separator}tmp" + + +} + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala new file mode 100644 index 0000000000..381a5276f6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.listener.{YarnAppIdCallbackEvent, YarnInfoCallbackEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.YarnCallbackService +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +class DefaultYarnCallbackService extends YarnCallbackService { + + @Receiver + override def dealApplicationId(protocol: YarnAPPIdCallbackProtocol): Unit = { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(YarnAppIdCallbackEvent(protocol)) + } + + @Receiver + override def dealApplicationURI(protocol: YarnInfoCallbackProtocol): Unit = { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(YarnInfoCallbackEvent(protocol)) + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala new file mode 100644 index 0000000000..8dfcbedc9d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala @@ -0,0 +1,64 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.core.launch.{DiscoveryMsgGenerator, EngineConnLaunch, EurekaDiscoveryMsgGenerator} +import com.webank.wedatasphere.linkis.ecm.linux.launch.LinuxProcessEngineConnLaunch +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.{ENGINECONN_SPRING_NAME, _} +import com.webank.wedatasphere.linkis.manager.common.entity.node.EngineNode +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.{EngineConnBuildRequest, EngineConnLaunchRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf._ +import com.webank.wedatasphere.linkis.rpc.Sender + +import scala.concurrent.duration.Duration + + +class LinuxProcessEngineConnLaunchService extends ProcessEngineConnLaunchService { + + /** + * launchEngine启动一个引擎的方法 + * + * @param engineConnBuildRequest 封装了引擎启动的参数 + */ + @Receiver + def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest, smc: ServiceMethodContext): EngineNode = { + Sender.getSender(ENGINECONN_SPRING_NAME).ask(engineConnBuildRequest) match { + case request: EngineConnLaunchRequest if ENGINECONN_CREATE_DURATION._1 != 0L => + launchEngineConn(request, ENGINECONN_CREATE_DURATION._1) + case request: EngineConnLaunchRequest => + launchEngineConn(request, smc.getAttribute(DURATION_KEY).asInstanceOf[Duration]._1) + } + } + + override def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest): EngineNode = { + Sender.getSender(ENGINECONN_SPRING_NAME).ask(engineConnBuildRequest) match { + case request: EngineConnLaunchRequest => + launchEngineConn(request, ENGINECONN_CREATE_DURATION._1) + } + } + + def createDiscoveryMsgGenerator: DiscoveryMsgGenerator = new EurekaDiscoveryMsgGenerator + + override def createEngineConnLaunch: EngineConnLaunch = { + val launch = new LinuxProcessEngineConnLaunch + launch.setDiscoveryMsgGenerator(createDiscoveryMsgGenerator) + launch + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala new file mode 100644 index 0000000000..852499e754 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala @@ -0,0 +1,86 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.ProcessEngineConnLaunch +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.MANAGER_SPRING_NAME +import com.webank.wedatasphere.linkis.ecm.server.exception.ECMErrorException +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnStatusChangeEvent +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus._ +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallbackToAM +import com.webank.wedatasphere.linkis.rpc.Sender +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.exception.ExceptionUtils + +import scala.concurrent.duration.Duration +import scala.concurrent.{Future, TimeoutException} + + +abstract class ProcessEngineConnLaunchService extends AbstractEngineConnLaunchService { + + override def afterLaunch(conn: EngineConn, duration: Long): Unit = { + conn.getEngineConnLaunchRunner.getEngineConnLaunch match { + case launch: ProcessEngineConnLaunch => try { + processMonitorThread(conn, launch, duration) + } catch { + case e: ECMErrorException => + warn("EngineConn init failed", e) + val logPath = conn.getEngineConnManagerEnv.engineConnWorkDir + "/logs" + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(conn.getServiceInstance, + NodeStatus.ShuttingDown, "Failed to start EngineConn, reason: " + ExceptionUtils.getRootCauseMessage(e) + s"You can go to this path($logPath) to find the reason or ask the administrator for help")) + } + case _ => + } + } + + private def processMonitorThread(engineConn: EngineConn, launch: ProcessEngineConnLaunch, timeout: Long): Unit = { + val isCompleted: EngineConn => Boolean = engineConn => engineConn.getStatus == Success || engineConn.getStatus == Failed + val tickedId = engineConn.getTickedId + Future { + val iterator = IOUtils.lineIterator(launch.getProcessInputStream, "utf-8") + while (!isCompleted(engineConn) && iterator.hasNext) { + println(s"${engineConn.getTickedId}:${iterator.next()}") + } + val exitCode = Option(launch.processWaitFor) + if (exitCode.exists(_ != 0)) { + // TODO: 错误日志获取 + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(tickedId, ShuttingDown)) + } else { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(tickedId, Success)) + } + } + Utils.tryThrow(Utils.waitUntil(() => engineConn.getStatus != Starting, Duration(timeout, TimeUnit.MILLISECONDS))) { + case e: TimeoutException => + throw new ECMErrorException(10000, s"wait for $engineConn initial timeout.") + case e: InterruptedException => //比如被ms cancel + throw new ECMErrorException(10000, s"wait for $engineConn initial interrupted.") + case t: Throwable => + error(s"unexpected error, now shutdown it.") + throw t + } + if (engineConn.getStatus == ShuttingDown) { + throw new ECMErrorException(10000, s"Failed to init $engineConn, status shutting down") + } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala new file mode 100644 index 0000000000..21e0b74ff5 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala @@ -0,0 +1,118 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.spring + +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMEventListener +import com.webank.wedatasphere.linkis.ecm.server.context.{DefaultECMContext, ECMContext} +import com.webank.wedatasphere.linkis.ecm.server.service._ +import com.webank.wedatasphere.linkis.ecm.server.service.impl._ +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.context.annotation.{Bean, Configuration} + + +@Configuration +class ECMSpringConfiguration { + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnManagerContext: ECMContext = { + new DefaultECMContext + } + + @Bean + @ConditionalOnMissingBean + def getDefaultYarnCallbackService: YarnCallbackService = { + new DefaultYarnCallbackService + } + + @Bean + @ConditionalOnMissingBean + def getBmlResourceLocalizationService(context: ECMContext, localDirsHandleService: LocalDirsHandleService): ResourceLocalizationService = { + val service: BmlResourceLocalizationService = new BmlResourceLocalizationService + service.setLocalDirsHandleService(localDirsHandleService) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultLogCallbackService: LogCallbackService = { + null + } + + @Bean + @ConditionalOnMissingBean + def getDefaultlocalDirsHandleService: LocalDirsHandleService = { + new DefaultLocalDirsHandleService + } + + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnPidCallbackService: EngineConnPidCallbackService = { + new DefaultEngineConnPidCallbackService + } + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnListService(context: ECMContext): EngineConnListService = { + implicit val service: DefaultEngineConnListService = new DefaultEngineConnListService + registerSyncListener(context) + service + } + + @Bean + @ConditionalOnMissingBean + def getLinuxProcessEngineConnLaunchService(resourceLocalizationService: ResourceLocalizationService): EngineConnLaunchService = { + val service = new LinuxProcessEngineConnLaunchService + service.setResourceLocalizationService(resourceLocalizationService) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultECMRegisterService(context: ECMContext): ECMRegisterService = { + implicit val service: DefaultECMRegisterService = new DefaultECMRegisterService + registerSyncListener(context) + service + } + + + @Bean + @ConditionalOnMissingBean + def getDefaultECMHealthService(context: ECMContext): ECMHealthService = { + implicit val service: DefaultECMHealthService = new DefaultECMHealthService + registerSyncListener(context) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnKillService(engineConnListService: EngineConnListService): EngineConnKillService = { + val service = new DefaultEngineConnKillService + service.setEngineConnListService(engineConnListService) + service + } + + private def registerSyncListener(context: ECMContext)(implicit listener: ECMEventListener): Unit = { + context.getECMSyncListenerBus.addListener(listener) + } + + private def registerASyncListener(context: ECMContext)(implicit listener: ECMEventListener): Unit = { + context.getECMAsyncListenerBus.addListener(listener) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala new file mode 100644 index 0000000000..0c41ac14bf --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.util + +import java.io.{File, InputStream} +import java.util + +import com.webank.wedatasphere.linkis.bml.client.{BmlClient, BmlClientFactory} +import com.webank.wedatasphere.linkis.bml.protocol.BmlDownloadResponse +import com.webank.wedatasphere.linkis.ecm.server.exception.ECMErrorException +import com.webank.wedatasphere.linkis.manager.common.protocol.bml.BmlResource +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import org.apache.commons.io.{FileUtils, IOUtils} + +import scala.collection.JavaConversions._ + + +object ECMUtils { + + private def download(resource: BmlResource, userName: String): util.Map[String, Object] = { + val client: BmlClient = createBMLClient(userName) + var response: BmlDownloadResponse = null + if (resource.getVersion == null) { + response = client.downloadShareResource(userName, resource.getResourceId) + } else { + response = client.downloadShareResource(userName, resource.getResourceId, resource.getVersion) + } + if (!response.isSuccess) throw new ECMErrorException(911115, "下载失败") + val map = new util.HashMap[String, Object] + map += "path" -> response.fullFilePath + map += "is" -> response.inputStream + } + + def downLoadBmlResourceToLocal(resource: BmlResource, userName: String, path: String)(implicit fs: FileSystem): Unit = { + val is = download(resource, userName).get("is").asInstanceOf[InputStream] + val os = FileUtils.openOutputStream(new File(path + File.separator + resource.getFileName)) + IOUtils.copy(is, os) + IOUtils.closeQuietly(os) + IOUtils.closeQuietly(is) + } + + private def createBMLClient(userName: String): BmlClient = { + if (userName == null) + BmlClientFactory.createBmlClient() + else + BmlClientFactory.createBmlClient(userName) + } + + + private val address = Sender.getThisInstance.substring(0, Sender.getThisInstance.lastIndexOf(":")) + + def getInstanceByPort(port: String): String = address + ":" + port + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/pom.xml new file mode 100644 index 0000000000..91420a63c0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/pom.xml @@ -0,0 +1,36 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-engineconn-manager + pom + + linkis-engineconn-manager-core + linkis-engineconn-manager-server + linkis-engineconn-linux-launch + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml new file mode 100644 index 0000000000..444957637e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml @@ -0,0 +1,128 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-computation-engineconn + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-accessible-executor + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-resource-executor + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-callback-service + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-cs-engine-support + ${linkis.version} + + + reflections + org.reflections + + + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + com.google.guava + guava + ${guava.version} + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala new file mode 100644 index 0000000000..cc4661aaf7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{ByteType, CommonVars} + + +object ComputationExecutorConf { + + val ENGINECONN_RESULT_SET_STORE_PATH = CommonVars("wds.linkis.engineconn.resultSet.default.store.path", "hdfs:///tmp") + + val ENGINE_RESULT_SET_MAX_CACHE = CommonVars("wds.linkis.engine.resultSet.cache.max", new ByteType("0k")) + + val ENGINE_DEFAULT_LIMIT = CommonVars("wds.linkis.engine.default.limit", 5000) + + val ENGINE_LOCK_DEFAULT_EXPIRE_TIME = CommonVars("wds.linkis.engine.lock.expire.time", 2 * 60 * 1000) + + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala new file mode 100644 index 0000000000..dc07740049 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.cs.client.utils.ContextServiceUtils +import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationExecutorHook +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest + + +class CSEnginePreExecuteHook extends ComputationExecutorHook with Logging { + + private val csResourceParser: CSResourceParser = new CSResourceParser + + override def getHookName: String = "ContextServicePreHook" + + override def beforeExecutorExecute(engineExecutionContext: EngineExecutionContext, engineCreationContext: EngineCreationContext, code: String): String = { + val props = engineExecutionContext.getProperties + if (null != props && props.containsKey(CSCommonUtils.CONTEXT_ID_STR)) { + var parsedCode = code + val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap (props) + val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap (props) + engineExecutionContext.addProperty (CSCommonUtils.CONTEXT_ID_STR, contextIDValueStr) + engineExecutionContext.addProperty (CSCommonUtils.NODE_NAME_STR, nodeNameStr) + info (s"Start to call cs engine pre hook,contextID is $contextIDValueStr, nodeNameStr is $nodeNameStr") + parsedCode = csResourceParser.parse (props, parsedCode, contextIDValueStr, nodeNameStr) + info (s"Finished to call cs engine pre hook,contextID is $contextIDValueStr, nodeNameStr is $nodeNameStr") + parsedCode + } else { + code + } + } + + +} diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala similarity index 86% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala index df09dfc170..fb70c01b93 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala @@ -11,23 +11,18 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.cs - +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs import java.util import java.util.regex.Pattern import com.webank.wedatasphere.linkis.cs.client.service.CSResourceService -import com.webank.wedatasphere.linkis.engine.PropertiesExecuteRequest import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions._ import scala.collection.mutable.ArrayBuffer -/** - * @author peacewong - * @date 2020/3/5 19:42 - */ + class CSResourceParser { private val pb = Pattern.compile("cs://[^\\s\"]+[$\\s]{0,1}", Pattern.CASE_INSENSITIVE) @@ -41,7 +36,7 @@ class CSResourceParser { bmlResourceNames.toArray } - def parse(executeRequest: PropertiesExecuteRequest, code: String, contextIDValueStr: String, nodeNameStr: String): String = { + def parse(props: util.Map[String, Object], code: String, contextIDValueStr: String, nodeNameStr: String): String = { //TODO getBMLResource peaceWong val bmlResourceList = CSResourceService.getInstance().getUpstreamBMLResource(contextIDValueStr, nodeNameStr) @@ -66,7 +61,7 @@ class CSResourceParser { } } - executeRequest.properties.put("resources", parsedResources) + props.put("resources", parsedResources) StringUtils.replaceEach(code, preFixNames.toArray, parsedNames.toArray) } diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala similarity index 92% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala index e6c4dadc87..e2ff4593c6 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala @@ -11,10 +11,9 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.cs +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs import java.util.Date - import com.webank.wedatasphere.linkis.common.io.resultset.ResultSetWriter import com.webank.wedatasphere.linkis.common.io.{MetaData, Record} import com.webank.wedatasphere.linkis.common.utils.Logging @@ -24,22 +23,19 @@ import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.{ContextScope import com.webank.wedatasphere.linkis.cs.common.entity.metadata.{CSColumn, CSTable} import com.webank.wedatasphere.linkis.cs.common.entity.source.CommonContextKey import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils -import com.webank.wedatasphere.linkis.engine.execute.EngineExecutorContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext import com.webank.wedatasphere.linkis.storage.domain.Column import com.webank.wedatasphere.linkis.storage.utils.StorageUtils import org.apache.commons.lang.StringUtils -/** - * @author peacewong - * @date 2020/3/13 16:29 - */ + object CSTableRegister extends Logging{ - def registerTempTable(engineExecutorContext: EngineExecutorContext, + def registerTempTable(engineExecutionContext: EngineExecutionContext, writer: ResultSetWriter[_ <: MetaData, _ <: Record], alias: String, columns: Array[Column]): Unit = { - val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap(engineExecutorContext.getProperties) - val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap(engineExecutorContext.getProperties) + val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap(engineExecutionContext.getProperties) + val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap(engineExecutionContext.getProperties) if (StringUtils.isNotBlank(contextIDValueStr) && StringUtils.isNotBlank(nodeNameStr)) { info(s"Start to register TempTable nodeName:$nodeNameStr") diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala new file mode 100644 index 0000000000..ef1e0cf3dc --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +class CommonEngineConnTask(val taskId: String, var taskSupportRetry: Boolean = false) extends EngineConnTask { + + private var code: String = _ + private var prop: util.Map[String, Object] = _ + private var status: ExecutionNodeStatus = ExecutionNodeStatus.Inited + private var labels: Array[Label[_]] = new Array[Label[_]](0) + private var serviceInstance: ServiceInstance = _ + + override def getTaskId: String = taskId + + override def isTaskSupportRetry: Boolean = taskSupportRetry + + override def getCode: String = code + + override def setCode(code: String): Unit = this.code = code + + override def getProperties: util.Map[String, Object] = prop + + override def setProperties(properties: util.Map[String, Object]): Unit = this.prop = properties + + override def data(key: String, value: Object): Unit = this.prop.put(key, value) + + override def getStatus: ExecutionNodeStatus = status + + override def setStatus(status: ExecutionNodeStatus): Unit = this.status = status + + override def getLables: Array[Label[_]] = labels + + override def setLabels(labels: Array[Label[_]]): Unit = this.labels = labels + + override def getCallbackServiceInstance(): ServiceInstance = serviceInstance + + override def setCallbackServiceInstance(serviceInstance: ServiceInstance): Unit = this.serviceInstance = serviceInstance +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala new file mode 100644 index 0000000000..3f5e957789 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineConnTask { + + def getTaskId: String + + def isTaskSupportRetry: Boolean + + def getCode: String + + def setCode(code: String): Unit + + def getProperties: util.Map[String, Object] + + def setProperties(properties: util.Map[String, Object]) + + def data(key: String, value: Object): Unit + + def getStatus: ExecutionNodeStatus + + def setStatus(taskStatus: ExecutionNodeStatus): Unit + + + def getLables: Array[Label[_]] + + def setLabels(labels: Array[Label[_]]): Unit + + def getCallbackServiceInstance(): ServiceInstance + + def setCallbackServiceInstance(serviceInstance: ServiceInstance): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala new file mode 100644 index 0000000000..dd150e5fe0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity + + +object TaskStatus extends Enumeration { + + type TaskStatus = Value + val PENDING = Value(0) + val RUNNING = Value(1) + val SUCCESS = Value(2) + val ERROR = Value(3) + val CANCEL = Value(4) + + def isCompleted(status: TaskStatus): Boolean = { + if (status == PENDING || status == RUNNING) false + else true + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala new file mode 100644 index 0000000000..32b23d104c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala @@ -0,0 +1,84 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.common.execution.EngineExecution +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, ResourceExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper + + +class ComputationEngineConnExecution extends EngineExecution with Logging { + + private val executorManager: ExecutorManager = ExecutorManager.getInstance() + + /** + * 创建出默认的Executor + * + * @param engineCreationContext + * @param engineConn + */ + override def execute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + Utils.tryCatch{ + init(engineCreationContext) + val defaultExecutor = executorManager.getDefaultExecutor.asInstanceOf[ComputationExecutor] + reportUsedResource(defaultExecutor, engineCreationContext) + reportLabel(defaultExecutor.getExecutorLabels()) + info(s"Engine Executor ${defaultExecutor.getId()} started.") + info("Debug: engineCreationContext: " + BDPJettyServerHelper.gson.toJson(engineCreationContext)) + }{ + t => + error(s"Init executor error. ", t) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INIT_EXECUTOR_FAILED, "Init executor failed. ", t) + } + } + + private def init(engineCreationContext: EngineCreationContext): Unit = { + // msContext.getPublisher.publish(RequestTaskExecute) + val listenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext + listenerBusContext.getEngineConnAsyncListenerBus.start() + } + + private def reportUsedResource(executor: Executor, engineCreationContext: EngineCreationContext): Unit = { + Utils.tryCatch( + executor match { + case resourceExecutor: ResourceExecutor => + ManagerService.getManagerService.reportUsedResource(ResourceUsedProtocol(Sender.getThisServiceInstance, resourceExecutor.getCurrentNodeResource(), engineCreationContext.getTicketId)) + case _ => + info("do not to report usedResource") + } + ) { + t => error("ReportUsedResource error. cause: " + t.getCause) + } + } + + private def reportLabel(labels: util.List[Label[_]]): Unit = { + ManagerService.getManagerService.labelReport(labels) + info("Reported label to am.") + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala new file mode 100644 index 0000000000..c10fcf5f7b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala @@ -0,0 +1,271 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.util.concurrent.TimeUnit + +import com.google.common.cache.{Cache, CacheBuilder} +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.common.conf.{EngineConnConf, EngineConnConstant} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.EngineConnTask +import com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationExecutorHook +import com.webank.wedatasphere.linkis.engineconn.computation.executor.parser.CodeParser +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{LabelExecutor, ResourceExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{EngineConcurrentInfo, RequestTask} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.ExecutorFactory +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.scheduler.executer._ +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.exception.ExceptionUtils + + +abstract class ComputationExecutor(val outputPrintLimit: Int = 1000) extends AccessibleExecutor with ResourceExecutor with LabelExecutor with Logging { + + private val listenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext + + // private val taskMap: util.Map[String, EngineConnTask] = new ConcurrentHashMap[String, EngineConnTask](8) + private val taskCache: Cache[String, EngineConnTask] = CacheBuilder.newBuilder().expireAfterAccess(EngineConnConf.ENGINE_TASK_EXPIRE_TIME.getValue, TimeUnit.MILLISECONDS) + .maximumSize(EngineConnConstant.MAX_TASK_NUM).build() + + private var engineInitialized: Boolean = false + + private var codeParser: Option[CodeParser] = None + + private var runningTasks: Int = 0 + + private var pendingTasks: Int = 0 + + private var succeedTasks: Int = 0 + + private var failedTasks: Int = 0 + + private var lastTask: EngineConnTask = null + + final override def tryReady: Boolean = { + transition(NodeStatus.Unlock) + if (!engineInitialized) { + engineInitialized = true + } + true + } + + + override def init: Unit = { + info(s"executor($getId()) is ready ") + tryReady + } + + def tryShutdown(): Boolean = { + this.ensureAvailable(transition(NodeStatus.ShuttingDown)) + close() + true + } + + def tryFailed(): Boolean = { + this.whenStatus(NodeStatus.ShuttingDown, transition(NodeStatus.Failed)) + true + } + + + def getSucceedNum = succeedTasks + + def getFailedNum = failedTasks + + def getRunningTask: Int = runningTasks + + private def getExecutorConcurrentInfo: EngineConcurrentInfo = EngineConcurrentInfo(runningTasks, pendingTasks, succeedTasks, failedTasks) + + def isEngineInitialized = engineInitialized + + protected def callback(): Unit = {} + + override def close(): Unit = { + if (null != lastTask) synchronized { + killTask(lastTask.getTaskId) + } else { + killTask("By close") + } + super.close() + } + + // override def getName: String = ComputationExecutorConf.DEFAULT_COMPUTATION_NAME + + protected def ensureOp[A](f: => A): A = if (!this.engineInitialized) + f + else ensureIdle(f) + + def execute(engineConnTask: EngineConnTask): ExecuteResponse = { + + runningTasks += 1 + + taskCache.put(engineConnTask.getTaskId, engineConnTask) + lastTask = engineConnTask + + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Running) + + ensureOp { + val engineExecutionContext = createEngineExecutionContext(engineConnTask) + var hookedCode = engineConnTask.getCode + Utils.tryCatch { + val engineCreationContext = EngineConnManager.getEngineConnManager.getEngineConn().getEngineCreationContext + ComputationExecutorHook.getComputationExecutorHooks.foreach(hook => { + hookedCode = hook.beforeExecutorExecute(engineExecutionContext, engineCreationContext, hookedCode) + }) + } { + case e: Throwable => logger.info("failed to do with hook", e) + } + if (hookedCode.length > 100) { + info(s"hooked after code: ${hookedCode.substring(0, 100)} ....") + } else { + info(s"hooked after code: $hookedCode ") + } + val localPath = System.getenv(EngineConnConf.ENGINE_CONN_LOCAL_LOG_DIRS_KEY.getValue) + engineExecutionContext.appendStdout(s"EngineConn local log path : ${DataWorkCloudApplication.getServiceInstance.toString} ${localPath}") + var response: ExecuteResponse = null + val incomplete = new StringBuilder + val codes = Utils.tryCatch(getCodeParser().map(_.parse(hookedCode, engineExecutionContext)).getOrElse(Array(hookedCode))) { e => + info("Your code will be submitted in overall mode") + Array(hookedCode) + } + engineExecutionContext.setTotalParagraph(codes.length) + codes.indices.foreach({ + index => + if (ExecutionNodeStatus.Cancelled == engineConnTask.getStatus) return ErrorExecuteResponse("Job is killed by user!", null) + val code = codes(index) + engineExecutionContext.setCurrentParagraph(index + 1) + response = Utils.tryCatch(if (incomplete.nonEmpty) executeCompletely(engineExecutionContext, code, incomplete.toString()) + else executeLine(engineExecutionContext, code) + ) { + t => ErrorExecuteResponse(ExceptionUtils.getRootCauseMessage(t), t) + } + info(s"Finished to execute task ${engineConnTask.getTaskId}") + incomplete ++= code + response match { + case e: ErrorExecuteResponse => + failedTasks += 1 + error("execute code failed!", e.t) + return response + case SuccessExecuteResponse() => + engineExecutionContext.appendStdout("\n") + incomplete.setLength(0) + case e: OutputExecuteResponse => + incomplete.setLength(0) + val output = if (StringUtils.isNotEmpty(e.getOutput) && e.getOutput.length > outputPrintLimit) + e.getOutput.substring(0, outputPrintLimit) else e.getOutput + engineExecutionContext.appendStdout(output) + if (StringUtils.isNotBlank(e.getOutput)) engineExecutionContext.sendResultSet(e) + case _: IncompleteExecuteResponse => + incomplete ++= incompleteSplitter + } + }) + Utils.tryCatch(engineExecutionContext.close()) { + t => + response = ErrorExecuteResponse("send resultSet to entrance failed!", t) + failedTasks += 1 + } + runningTasks -= 1 + lastTask = null + response match { + case _: OutputExecuteResponse => + succeedTasks += 1 + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Succeed) + SuccessExecuteResponse() + case s: SuccessExecuteResponse => + succeedTasks += 1 + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Succeed) + s + case _ => response + } + } + + + } + + def setCodeParser(codeParser: CodeParser) = this.codeParser = Some(codeParser) + + def getCodeParser(): Option[CodeParser] = this.codeParser + + def executeLine(engineExecutorContext: EngineExecutionContext, code: String): ExecuteResponse + + protected def incompleteSplitter = "\n" + + def executeCompletely(engineExecutorContext: EngineExecutionContext, code: String, completedLine: String): ExecuteResponse + + def progress(): Float + + def getProgressInfo: Array[JobProgressInfo] + + protected def createEngineExecutionContext(engineConnTask: EngineConnTask): EngineExecutionContext = { + val userCreator = ExecutorFactory.parseUserWithCreator(engineConnTask.getLables) + + val engineExecutionContext = if (null != userCreator && StringUtils.isNotBlank(userCreator.user)) { + new EngineExecutionContext(this, userCreator.user) + } else { + new EngineExecutionContext(this) + } + if (engineConnTask.getProperties.containsKey(RequestTask.RESULT_SET_STORE_PATH)) { + engineExecutionContext.setStorePath(engineConnTask.getProperties.get(RequestTask.RESULT_SET_STORE_PATH).toString) + } + engineExecutionContext.setJobId(engineConnTask.getTaskId) + engineExecutionContext.getProperties.putAll(engineConnTask.getProperties) + engineExecutionContext.setLabels(engineConnTask.getLables) + engineExecutionContext + } + + def killTask(taskId: String): Unit = { + Utils.tryAndWarn { + val task = taskCache.getIfPresent(taskId) + task.setStatus(ExecutionNodeStatus.Cancelled) + if (null != task) { + transformTaskStatus(task, ExecutionNodeStatus.Cancelled) + } + } + } + + def transformTaskStatus(task: EngineConnTask, newStatus: ExecutionNodeStatus) = { + val oriStatus = task.getStatus + oriStatus match { + case ExecutionNodeStatus.Scheduled => + if (task.getStatus != newStatus) { + task.setStatus(newStatus) + } + case ExecutionNodeStatus.Running => + if (newStatus == ExecutionNodeStatus.Succeed || newStatus == ExecutionNodeStatus.Failed || newStatus == ExecutionNodeStatus.Cancelled) { + task.setStatus(newStatus) + } else { + error(s"Task status change error. task: ${task}, newStatus : ${newStatus}") + } + case _ => + error(s"Task status change error. task: ${task}, newStatus : ${newStatus}") + } + if (oriStatus != newStatus) { + listenerBusContext.getEngineConnSyncListenerBus.postToAll(TaskStatusChangedEvent(task.getTaskId, oriStatus, newStatus)) + } + } + + def getTaskById(taskId: String): EngineConnTask = { + taskCache.getIfPresent(taskId) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala new file mode 100644 index 0000000000..c8bfe2c597 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.EngineConnTask +import com.webank.wedatasphere.linkis.engineconn.executor.entity.ConcurrentExecutor +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteResponse + + +abstract class ConcurrentComputationExecutor(override val outputPrintLimit: Int = 1000) extends ComputationExecutor(outputPrintLimit) with ConcurrentExecutor { + + override def execute(engineConnTask: EngineConnTask): ExecuteResponse = { + if (getRunningTask >= getConcurrentLimit) synchronized { + if (getRunningTask >= getConcurrentLimit) { + info(s"running task($getRunningTask) > concurrent limit $getConcurrentLimit, now to mark engine to busy ") + transition(NodeStatus.Busy) + } + } + val response = super.execute(engineConnTask) + if (getStatus == NodeStatus.Busy && getConcurrentLimit > getRunningTask) synchronized { + if (getStatus == NodeStatus.Busy && getConcurrentLimit > getRunningTask) { + info(s"running task($getRunningTask) < concurrent limit $getConcurrentLimit, now to mark engine to Unlock ") + transition(NodeStatus.Unlock) + } + } + response + } + + protected override def ensureOp[A](f: => A): A = if (!isEngineInitialized) + f + else ensureIdle(f, false) +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala new file mode 100644 index 0000000000..5e268f682b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala @@ -0,0 +1,217 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.io.File +import java.util +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.io.resultset.{ResultSet, ResultSetWriter} +import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.cs.client.utils.ContextServiceUtils +import com.webank.wedatasphere.linkis.cs.storage.CSTableResultSetWriter +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{TaskLogUpdateEvent, TaskProgressUpdateEvent, TaskResultCreateEvent, TaskResultSizeCreatedEvent} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.conf.ComputationExecutorConf +import com.webank.wedatasphere.linkis.engineconn.executor.listener.{EngineConnAsyncListenerBus, EngineConnSyncListenerBus, ExecutorListenerBusContext} +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.EngineConnExecutorErrorException +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.scheduler.executer.{AliasOutputExecuteResponse, OutputExecuteResponse} +import com.webank.wedatasphere.linkis.storage.resultset.table.TableResultSet +import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetWriter} +import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.time.DateFormatUtils + +import scala.collection.mutable.ArrayBuffer + + +class EngineExecutionContext(executor: ComputationExecutor, executorUser: String = Utils.getJvmUser) extends Logging { + + private val resultSetFactory = ResultSetFactory.getInstance + + private val resultSetWriters = ArrayBuffer[ResultSetWriter[_ <: MetaData, _ <: Record]]() + + private var defaultResultSetWriter: ResultSetWriter[_ <: MetaData, _ <: Record] = _ + + private var resultSize = 0 + + private var interrupted = false + + private var jobId: Option[String] = None + private val aliasNum = new AtomicInteger(0) + protected var storePath: Option[String] = None + + private val properties: java.util.Map[String, Object] = new util.HashMap[String, Object]() + + private var labels: Array[Label[_]] = new Array[Label[_]](0) + + private var totalParagraph = 0 + private var currentParagraph = 0 + + def kill(): Unit = interrupted = true + + def isKilled: Boolean = interrupted + + def getTotalParagraph: Int = totalParagraph + + def setTotalParagraph(totalParagraph: Int): Unit = this.totalParagraph = totalParagraph + + def getCurrentParagraph: Int = currentParagraph + + def setCurrentParagraph(currentParagraph: Int): Unit = this.currentParagraph = currentParagraph + + def pushProgress(progress: Float, progressInfo: Array[JobProgressInfo]): Unit = { + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + listenerBus.postToAll(TaskProgressUpdateEvent(jId, progress, progressInfo)) + }) + } + + def sendResultSet(resultSetWriter: ResultSetWriter[_ <: MetaData, _ <: Record]): Unit = { + info("Start to send res to entrance") + val fileName = new File(resultSetWriter.toFSPath.getPath).getName + val index = if (fileName.indexOf(".") < 0) fileName.length else fileName.indexOf(".") + val alias = if (fileName.startsWith("_")) fileName.substring(1, index) else fileName.substring(0, fileName.indexOf("_")) + Utils.tryFinally(sendResultSet(resultSetWriter.toString(), alias)) { + IOUtils.closeQuietly(resultSetWriter) + resultSetWriters synchronized resultSetWriters -= resultSetWriter + } + } + + def sendResultSet(output: String): Unit = sendResultSet(output, "_" + aliasNum.getAndIncrement()) + + def appendTextResultSet(output: String): Unit = { + if (defaultResultSetWriter == null) aliasNum synchronized { + if (defaultResultSetWriter == null) { + defaultResultSetWriter = createDefaultResultSetWriter(ResultSetFactory.TEXT_TYPE) + defaultResultSetWriter.addMetaData(new LineMetaData()) + resultSetWriters += defaultResultSetWriter + } + } + defaultResultSetWriter.addRecord(new LineRecord(output)) + } + + private def sendResultSet(output: String, alias: String): Unit = { + if (StringUtils.isEmpty(output)) return + if (resultSetFactory.isResultSetPath(output) || resultSetFactory.isResultSet(output)) { + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + //TODO peacewong executor.getEngineServerContext().getEngineAsyncListenerBus().post(ResultSetCreatedEvent(jId, output, alias)) + listenerBus.postToAll(TaskResultCreateEvent(jId, output, alias)) + resultSize += 1 + }) + } else throw new EngineConnExecutorErrorException(50050, "unknown resultSet: " + output) + } + + def setJobId(jobId: String) = this.jobId = Option(jobId) + + def getJobId = jobId + + def setStorePath(storePath: String) = this.storePath = Option(storePath) + + def getLables: Array[Label[_]] = labels + + def setLabels(labels: Array[Label[_]]): Unit = this.labels = labels + + def sendResultSet(outputExecuteResponse: OutputExecuteResponse): Unit = outputExecuteResponse match { + case AliasOutputExecuteResponse(alias, output) => sendResultSet(output, alias) + case output: OutputExecuteResponse => sendResultSet(output.getOutput, "_" + aliasNum.getAndIncrement()) + } + + def getProperties: java.util.Map[String, Object] = properties + + def addProperty(key: String, value: String): Unit = properties.put(key, value) + + protected def getDefaultStorePath: String = { + val path = ComputationExecutorConf.ENGINECONN_RESULT_SET_STORE_PATH.getValue + (if (path.endsWith("/")) path else path + "/") + Utils.getJvmUser + "/" + + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + "/" + getJobId.get + "/" + System.nanoTime + } + + def createDefaultResultSetWriter(): ResultSetWriter[_ <: MetaData, _ <: Record] = { + // createResultSetWriter(resultSetFactory.getResultSetByType(engine.getDefaultResultSetType)) + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetFactory.getResultSetType(0))) // todo check + } + + def createDefaultResultSetWriter(alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetFactory.getResultSetType(0)), alias) // todo check + + def createResultSetWriter(resultSetType: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetType), null) + + def createResultSetWriter(resultSet: ResultSet[_ <: MetaData, _ <: Record]): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSet, null) + + def createResultSetWriter(resultSetType: String, alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetType), alias) + + def createResultSetWriter(resultSet: ResultSet[_ <: MetaData, _ <: Record], alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = { + val filePath = storePath.getOrElse(getDefaultStorePath) + val fileName = if (StringUtils.isEmpty(alias)) "_" + aliasNum.getAndIncrement() else alias + "_" + aliasNum.getAndIncrement() + val resultSetPath = resultSet.getResultSetPath(new FsPath(filePath), fileName) + //update by peaceWong 20200402 + val resultSetWriter = resultSet match { + case result: TableResultSet => + val contextIDStr = ContextServiceUtils.getContextIDStrByMap(getProperties) + val nodeName = ContextServiceUtils.getNodeNameStrByMap(getProperties) + if (StringUtils.isNotBlank(contextIDStr) && StringUtils.isNotBlank(nodeName)) { + val csWriter = new CSTableResultSetWriter(result, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, contextIDStr, nodeName, alias) + csWriter.setProxyUser(executorUser) + csWriter + } else { + ResultSetWriter.getResultSetWriter(resultSet, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, executorUser) + } + case _ => ResultSetWriter.getResultSetWriter(resultSet, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, executorUser) + } + //update by peaceWong 20200402 end + resultSetWriters synchronized resultSetWriters += resultSetWriter + resultSetWriter + } + + def appendStdout(log: String): Unit = if (!executor.isEngineInitialized) { + executor.info(log) + } else { + val listenerBus = getEngineSyncListenerBus + // jobId.foreach(jId => listenerBus.post(TaskLogUpdateEvent(jId, log))) + jobId.foreach(jId => listenerBus.postToAll(TaskLogUpdateEvent(jId, log))) + } + + def sendProgress(progress: Float, progressInfos: Array[JobProgressInfo]): Unit = { + if (executor.isEngineInitialized) { + val listenerBus = getEngineSyncListenerBus + // jobId.foreach(jId => listenerBus.post(TaskProgressUpdateEvent(jId, progress, progressInfos))) + jobId.foreach(jId => listenerBus.postToAll(TaskProgressUpdateEvent(jId, progress, progressInfos))) + } + } + + def close(): Unit = { + resultSetWriters.toArray.foreach(sendResultSet) + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + listenerBus.postToAll(TaskResultSizeCreatedEvent(jId, resultSize)) + }) + resultSetWriters.clear() + } + + private def getEngineAsyncListenerBus: EngineConnAsyncListenerBus = { + ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + } + + private def getEngineSyncListenerBus: EngineConnSyncListenerBus = { + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnSyncListenerBus + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala new file mode 100644 index 0000000000..6c594899e6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.hook + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.conf.DWCArgumentsParser +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.callback.service.{EngineConnAfterStartCallback, EngineConnPidCallback} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.common.hook.EngineConnHook +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallback +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.exception.ExceptionUtils + + +class ComputationEngineConnHook extends EngineConnHook with Logging { + + override def beforeCreateEngineConn(engineCreationContext: EngineCreationContext): Unit = { + info("<----------Start Spring app---------->") + val parser = DWCArgumentsParser.parse(engineCreationContext.getArgs) + DWCArgumentsParser.setDWCOptionMap(parser.getDWCConfMap) + val existsExcludePackages = ServerConfiguration.BDP_SERVER_EXCLUDE_PACKAGES.getValue + if (!StringUtils.isEmpty(existsExcludePackages)) + DataWorkCloudApplication.setProperty(ServerConfiguration.BDP_SERVER_EXCLUDE_PACKAGES.key, existsExcludePackages) + // 加载spring类 + DataWorkCloudApplication.main(DWCArgumentsParser.formatSpringOptions(parser.getSpringConfMap)) + + val engineConnPidCallBack = new EngineConnPidCallback(engineCreationContext.getEMInstance) + Utils.tryAndError(engineConnPidCallBack.callback()) + info("<----------Spring app init success---------->") + } + + + override def beforeExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = {} + + override def afterExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = {} + + override def afterEngineServerStartFailed(engineCreationContext: EngineCreationContext, throwable: Throwable): Unit = { + + val engineConnAfterStartCallback = new EngineConnAfterStartCallback(engineCreationContext.getEMInstance) + engineConnAfterStartCallback.callback(EngineConnStatusCallback(Sender.getThisServiceInstance, + engineCreationContext.getTicketId, NodeStatus.ShuttingDown, ExceptionUtils.getRootCauseMessage(throwable))) + error("init engineConn failed! now exit", throwable) + ShutdownHook.getShutdownHook.notifyError(throwable) + } + + override def afterEngineServerStartSuccess(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + val engineConnAfterStartCallback = new EngineConnAfterStartCallback(engineCreationContext.getEMInstance) + engineConnAfterStartCallback.callback(EngineConnStatusCallback(Sender.getThisServiceInstance, + engineCreationContext.getTicketId, NodeStatus.Unlock, "success")) + warn("init engineConn success!") + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala new file mode 100644 index 0000000000..90a47ceffd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.hook + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.ExecutorFactory +import org.reflections.Reflections + +import scala.collection.JavaConverters.asScalaSetConverter +import scala.collection.mutable.ArrayBuffer + + +trait ComputationExecutorHook { + + def getHookName(): String + + def beforeExecutorExecute(engineExecutionContext: EngineExecutionContext, engineCreationContext: EngineCreationContext, codeBeforeHook: String): String = codeBeforeHook + +// def afterExecutorExecute(engineExecutionContext: EngineExecutionContext, code: String): Unit +} + +object ComputationExecutorHook extends Logging { + + private lazy val computationExecutorHooks: Array[ComputationExecutorHook] = initComputationExecutorHook + + private def initComputationExecutorHook: Array[ComputationExecutorHook] = { + val hooks = new ArrayBuffer[ComputationExecutorHook] + Utils.tryCatch { + val reflections = new Reflections("com.webank.wedatasphere.linkis.engineconn.computation", classOf[ComputationExecutorHook]) + val allSubClass = reflections.getSubTypesOf(classOf[ComputationExecutorHook]) + allSubClass.asScala.foreach(l => { + hooks += l.newInstance + }) + } { + t: Throwable => + error(t.getMessage) + } + hooks.toArray + } + + def getComputationExecutorHooks = computationExecutorHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala new file mode 100644 index 0000000000..8bce49bf30 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{TaskResultCreateEvent, TaskResultSizeCreatedEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait ResultSetListener extends EngineConnSyncListener { + + def onResultSetCreated(taskResultCreateEvent: TaskResultCreateEvent): Unit + + def onResultSizeCreated(taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala new file mode 100644 index 0000000000..4c34719fb6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskProgressUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait TaskProgressListener extends EngineConnSyncListener { + + def onProgressUpdate(taskProgressUpdateEvent: TaskProgressUpdateEvent) + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala new file mode 100644 index 0000000000..a2db53e4df --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait TaskStatusListener extends EngineConnSyncListener { + + def onTaskStatusChanged(taskStatusChangedEvent: TaskStatusChangedEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala new file mode 100644 index 0000000000..2f9af2483f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala @@ -0,0 +1,235 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.parser + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.computation.executor.conf.ComputationExecutorConf +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.parser.CodeType.CodeType +import org.apache.commons.lang.StringUtils +import org.slf4j.{Logger, LoggerFactory} + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + + +trait CodeParser { + + def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] + +} + +abstract class SingleCodeParser extends CodeParser { + val codeType: CodeType + + def canParse(codeType: String): Boolean = { + CodeType.getType(codeType) == this.codeType + } +} + +abstract class CombinedEngineCodeParser extends CodeParser { + val parsers: Array[SingleCodeParser] + + def getCodeType(code: String, engineExecutorContext: EngineExecutionContext): String + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + val codeType = getCodeType(code, engineExecutorContext) + parsers.find(_.canParse(codeType)) match { + case Some(parser) => parser.parse(code, engineExecutorContext) + case None => Array(code) + } + } +} + +class ScalaCodeParser extends SingleCodeParser with Logging { + + override val codeType: CodeType = CodeType.Scala + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val codeBuffer = new ArrayBuffer[String]() + val statementBuffer = new ArrayBuffer[String]() + code.split("\n").foreach { + case "" => + case l if l.startsWith(" ") || l.startsWith("\t") => if (!l.trim.startsWith("//")) statementBuffer.append(l) + case l if l.startsWith("@") => statementBuffer.append(l) + case l if StringUtils.isNotBlank(l) => + if (l.trim.startsWith("}")) { + statementBuffer.append(l) + } else { + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + statementBuffer.clear() + //statementBuffer.append("%scala") + statementBuffer.append(l) + } + case _ => + } + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + codeBuffer.toArray + } +} + +class PythonCodeParser extends SingleCodeParser { + + override val codeType: CodeType = CodeType.Python + val openBrackets = Array("{", "(", "[") + val closeBrackets = Array("}", ")", "]") + val LOG: Logger = LoggerFactory.getLogger(getClass) + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val bracketStack = new mutable.Stack[String] + val codeBuffer = new ArrayBuffer[String]() + val statementBuffer = new ArrayBuffer[String]() + var notDoc = true + //quotationMarks is used to optimize the three quotes problem(quotationMarks用来优化三引号问题) + var quotationMarks: Boolean = false + code.split("\n").foreach { + case "" => + case l if l.trim.contains("\"\"\"") || l.trim.contains("""'''""") => quotationMarks = !quotationMarks + statementBuffer.append(l) + recordBrackets(bracketStack, l) + case l if quotationMarks => statementBuffer.append(l) + //shanhuang 用于修复python的引号问题 + //recordBrackets(bracketStack, l) + case l if notDoc && l.startsWith("#") => + case l if StringUtils.isNotBlank(statementBuffer.last) && statementBuffer.last.endsWith("""\""") => + statementBuffer.append(l) + case l if notDoc && l.startsWith(" ") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("\t") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("@") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("else") => //LOG.info("I am else") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("elif") => //LOG.info("I am elif") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && StringUtils.isNotBlank(l) => + if (statementBuffer.nonEmpty && bracketStack.isEmpty) { + codeBuffer.append(statementBuffer.mkString("\n")) + statementBuffer.clear() + } + // statementBuffer.append("%python") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case _ => + } + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + codeBuffer.toArray + } + + def recordBrackets(bracketStack: mutable.Stack[String], l: String): Unit = { + val real = l.replace("\"\"\"", "").replace("'''", "").trim + if (StringUtils.endsWithAny(real, openBrackets)) { + for (i <- (0 to real.length - 1).reverse) { + val token = real.substring(i, i + 1) + if (openBrackets.contains(token)) { + bracketStack.push(token) + } + } + } + if (StringUtils.startsWithAny(real, closeBrackets)) { + for (i <- 0 to real.length - 1) { + val token = real.substring(i, i + 1) + if (closeBrackets.contains(token)) { + bracketStack.pop() + } + } + } + } + +} + + +object Main { + def main(args: Array[String]): Unit = { + val codeParser = new PythonCodeParser + val code = "if True: \n print 1 \nelif N=123: \n print 456 \nelse: \n print 789" + println(code) + val arrCodes = codeParser.parse(code, null) + print(arrCodes.mkString("||\n")) + } +} + +class SQLCodeParser extends SingleCodeParser { + + override val codeType: CodeType = CodeType.SQL + + val separator = ";" + + val defaultLimit: Int = ComputationExecutorConf.ENGINE_DEFAULT_LIMIT.getValue + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val codeBuffer = new ArrayBuffer[String]() + + def appendStatement(sqlStatement: String): Unit = { + codeBuffer.append(sqlStatement) + } + + if (StringUtils.contains(code, separator)) { + StringUtils.split(code, ";").foreach { + case s if StringUtils.isBlank(s) => + case s if isSelectCmdNoLimit(s) => appendStatement(s); + case s => appendStatement(s); + } + } else { + code match { + case s if StringUtils.isBlank(s) => + case s if isSelectCmdNoLimit(s) => appendStatement(s); + case s => appendStatement(s); + } + } + codeBuffer.toArray + } + + def isSelectCmdNoLimit(cmd: String): Boolean = { + var code = cmd.trim + if (!cmd.split("\\s+")(0).equalsIgnoreCase("select")) return false + if (code.contains("limit")) code = code.substring(code.lastIndexOf("limit")).trim + else if (code.contains("LIMIT")) code = code.substring(code.lastIndexOf("LIMIT")).trim.toLowerCase + else return true + val hasLimit = code.matches("limit\\s+\\d+\\s*;?") + if (hasLimit) { + if (code.indexOf(";") > 0) code = code.substring(5, code.length - 1).trim + else code = code.substring(5).trim + val limitNum = code.toInt + if (limitNum > defaultLimit) throw new IllegalArgumentException("We at most allowed to limit " + defaultLimit + ", but your SQL has been over the max rows.") + } + !hasLimit + } +} + +object CodeType extends Enumeration { + type CodeType = Value + val Python, SQL, Scala, Shell, Other = Value + + def getType(codeType: String): CodeType = codeType.toLowerCase() match { + case "python" | "pyspark" | "py" => Python + case "sql" | "hql" => SQL + case "scala" => Scala + case "shell" => Shell + case _ => Other + } +} + diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala similarity index 86% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala index ab1897422b..42d229ee9d 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala @@ -14,22 +14,19 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.rs +package com.webank.wedatasphere.linkis.engineconn.computation.executor.rs import java.io.OutputStream import com.webank.wedatasphere.linkis.common.io.resultset.ResultSetWriter import com.webank.wedatasphere.linkis.common.io.{MetaData, Record} import com.webank.wedatasphere.linkis.common.utils.Logging -import com.webank.wedatasphere.linkis.engine.execute.EngineExecutorContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext import com.webank.wedatasphere.linkis.storage.LineRecord import scala.collection.mutable.ArrayBuffer -/** - * Created by enjoyyin on 2018/11/28. - */ class RsOutputStream extends OutputStream with Logging{ private val line = ArrayBuffer[Byte]() private var isReady = false @@ -47,8 +44,8 @@ class RsOutputStream extends OutputStream with Logging{ } } - def reset(engineExecutorContext: EngineExecutorContext) = { - writer = engineExecutorContext.createDefaultResultSetWriter() + def reset(engineExecutionContext: EngineExecutionContext) = { + writer = engineExecutionContext.createDefaultResultSetWriter() writer.addMetaData(null) } diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala new file mode 100644 index 0000000000..aa45ed2a4e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.service + +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteResponse + + +trait TaskExecutionService { + + def execute(requestTask: RequestTask, smc: ServiceMethodContext): ExecuteResponse + +// def taskStatus(taskID: String): ResponseTaskStatus + + def taskProgress(taskID: String): ResponseTaskProgress + + def taskLog(taskID: String): ResponseTaskLog + + def killTask(taskID: String): Unit + + /*def pauseTask(taskID: String): Unit + + def resumeTask(taskID: String): Unit*/ + + + def dealRequestTaskStatus(requestTaskStatus: RequestTaskStatus): ResponseTaskStatus + + def dealRequestTaskPause(requestTaskPause: RequestTaskPause): Unit + + def dealRequestTaskKill(requestTaskKill: RequestTaskKill): Unit + + def dealRequestTaskResume(requestTaskResume: RequestTaskResume): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala new file mode 100644 index 0000000000..1de9a72089 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala @@ -0,0 +1,349 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.service + +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.{ExecutorService, Executors, Future, TimeUnit} + +import com.google.common.cache.{Cache, CacheBuilder} +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.LogListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event._ +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.log.LogHelper +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.LockService +import com.webank.wedatasphere.linkis.engineconn.common.conf.{EngineConnConf, EngineConnConstant} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.{CommonEngineConnTask, EngineConnTask} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.ComputationExecutor +import com.webank.wedatasphere.linkis.engineconn.computation.executor.listener.{ResultSetListener, TaskProgressListener, TaskStatusListener} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis.{ComputationEngineUtils, ComputaionEngineContant} +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{ErrorExecuteResponse, ExecuteResponse, IncompleteExecuteResponse, SubmitResponse} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import javax.annotation.PostConstruct +import org.apache.commons.lang.StringUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Component + +import scala.collection.JavaConverters._ + + +@Component +class TaskExecutionServiceImpl extends TaskExecutionService with Logging with ResultSetListener with LogListener with TaskProgressListener with TaskStatusListener { + + private val executorManager = ExecutorManager.getInstance() + private val taskExecutedNum = new AtomicInteger(0) + private var lastTask: EngineConnTask = _ + private var executorService: ExecutorService = _ + private var lastTaskFuture: Future[_] = _ + + @Autowired + private var lockService: LockService = _ + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + private val syncListenerBus = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnSyncListenerBus + private val taskIdCache: Cache[String, ComputationExecutor] = CacheBuilder.newBuilder().expireAfterAccess(EngineConnConf.ENGINE_TASK_EXPIRE_TIME.getValue, TimeUnit.MILLISECONDS) + .maximumSize(EngineConnConstant.MAX_TASK_NUM).build() + + @PostConstruct + def init(): Unit = { + LogHelper.setLogListener(this) + syncListenerBus.addListener(this) + executorService = Executors.newSingleThreadExecutor() + } + + private def sendToEntrance(task: EngineConnTask, msg: RequestProtocol): Unit = synchronized { + Utils.tryCatch { + var sender : Sender = null + if (null != task && null != task.getCallbackServiceInstance()) { + sender = Sender.getSender(task.getCallbackServiceInstance()) + sender.send(msg) + } else { + // todo + debug("SendtoEntrance error, cannot find entrance instance.") + } + }{ + t => + val errorMsg = s"SendToEntrance error. $msg" + t.getCause + error(errorMsg, t) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.SEND_TO_ENTRANCE_ERROR, errorMsg) + } + } + + @Receiver + override def execute(requestTask: RequestTask, smc: ServiceMethodContext): ExecuteResponse = { + // smc // todo get sender + // check lock + if (StringUtils.isBlank(requestTask.getLock)) { + error(s"Invalid lock : ${requestTask.getLock} , requestTask : " + BDPJettyServerHelper.gson.toJson(requestTask)) + return ErrorExecuteResponse(s"Invalid lock : ${requestTask.getLock}.", new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_PARAMS, "Invalid lock or code(请获取到锁后再提交任务.)")) + } + if (!lockService.isLockExist(requestTask.getLock)) { + error(s"Lock ${requestTask.getLock} not exist, cannot execute.") + return ErrorExecuteResponse("Lock not exixt", new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_LOCK, "Lock : " + requestTask.getLock + " not exist(您的锁无效,请重新获取后再提交).")) + } + + if (StringUtils.isBlank(requestTask.getCode)) { + return IncompleteExecuteResponse("Your code is incomplete, it may be that only comments are selected for execution(您的代码不完整,可能是仅仅选中了注释进行执行)") + } + + // 获取任务类型和任务代码,运行任务 + val taskId: Int = taskExecutedNum.incrementAndGet() + val retryAble: Boolean = { + val retry = requestTask.getProperties.getOrDefault(ComputaionEngineContant.RETRYABLE_TYPE_NAME, null) + if (null != retry) retry.asInstanceOf[Boolean] + else false + } + val task = new CommonEngineConnTask(String.valueOf(taskId), retryAble) + task.setCode(requestTask.getCode) + task.setProperties(requestTask.getProperties) + task.data(ComputaionEngineContant.LOCK_TYPE_NAME, requestTask.getLock) + task.setStatus(ExecutionNodeStatus.Scheduled) + val labels = requestTask.getLabels.asScala.toArray + task.setLabels(labels) + val entranceServerInstance = RPCUtils.getServiceInstanceFromSender(smc.getSender) + task.setCallbackServiceInstance(entranceServerInstance) + val executor = executorManager.getExecutorByLabels(labels) + executor match { + case computationExecutor: ComputationExecutor => + taskIdCache.put(task.getTaskId, computationExecutor) + submitTask(task, computationExecutor) + case o => + val msg = "Invalid compuatitionExecutor : " + ComputationEngineUtils.GSON.toJson(o) + ", labels : " + ComputationEngineUtils.GSON.toJson(labels) + ", requestTask : " + ComputationEngineUtils.GSON.toJson(requestTask) + error(msg) + ErrorExecuteResponse("Invalid computationExecutor(生成无效的计算引擎,请联系管理员).", + new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_ENGINE_TYPE, msg)) + } + + } + + +// override def taskStatus(taskID: String): ResponseTaskStatus = { +// val task = taskIdCache.get(taskID) +// ResponseTaskStatus(taskID, task.getStatus.id) +// } + + private def submitTask(task: CommonEngineConnTask, computationExecutor: ComputationExecutor) = { + val runTask = new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val response = computationExecutor.execute(task) + response match { + case ErrorExecuteResponse(message, throwable) => + sendToEntrance(task, ResponseTaskError(task.getTaskId, message)) + error(message, throwable) + computationExecutor.transformTaskStatus(task, ExecutionNodeStatus.Failed) + case _ => + } + } + } + lastTask = task + lastTaskFuture = executorService.submit(runTask) + info(s"Task ${task.getTaskId} was submited.") + SubmitResponse(task.getTaskId) + } + + override def taskProgress(taskID: String): ResponseTaskProgress = { + var response = ResponseTaskProgress(taskID, -1, null) + if (StringUtils.isBlank(taskID)) response + val executor = taskIdCache.getIfPresent(taskID) + if (null != executor) { + val task = executor.getTaskById(taskID) + if (null != task) { + if (ExecutionNodeStatus.isCompleted(task.getStatus)) { + response = ResponseTaskProgress(taskID, 1.0f, null) + } else { + response = ResponseTaskProgress(taskID, executor.progress(), executor.getProgressInfo) + } + } else { + response = ResponseTaskProgress(taskID, -1, null) + } + } else { + error(s"Executor of taskId : $taskID is not cached.") + } + response + } + + override def taskLog(taskID: String): ResponseTaskLog = { + // todo check + null + } + +// override def pauseTask(taskID: String): Unit = { +// val task = taskIdCache.get(taskID) +// // todo +// } + + override def killTask(taskID: String): Unit = { + val executor = taskIdCache.getIfPresent(taskID) + if (null != executor) { + executor.killTask(taskID) + } else { + error(s"Executor of taskId : $taskID is not cached.") + } + Utils.tryAndWarn (Thread.sleep(50)) + if (null != lastTask && lastTask.getTaskId.equalsIgnoreCase(taskID)) { + if (null != lastTaskFuture && !lastTaskFuture.isDone) { + Utils.tryAndWarn(lastTaskFuture.cancel(true)) + } + } + } + + /*override def resumeTask(taskID: String): Unit = { + // todo + }*/ + + @Receiver + override def dealRequestTaskStatus(requestTaskStatus: RequestTaskStatus): ResponseTaskStatus = { + val task = getTaskByTaskId(requestTaskStatus.execId) + if (null != task) { + ResponseTaskStatus(task.getTaskId, task.getStatus) + } else { + val msg = "Task null! requestTaskStatus: " + ComputationEngineUtils.GSON.toJson(requestTaskStatus) + error(msg) + ResponseTaskStatus(requestTaskStatus.execId, ExecutionNodeStatus.Cancelled) + } + } + + @Receiver + override def dealRequestTaskPause(requestTaskPause: RequestTaskPause): Unit = { + info(s"Pause is Not supported for task : " + requestTaskPause.execId ) + } + + @Receiver + override def dealRequestTaskKill(requestTaskKill: RequestTaskKill): Unit = { + val executor = taskIdCache.getIfPresent(requestTaskKill.execId) + if (null != executor) { + executor.killTask(requestTaskKill.execId) + info(s"TaskId : ${requestTaskKill.execId} was killed by user.") + } else { + error(s"Invalid executor : null for taskId : ${requestTaskKill.execId}") + } + } + + @Receiver + override def dealRequestTaskResume(requestTaskResume: RequestTaskResume): Unit = { + info(s"Resume is Not support for task : " + requestTaskResume.execId ) + } + + override def onEvent(event: EngineConnSyncEvent): Unit = event match { + case taskStatusChangedEvent: TaskStatusChangedEvent => onTaskStatusChanged(taskStatusChangedEvent) + case taskProgressUpdateEvent: TaskProgressUpdateEvent => onProgressUpdate(taskProgressUpdateEvent) + case logUpdateEvent: TaskLogUpdateEvent => onLogUpdate(logUpdateEvent) + case taskResultCreateEvent: TaskResultCreateEvent => onResultSetCreated(taskResultCreateEvent) + case taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent => onResultSizeCreated(taskResultSizeCreatedEvent) + case _ => + warn("Unknown event : " + BDPJettyServerHelper.gson.toJson(event)) + } + + override def onLogUpdate(logUpdateEvent: TaskLogUpdateEvent): Unit = { + if (EngineConnConf.ENGINE_PUSH_LOG_TO_ENTRANCE.getValue) { + if (null != logUpdateEvent && StringUtils.isNotBlank(logUpdateEvent.taskId)) { + val task = getTaskByTaskId(logUpdateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskLog(logUpdateEvent.taskId, logUpdateEvent.log)) + } else { + error("Task cannot null! logupdateEvent: " + ComputationEngineUtils.GSON.toJson(logUpdateEvent)) + } + } else { + val executor = ExecutorManager.getInstance().getDefaultExecutor + executor match { + case computationExecutor: ComputationExecutor => + sendToEntrance(lastTask, ResponseTaskLog(lastTask.getTaskId, logUpdateEvent.log)) + case _ => + error("OnLogUpdate error. Invalid ComputationExecutor : " + ComputationEngineUtils.GSON.toJson(executor)) + } + } + + } + } + + override def onTaskStatusChanged(taskStatusChangedEvent: TaskStatusChangedEvent): Unit = { + val task = getTaskByTaskId(taskStatusChangedEvent.taskId) + if (null != task) { + if (ExecutionNodeStatus.isCompleted(taskStatusChangedEvent.toStatus)) { + lastTask = task + LogHelper.pushAllRemainLogs() + } + sendToEntrance(task, ResponseTaskStatus(taskStatusChangedEvent.taskId, taskStatusChangedEvent.toStatus)) + } else { + error("Task cannot null! taskStatusChangedEvent: " + ComputationEngineUtils.GSON.toJson(taskStatusChangedEvent)) + } + } + + override def onProgressUpdate(taskProgressUpdateEvent: TaskProgressUpdateEvent): Unit = { + if (EngineConnConf.ENGINE_PUSH_LOG_TO_ENTRANCE.getValue) { + val task = getTaskByTaskId(taskProgressUpdateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskProgress(taskProgressUpdateEvent.taskId, taskProgressUpdateEvent.progress, taskProgressUpdateEvent.progressInfo)) + } else { + error("Task cannot null! taskProgressUpdateEvent : " + ComputationEngineUtils.GSON.toJson(taskProgressUpdateEvent)) + } + } + } + + override def onResultSetCreated(taskResultCreateEvent: TaskResultCreateEvent): Unit = { + info(s"start to deal result event ${taskResultCreateEvent.taskId}") + val task = getTaskByTaskId(taskResultCreateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskResultSet( + taskResultCreateEvent.taskId, + taskResultCreateEvent.resStr, + taskResultCreateEvent.alias + )) + } else { + error("Task cannot null! taskResultCreateEvent: " + ComputationEngineUtils.GSON.toJson(taskResultCreateEvent)) + } + info(s"Finished to deal result event ${taskResultCreateEvent.taskId}") + } + + def getTaskByTaskId(taskId: String): EngineConnTask = { + if (StringUtils.isBlank(taskId)) return null + val executor = taskIdCache.getIfPresent(taskId) + if (null != executor) { + executor.getTaskById(taskId) + } else { + error(s"Executor of taskId : $taskId is not cached.") + null + } + } + + override def onResultSizeCreated(taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent): Unit = { + val task = getTaskByTaskId(taskResultSizeCreatedEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskResultSize( + taskResultSizeCreatedEvent.taskId, + taskResultSizeCreatedEvent.resultSize + )) + } else { + error("Task cannot null! taskResultSizeCreatedEvent: " + ComputationEngineUtils.GSON.toJson(taskResultSizeCreatedEvent)) + } + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala new file mode 100644 index 0000000000..40eefeff1d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis + + +object ComputaionEngineContant { + + def RETRYABLE_TYPE_NAME = "taskRetryable" + + def LOCK_TYPE_NAME = "lock" +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala new file mode 100644 index 0000000000..049bca958b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis + +import com.google.gson.{Gson, GsonBuilder} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper + + +object ComputationEngineUtils { + + def GSON: Gson = BDPJettyServerHelper.gson + + def GSON_PRETTY: Gson = new GsonBuilder().setPrettyPrinting().create() + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml new file mode 100644 index 0000000000..1b707e875c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml @@ -0,0 +1,91 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-common + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-label-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala new file mode 100644 index 0000000000..52dc90ed39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala @@ -0,0 +1,45 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.conf + +import com.webank.wedatasphere.linkis.common.conf.CommonVars + + +object EngineConnConf { + + val ENGINE_EXECUTIONS = CommonVars("wds.linkis.engine.connector.executions", "com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.ComputationEngineConnExecution") + + val ENGINE_CONN_HOOKS = CommonVars("wds.linkis.engine.connector.hooks", "com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationEngineConnHook") + + + val ENGINE_LAUNCH_CMD_PARAMS_USER_KEY = CommonVars("wds.linkis.engine.launch.cmd.params.user.key", "user") + + val ENGINE_SUPPORT_PARALLELISM = CommonVars("wds.linkis.engine.parallelism.support.enabled", false) + + val ENGINE_PUSH_LOG_TO_ENTRANCE = CommonVars("wds.linkis.engine.push.log.enable", true) + + val ENGINECONN_PLUGIN_CLAZZ = CommonVars("wds.linkis.engineconn.plugin.default.clazz", "com.webank.wedatasphere.linkis.engineplugin.hive.HiveEngineConnPlugin") + + + val ENGINE_TASK_EXPIRE_TIME = CommonVars("wds.linkis.engine.task.expire.time", 1000 * 3600 * 24) + + val ENGINE_LOCK_REFRESH_TIME = CommonVars("wds.linkis.engine.lock.refresh.time", 1000 * 60 * 3) + + val ENGINE_CONN_LOCALPATH_PWD_KEY = CommonVars("wds.linkis.engine.localpath.pwd.key", "PWD") + + val ENGINE_CONN_LOCAL_LOG_DIRS_KEY = CommonVars("wds.linkis.engine.logs.dir.key", "LOG_DIRS") +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala new file mode 100644 index 0000000000..b5f7d6a8fb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.conf + + +object EngineConnConstant { + + val MAX_TASK_NUM = 10000 + + val SPRING_CONF_MAP_NAME = "SpringConfMap" + + val MAX_EXECUTOR_ID_NAME = "MaxExecutorId" +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala new file mode 100644 index 0000000000..281a3de469 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala @@ -0,0 +1,103 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.creation + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineCreationContext { + + def getUser: String + + def setUser(user: String): Unit + + def getTicketId: String + + def setTicketId(ticketId: String): Unit + + def getLabels(): util.List[Label[_]] + + def setLabels(labels: util.List[Label[_]]): Unit + + def getEMInstance: ServiceInstance + + def setEMInstance(instance: ServiceInstance): Unit + + def getOptions: util.Map[String, String] + + def setOptions(options: util.Map[String, String]) + + def getExecutorId: Int + + def setExecutorId(id: Int) + + def setArgs(args: Array[String]) + + def getArgs: Array[String] +} + +class DefaultEngineCreationContext extends EngineCreationContext { + + private var user: String = _ + + private var ticketId: String = _ + + private var labels: util.List[Label[_]] = _ + + private var options: util.Map[String, String] = _ + + private var emInstance: ServiceInstance = _ + + private var executorId: Int = 0 + + private var args: Array[String] = null + + override def getTicketId: String = this.ticketId + + override def setTicketId(ticketId: String): Unit = this.ticketId = ticketId + + override def getLabels(): util.List[Label[_]] = this.labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels + + override def getEMInstance: ServiceInstance = this.emInstance + + override def setEMInstance(instance: ServiceInstance): Unit = this.emInstance = instance + + override def getOptions: util.Map[String, String] = this.options + + override def setOptions(options: util.Map[String, String]): Unit = this.options = options + + override def getUser: String = user + + override def setUser(user: String): Unit = this.user = user + + override def getExecutorId: Int = executorId + + override def setExecutorId(id: Int): Unit = executorId = id + + override def setArgs(args: Array[String]): Unit = this.args = args + + override def getArgs: Array[String] = args + + + override def toString = s"DefaultEngineCreationContext(user-$user, ticketID-$ticketId, emInstance-$emInstance)" +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala new file mode 100644 index 0000000000..c97339e101 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.engineconn + +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext + + +trait EngineConn { + + /** + * 底层engine的类型比如:Spark、hive + * + * @return + */ + def getEngineType(): String + + def setEngineType(engineType: String): Unit + + /** + * 底层计算存储Engine的具体连接信息,比如SparkSession,hive的sessionState + * + * @return + */ + def getEngine(): Any + + def setEngine(engine: Any): Unit + + def getEngineCreationContext: EngineCreationContext + + +} + +class DefaultEngineConn(engineCreationContext: EngineCreationContext) extends EngineConn { + + var engineType: String = "spark" + + var engine: Any = null + + + /** + * 底层engine的类型比如:Spark、hive + * + * @return + */ + override def getEngineType(): String = engineType + + override def setEngineType(engineType: String): Unit = this.engineType = engineType + + /** + * 底层计算存储Engine的具体连接信息,比如SparkSession,hive的sessionState + * + * @return + */ + override def getEngine(): Any = engine + + override def setEngine(engine: Any): Unit = this.engine = engine + + override def getEngineCreationContext: EngineCreationContext = engineCreationContext + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala new file mode 100644 index 0000000000..51fa841b5f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class EngineTypeVersionNotMatchException(msg: String) extends ErrorException(40010, msg) + + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala new file mode 100644 index 0000000000..b6e6252140 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala @@ -0,0 +1,56 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.execution + +import com.webank.wedatasphere.linkis.common.exception.FatalException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import org.apache.commons.lang.StringUtils + + +trait EngineExecution { + + def execute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit +} + +object EngineExecution extends Logging { + + + private val engineExecutions = initEngineExecutions + + private def initEngineExecutions: Array[EngineExecution] = { + + val executions = EngineConnConf.ENGINE_EXECUTIONS.getValue + if (StringUtils.isNotBlank(executions)) { + val clazzArr = executions.split(",") + if (null != clazzArr && !clazzArr.isEmpty) { + clazzArr.map { clazz => + Utils.getClassInstance[EngineExecution](clazz) + } + } else { + throw new FatalException(0, "ENGINE_EXECUTIONS must be set") + } + } else { + throw new FatalException(0, "ENGINE_EXECUTIONS must be set") + } + + } + + def getEngineExecutions: Array[EngineExecution] = engineExecutions +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala new file mode 100644 index 0000000000..dab0149ed9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.hook + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import org.apache.commons.lang.StringUtils + + +trait EngineConnHook { + + def beforeCreateEngineConn(engineCreationContext: EngineCreationContext): Unit + + /*def afterCreateEngineConn(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit*/ + + def beforeExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit + + def afterExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit + + def afterEngineServerStartFailed(engineCreationContext: EngineCreationContext, throwable: Throwable): Unit = { + + } + + def afterEngineServerStartSuccess(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + + } + +} + +object EngineConnHook extends Logging { + + private val engineConnHooks = initEngineConnHooks + + private def initEngineConnHooks: Array[EngineConnHook] = { + + val hooks = EngineConnConf.ENGINE_CONN_HOOKS.getValue + if (StringUtils.isNotBlank(hooks)) { + val clazzArr = hooks.split(",") + if (null != clazzArr && clazzArr.nonEmpty) { + clazzArr.map { clazz => + Utils.tryAndWarn(Utils.getClassInstance[EngineConnHook](clazz)) + }.filter(_ != null) + } else { + Array.empty + } + } else { + Array.empty + } + + } + + def getEngineConnHooks: Array[EngineConnHook] = engineConnHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml new file mode 100644 index 0000000000..cbdca0a76b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml @@ -0,0 +1,84 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-core + + + + com.webank.wedatasphere.linkis + linkis-engineconn-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-plugin-core + ${linkis.version} + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala new file mode 100644 index 0000000000..5b7b72cc86 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.{DefaultEngineCreationContext, EngineCreationContext} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.EngineConnPlugin + +object EngineConnObject extends Logging { + + private val engineConnPlugin: EngineConnPlugin = Utils.tryCatch { + Utils.getClassInstance[EngineConnPlugin](EngineConnConf.ENGINECONN_PLUGIN_CLAZZ.getValue) + } { case t: Throwable => + error("Failed to create engineConnPlugin: " + EngineConnConf.ENGINECONN_PLUGIN_CLAZZ.getValue, t) + System.exit(1) + null + } + private var engineCreationContext: EngineCreationContext = _ + private var ready = false + + def isReady: Boolean = isReady + + def setReady: Unit = this.ready = true + + def getEngineConnPlugin: EngineConnPlugin = engineConnPlugin + + def getEngineCreationContext: EngineCreationContext = this.engineCreationContext + + def setEngineCreationContext( engineCreationContext: EngineCreationContext): Unit = this.engineCreationContext = engineCreationContext + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala new file mode 100644 index 0000000000..6f417954ab --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.engineconn + +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject + +trait EngineConnManager { + + def createEngineConn(engineCreationContext: EngineCreationContext): EngineConn + + def getEngineConn(): EngineConn + + +} + +object EngineConnManager { + val engineConnManager: EngineConnManager = new DefaultEngineConnManager + + def getEngineConnManager = engineConnManager +} + +class DefaultEngineConnManager extends EngineConnManager { + + private var engineConn: EngineConn = _ + + override def createEngineConn(engineCreationContext: EngineCreationContext): EngineConn = { + this.engineConn = EngineConnObject.getEngineConnPlugin.getEngineConnFactory.createEngineConn(engineCreationContext) + this.engineConn + } + + override def getEngineConn(): EngineConn = this.engineConn + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala new file mode 100644 index 0000000000..a6ac558c79 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala @@ -0,0 +1,174 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.executor + +import java.util +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.util.EngineConnUtils +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, LabelExecutor} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.EngineConnPlugin +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.{MultiExecutorEngineConnFactory, SingleExecutorEngineConnFactory} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.exception.{EngineConnPluginErrorCode, EngineConnPluginErrorException} +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.EngineRunTypeLabel + +import scala.collection.JavaConverters._ + +trait ExecutorManager { + + def getDefaultExecutor: Executor + + def getExecutorByLabels(labels: Array[Label[_]]): Executor + + def createExecutor(engineCreationContext: EngineCreationContext, labels: Array[Label[_]]): Executor + + def getAllExecutorsMap(): util.Map[String, Executor] + + def generateId(): Int + +} + +class ExecutorManagerImpl extends ExecutorManager with Logging { + + private val executors: util.Map[String, Executor] = new ConcurrentHashMap[String, Executor](2) + private val GSON = EngineConnUtils.GSON + private var defaultExecutor: Executor = _ + + private val idCreator = new AtomicInteger() + + override def getDefaultExecutor: Executor = { + if (null == defaultExecutor || defaultExecutor.isClosed()) { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + if (null == engineConn) { + error("Create default executor failed., engineConn not ready") + return null + } + Utils.tryCatch { + createExecutor(engineConn.getEngineCreationContext, null) + } { + case t: Throwable => + error("Create default executor failed. Now will try again once.", t) + createExecutor(engineConn.getEngineCreationContext, null) + } + } + defaultExecutor + } + + override def createExecutor(engineCreationContext: EngineCreationContext, labels: Array[Label[_]]): Executor = { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + val enginePlugin: EngineConnPlugin = EngineConnObject.getEngineConnPlugin + val isDefault: Boolean = if (null == labels || labels.isEmpty || null == defaultExecutor || defaultExecutor.isClosed()) true else false + var runType: String = null + if (!isDefault) { + runType = getRunTypeFromLables(labels) + if (null == runType) { + val msg = "Invalid RunType label. labels : " + GSON.toJson(labels) + error(msg) + throw new EngineConnPluginErrorException(EngineConnPluginErrorCode.INVALID_LABELS, msg) + } + } + val executor: Executor = { + enginePlugin.getEngineConnFactory match { + case engineConnFactory: SingleExecutorEngineConnFactory => + engineConnFactory.createExecutor(engineCreationContext, engineConn) + case engineConnFactory: MultiExecutorEngineConnFactory => + val executorFactories = engineConnFactory.getExecutorFactories + val chooseExecutorFactory = if (isDefault) { + info("use default executor") + Some(engineConnFactory.getDefaultExecutorFactory) + } else { + executorFactories.find(e => e.canCreate(labels)) + } + if (chooseExecutorFactory.isEmpty) { + val msg = if (null == labels) { + "Cannot get default executorFactory. EngineCreation labels: " + GSON.toJson(engineCreationContext.getLabels()) + } else { + "Cannot get valid executorFactory. EngineCreation labels: " + GSON.toJson(labels) + } + error(msg) + throw new EngineConnPluginErrorException(EngineConnPluginErrorCode.INVALID_LABELS, msg) + } else { + chooseExecutorFactory.get.createExecutor(engineCreationContext, engineConn, labels) + } + case o => + error("Invalid ExecutorFactory " + GSON.toJson(o)) + null + } + } + info(s"Finished create executor ${executor.getId()}") + executor.init() + info(s"Finished init executor ${executor.getId()}") + executor match { + case labelExecutor: LabelExecutor => + runType = getRunTypeFromLables(labelExecutor.getExecutorLabels().asScala.toArray) + case _ => + } + executors.put(runType, executor) + if (isDefault) { + defaultExecutor = executor + } + executor + } + + override def generateId(): Int = idCreator.getAndIncrement() + + override def getExecutorByLabels(labels: Array[Label[_]]): Executor = { + var runType: String = null + labels.foreach(l => l match { + case label: EngineRunTypeLabel => + runType = label.getRunType + case _ => + }) + if (null == runType) { + error("Invalid RunType Label. labels: " + GSON.toJson(labels)) + return null + } + if (!executors.containsKey(runType)) { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + createExecutor(engineConn.getEngineCreationContext, labels) + } + executors.get(runType) + } + + override def getAllExecutorsMap(): util.Map[String, Executor] = executors + + private def getRunTypeFromLables(labels: Array[Label[_]]): String = { + + labels.foreach { + case label: EngineRunTypeLabel => + return label.getRunType + case _ => + } + null + } +} + +object ExecutorManager { + + private val executorManager: ExecutorManager = new ExecutorManagerImpl + Utils.getClassInstance[ExecutorManager](EngineConnExecutorConfiguration.EXECUTOR_MANAGER_SERVICE_CLAZZ.getValue) + + def getInstance(): ExecutorManager = executorManager + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala new file mode 100644 index 0000000000..9e226fe3ec --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala @@ -0,0 +1,98 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.hook + +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock + +import com.webank.wedatasphere.linkis.common.utils.Logging + +class ShutdownHook extends Logging { + + var exitCode = 0 + + private val lock = new ReentrantLock() + private val condition = lock.newCondition() + + // Guarded by "lock" + private var error: Throwable = null + + // Guarded by "lock" + private var stopped: Boolean = false + + def notifyError(e: Throwable): Unit = { + lock.lock() + try { + setExitCode(1) + error = e + error("process exit reason: ", e) + condition.signalAll() + } finally { + lock.unlock() + } + } + + def notifyStop(): Unit = { + lock.lock() + try { + setExitCode(0) + stopped = true + condition.signalAll() + } finally { + lock.unlock() + } + } + + /** + * Return `true` if it's stopped; or throw the reported error if `notifyError` has been called; or + * `false` if the waiting time detectably elapsed before return from the method. + */ + def waitForStopOrError(timeout: Long = -1): Boolean = { + lock.lock() + try { + if (timeout < 0) { + while (!stopped && error == null) { + condition.await() + } + } else { + var nanos = TimeUnit.MILLISECONDS.toNanos(timeout) + while (!stopped && error == null && nanos > 0) { + nanos = condition.awaitNanos(nanos) + } + } + // If already had error, then throw it + if (error != null) throw error + // already stopped or timeout + stopped + } finally { + lock.unlock() + } + } + + def setExitCode(exitCode: Int): Unit = this.exitCode = exitCode + + def getExitCode(): Int = exitCode + +} + +object ShutdownHook { + + private val shutdownHook = new ShutdownHook + + def getShutdownHook: ShutdownHook = shutdownHook + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala new file mode 100644 index 0000000000..e1d4e5ba83 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.util + +import com.google.gson.Gson + +object EngineConnUtils { + + val GSON = new Gson() + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml new file mode 100644 index 0000000000..1b6b563f61 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml @@ -0,0 +1,99 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-accessible-executor + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + reflections + org.reflections + + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-launch + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + + + reflections + org.reflections + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java new file mode 100644 index 0000000000..c60eacd8c0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.common.log.LogUtils; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.LogEvent; + +public abstract class AbstractLogCache implements LogCache { + protected String generateLog(LogEvent event) { + if (event.getLevel() == Level.INFO) { + return LogUtils.generateInfo(event.getMessage().toString()); + } else if (event.getLevel() == Level.WARN) { + return LogUtils.generateWarn(event.getMessage().toString()); + } else if (event.getLevel() == Level.ERROR) { + return LogUtils.generateERROR(event.getMessage().toString()); + } else if (event.getLevel() == Level.FATAL) { + return LogUtils.generateSystemError(event.getMessage().toString()); + } + return ""; + } +} diff --git a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java similarity index 86% rename from ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java rename to linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java index 63b67fba23..4000f33e51 100644 --- a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java @@ -14,26 +14,24 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.log; +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; import java.util.List; -/** - * created by enjoyyin on 2018/11/27 - * Description: - */ public interface LogCache { /** * Store logs in the cache for subsequent delivery * 将日志存储到缓存当中,用于后续的发送 + * * @param log 日志信息 */ void cacheLog(String log); /** * Get the log of the number of num(获取num数目的日志) - * @param num The number of logs you want to get(希望获取的日志的数量) + * + * @param num The number of logs you want to get(希望获取的日志的数量) * @return Log List Collection(日志List集合) */ List getLog(int num); @@ -41,6 +39,7 @@ public interface LogCache { /** * Take all the logs in the log cache for the engine to take out all the logs after performing a task * 将日志缓存中的所有日志都取出,用于engine执行完一个任务之后将日志全部取出 + * * @return */ List getRemain(); diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java new file mode 100644 index 0000000000..4058910ad9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java @@ -0,0 +1,126 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class MountLogCache extends AbstractLogCache { + + private static final Logger logger = LoggerFactory.getLogger(MountLogCache.class); + + class CircularQueue { + + private int max; + private String[] elements; + private int front, rear, count; + + CircularQueue() { + this((Integer) AccessibleExecutorConfiguration.ENGINECONN_LOG_CACHE_NUM().getValue()); + } + + CircularQueue(int max) { + this.max = max; + this.elements = new String[max]; + } + + public boolean isEmpty() { + return count == 0; + } + + public synchronized void enqueue(String value) { + if (count == max) { + logger.warn("Queue is full, log: {} needs to be dropped", value); + } else { + rear = (rear + 1) % max; + elements[rear] = value; + count++; + } + } + + public String dequeue() { + if (count == 0) { + logger.debug("Queue is empty, nothing to get"); + return null; + } else { + front = (front + 1) % max; + count--; + return elements[front]; + } + } + + public List dequeue(int num) { + List list = new ArrayList<>(); + int index = 0; + while (index < num) { + String tempLog = dequeue(); + if (StringUtils.isNotEmpty(tempLog)) { + list.add(tempLog); + } else if (tempLog == null) { + break; + } + index++; + } + return list; + } + + public synchronized List getRemain() { + List list = new ArrayList<>(); + while (!isEmpty()) { + list.add(dequeue()); + } + return list; + } + + public int size() { + return count; + } + } + + + private CircularQueue logs; + + + public MountLogCache(int loopMax) { + this.logs = new CircularQueue(loopMax); + } + + @Override + public void cacheLog(String log) { + logs.enqueue(log); + } + + @Override + public List getLog(int num) { + return logs.dequeue(num); + } + + @Override + public synchronized List getRemain() { + return logs.getRemain(); + } + + @Override + public int size() { + return logs.size(); + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java new file mode 100644 index 0000000000..ec6069cc7d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java @@ -0,0 +1,142 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.common.utils.Utils; +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration; +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent; +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject; +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListenerBus; +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@Plugin(name = "Send", category = "Core", elementType = "appender", printObject = true) +public class SendAppender extends AbstractAppender { + + /** + * @fields serialVersionUID + */ + private static final long serialVersionUID = -830237775522429777L; + + private static EngineConnSyncListenerBus engineConnSyncListenerBus = ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnSyncListenerBus(); + + private LogCache logCache; + private static final Logger logger = LoggerFactory.getLogger(SendAppender.class); + + private static final String IGNORE_WORDS = AccessibleExecutorConfiguration.ENGINECONN_IGNORE_WORDS().getValue(); + + private static final String[] IGNORE_WORD_ARR = IGNORE_WORDS.split(","); + + private static final String PASS_WORDS = AccessibleExecutorConfiguration.ENGINECONN_PASS_WORDS().getValue(); + + private static final String[] PASS_WORDS_ARR = PASS_WORDS.split(","); + + + class SendThread implements Runnable { + @Override + public void run() { + if (engineConnSyncListenerBus == null) { + //ignore + } else { + if (logCache == null) { + logger.warn("logCache is null"); + return; + } + List logs = logCache.getRemain(); + if (logs.size() > 0) { + StringBuilder sb = new StringBuilder(); + for (String log : logs) { + sb.append(log).append("\n"); + } + if (EngineConnObject.isReady()) { + engineConnSyncListenerBus.postToAll(new TaskLogUpdateEvent(null, sb.toString())); + } + } + } + } + } + + + public SendAppender(final String name, final Filter filter, final Layout extends Serializable> layout, + final boolean ignoreExceptions) { + super(name, filter, layout, ignoreExceptions); + this.logCache = LogHelper.logCache(); + SendThread thread = new SendThread(); + Utils.defaultScheduler().scheduleAtFixedRate(thread, 10, (Integer) AccessibleExecutorConfiguration.ENGINECONN_LOG_SEND_TIME_INTERVAL().getValue(), TimeUnit.MILLISECONDS); + } + + + + @Override + public void append(LogEvent event) { + if (engineConnSyncListenerBus == null) { + return; + } + String logStr = new String(getLayout().toByteArray(event)); + if (event.getLevel().intLevel() == Level.INFO.intLevel()) { + boolean flag = false; + for (String ignoreLog : IGNORE_WORD_ARR) { + if (logStr.contains(ignoreLog)) { + flag = true; + break; + } + } + for (String word : PASS_WORDS_ARR) { + if (logStr.contains(word)) { + flag = false; + break; + } + } + if (!flag) { + logCache.cacheLog(logStr); + } + } else { + logCache.cacheLog(logStr); + } + } + + @PluginFactory + public static SendAppender createAppender(@PluginAttribute("name") String name, + @PluginElement("Filter") final Filter filter, + @PluginElement("Layout") Layout extends Serializable> layout, + @PluginAttribute("ignoreExceptions") boolean ignoreExceptions) { + if (name == null) { + LOGGER.error("No name provided for SendAppender"); + return null; + } + if (layout == null) { + layout = PatternLayout.createDefaultLayout(); + } + return new SendAppender(name, filter, layout, ignoreExceptions); + } + +} \ No newline at end of file diff --git a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java similarity index 84% rename from ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java rename to linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java index 0da73e4a42..68ff59454c 100644 --- a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java @@ -14,17 +14,14 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.log; - -import org.apache.logging.log4j.core.LogEvent; +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; import java.util.List; /** - * created by enjoyyin on 2018/11/27 * Description: Cache with time as storage unit(以时间作为存储单位的缓存方式) */ -public class TimeLogCache extends AbstractLogCache{ +public class TimeLogCache extends AbstractLogCache { @Override public void cacheLog(String log) { diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala new file mode 100644 index 0000000000..88a9d378e7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + +object AccessibleExecutorConfiguration { + + val ENGINECONN_LOG_CACHE_NUM = CommonVars("wds.linkis.engineconn.log.cache.default", 500) + + + val ENGINECONN_IGNORE_WORDS = CommonVars("wds.linkis.engineconn.ignore.words", "org.apache.spark.deploy.yarn.Client") + + val ENGINECONN_PASS_WORDS = CommonVars("wds.linkis.engineconn.pass.words", "org.apache.hadoop.hive.ql.exec.Task") + + val ENGINECONN_LOG_NUM_SEND_ONCE = CommonVars("wds.linkis.engineconn.log.send.once", 100) + + val ENGINECONN_LOG_SEND_TIME_INTERVAL = CommonVars("wds.linkis.engineconn.log.send.time.interval", 3) + + + val ENGINECONN_MAX_FREE_TIME = CommonVars("wds.linkis.engineconn.max.free.time", new TimeType("1h")) + + + val ENGINECONN_SUPPORT_PARALLELISM = CommonVars("wds.linkis.engineconn.support.parallelism", false) + + + val ENGINECONN_HEARTBEAT_TIME = CommonVars("wds.linkis.engineconn.heartbeat.time", new TimeType("3m")) + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala new file mode 100644 index 0000000000..2a0f157730 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.info.{DefaultNodeOverLoadInfoManager, NodeOverLoadInfoManager} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.{EngineConnConcurrentLockService, EngineConnTimedLockService, LockService} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.context.annotation.{Bean, Configuration} + +@Configuration +class AccessibleExecutorSpringConfiguration extends Logging { + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus + + @Bean(Array("lockService")) + @ConditionalOnMissingBean + def createLockManager(): LockService = { + + val lockService = if (AccessibleExecutorConfiguration.ENGINECONN_SUPPORT_PARALLELISM.getValue) new EngineConnConcurrentLockService + else new EngineConnTimedLockService + asyncListenerBusContext.addListener(lockService) + lockService + } + + @Bean + @ConditionalOnMissingBean(Array(classOf[NodeOverLoadInfoManager])) + def createNodeOverLoadInfoManager(): NodeOverLoadInfoManager = { + + new DefaultNodeOverLoadInfoManager + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala new file mode 100644 index 0000000000..277ad5eafb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala @@ -0,0 +1,90 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.ExecutorStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.executor.entity.SensibleExecutor +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException + +abstract class AccessibleExecutor extends SensibleExecutor { + + private var isExecutorClosed = false + + def isIdle = NodeStatus.isIdle(getStatus) + + def isBusy = NodeStatus.isLocked(getStatus) + + def whenBusy[A](f: => A) = whenStatus(NodeStatus.Busy, f) + + def whenIdle[A](f: => A) = whenStatus(NodeStatus.Idle, f) + + def whenStatus[A](_status: NodeStatus, f: => A) = if (getStatus == _status) f + + def ensureBusy[A](f: => A): A = { + lastActivityTime = System.currentTimeMillis + if (isBusy) synchronized { + if (isBusy) return f + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + def ensureIdle[A](f: => A): A = ensureIdle(f, true) + + def ensureIdle[A](f: => A, transitionState: Boolean): A = { + if (isIdle) synchronized { + if (isIdle) { + if (transitionState) transition(NodeStatus.Busy) + return Utils.tryFinally(f) { + if (transitionState) transition(NodeStatus.Idle) + callback() + } + } + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + + def ensureAvailable[A](f: => A): A = { + if (NodeStatus.isAvailable(getStatus)) synchronized { + if (NodeStatus.isAvailable(getStatus)) return Utils.tryFinally(f)(callback()) + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + def whenAvailable[A](f: => A): A = { + if (NodeStatus.isAvailable(getStatus)) return Utils.tryFinally(f)(callback()) + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + protected def callback(): Unit + + def supportCallBackLogs(): Boolean + + protected override def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit = { + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorStatusChangedEvent(this, fromStatus, toStatus)) + } + + override def close(): Unit = { + isExecutorClosed = true + super.close() + } + + override def isClosed(): Boolean = isExecutorClosed +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala new file mode 100644 index 0000000000..3633d4039a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.{NodeHealthyInfo, NodeOverLoadInfo} + +import scala.beans.BeanProperty + +class ExecutorStatusInfo { + + @BeanProperty + var status: NodeStatus = NodeStatus.Starting + + @BeanProperty + var healthyInfo: NodeHealthyInfo = null + + @BeanProperty + var overLoadInfo: NodeOverLoadInfo = null + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala new file mode 100644 index 0000000000..8238ef8d57 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeHealthy +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeHealthyInfo +import org.springframework.stereotype.Component + +trait NodeHealthyInfoManager { + + def getNodeHealthyInfo(): NodeHealthyInfo + + +} + + +@Component +class DefaultNodeHealthyInfoManager extends NodeHealthyInfoManager with Logging { + + override def getNodeHealthyInfo(): NodeHealthyInfo = { + val nodeHealthyInfo = new NodeHealthyInfo + nodeHealthyInfo.setMsg("") + nodeHealthyInfo.setNodeHealthy(NodeHealthy.Healthy) + nodeHealthyInfo + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala new file mode 100644 index 0000000000..f99cd8f836 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +trait NodeHeartbeatMsgManager { + + def getHeartBeatMsg(): String + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala new file mode 100644 index 0000000000..ed8b256785 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +import com.webank.wedatasphere.linkis.common.utils.{Logging, OverloadUtils} +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import org.springframework.stereotype.Component + +trait NodeOverLoadInfoManager { + // TODO linkis/windows/docker overload + def getNodeOverLoadInfo: NodeOverLoadInfo + +} + +//@ConditionalOnMissingBean(name=Array("nodeOverLoadInfoManager")) +@Component +class DefaultNodeOverLoadInfoManager extends NodeOverLoadInfoManager with Logging { + + override def getNodeOverLoadInfo: NodeOverLoadInfo = { + val nodeOverLoadInfo = new NodeOverLoadInfo + nodeOverLoadInfo.setMaxMemory(OverloadUtils.getProcessMaxMemory) + nodeOverLoadInfo.setUsedMemory(OverloadUtils.getProcessUsedMemory) + nodeOverLoadInfo.setSystemCPUUsed(OverloadUtils.getSystemCPUUsed) + nodeOverLoadInfo.setSystemLeftMemory(OverloadUtils.getSystemFreeMemory) + nodeOverLoadInfo + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala new file mode 100644 index 0000000000..b5b6b27546 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorLockEvent, ExecutorUnLockEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait ExecutorLockListener extends EngineConnAsyncListener { + + def onAddLock(addLockEvent: ExecutorLockEvent): Unit + + def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + case addLockEvent: ExecutorLockEvent => onAddLock(addLockEvent) + case releaseLockEvent: ExecutorUnLockEvent => onReleaseLock(releaseLockEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala new file mode 100644 index 0000000000..22139eecb2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorCompletedEvent, ExecutorCreateEvent, ExecutorStatusChangedEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait ExecutorStatusListener extends EngineConnAsyncListener { + + def onExecutorCreated(executorCreateEvent: ExecutorCreateEvent): Unit + + def onExecutorCompleted(executorCompletedEvent: ExecutorCompletedEvent): Unit + + def onExecutorStatusChanged(executorStatusChangedEvent: ExecutorStatusChangedEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + case executorCreateEvent: ExecutorCreateEvent => onExecutorCreated(executorCreateEvent) + case executorCompletedEvent: ExecutorCompletedEvent => onExecutorCompleted(executorCompletedEvent) + case executorStatusChangedEvent: ExecutorStatusChangedEvent => onExecutorStatusChanged(executorStatusChangedEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala new file mode 100644 index 0000000000..6d15d9ff65 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + +trait LogListener extends EngineConnSyncListener { + + def onLogUpdate(logUpdateEvent: TaskLogUpdateEvent) + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala new file mode 100644 index 0000000000..d6244d49c9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.NodeHealthyUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait NodeHealthyListener extends EngineConnAsyncListener { + + + def onNodeHealthyUpdate(nodeHealthyUpdateEvent: NodeHealthyUpdateEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + + case nodeHealthyUpdateEvent: NodeHealthyUpdateEvent => onNodeHealthyUpdate(nodeHealthyUpdateEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala new file mode 100644 index 0000000000..b60c4a4d4b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeHealthyInfo + +trait AccessibleExecutorConnAsyncEvent extends EngineConnAsyncEvent { + +} + +case class ExecutorCreateEvent(executor: Executor) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorCompletedEvent(executor: Executor, message: String) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorStatusChangedEvent(executor: Executor, fromStatus: NodeStatus, toStatus: NodeStatus) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorLockEvent(executor: Executor, lock: String) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorUnLockEvent(executor: Executor, lock: String) extends AccessibleExecutorConnAsyncEvent + +case class NodeHealthyUpdateEvent(nodeHealthyInfo: NodeHealthyInfo) extends AccessibleExecutorConnAsyncEvent + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala new file mode 100644 index 0000000000..5623ed7551 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +case class LogUpdateEvent(taskId: String, log: String) extends EngineConnSyncEvent diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala new file mode 100644 index 0000000000..92b3d66126 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo + +trait TaskEvent extends EngineConnSyncEvent { + +} + +case class TaskProgressUpdateEvent(taskId: String, progress: Float, progressInfo: Array[JobProgressInfo]) extends TaskEvent + +case class TaskLogUpdateEvent(taskId: String, log: String) extends TaskEvent + +case class TaskStatusChangedEvent(taskId: String, fromStatus: ExecutionNodeStatus, toStatus: ExecutionNodeStatus) extends TaskEvent + +case class TaskResultCreateEvent(taskId: String, resStr: String, alias: String) extends TaskEvent + +case class TaskResultSizeCreatedEvent(taskId: String, resultSize: Int) extends TaskEvent \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala new file mode 100644 index 0000000000..ae0b60471b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala @@ -0,0 +1,157 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock + +import java.util.concurrent.{ScheduledFuture, ScheduledThreadPoolExecutor, Semaphore, TimeUnit} + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.ExecutorUnLockEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus + +class EngineConnTimedLock(private var timeout: Long) extends TimedLock with Logging { + + var lock = new Semaphore(1) + val releaseScheduler = new ScheduledThreadPoolExecutor(1) + var releaseTask: ScheduledFuture[_] = null + var lastLockTime: Long = 0 + var lockedBy: AccessibleExecutor = null + + override def acquire(executor: AccessibleExecutor): Unit = { + lock.acquire() + lastLockTime = System.currentTimeMillis() + lockedBy = executor + scheduleTimeout + } + + override def tryAcquire(executor: AccessibleExecutor): Boolean = { + if (null == executor) return false + val succeed = lock.tryAcquire() + debug("try to lock for succeed is " + succeed.toString) + if (succeed) { + lastLockTime = System.currentTimeMillis() + lockedBy = executor + debug("try to lock for add time out task ! Locked by thread : " + lockedBy.getId) + scheduleTimeout + } + succeed + } + + // Unlock callback is not called in release method, because release method is called actively + override def release(): Unit = { + debug("try to release for lock," + lockedBy + ",current thread " + Thread.currentThread().getName) + if (lockedBy != null) { + //&& lockedBy == Thread.currentThread() Inconsistent thread(线程不一致) + debug("try to release for lockedBy and thread ") + if (releaseTask != null) { + releaseTask.cancel(true) + releaseTask = null + releaseScheduler.purge() + } + debug("try to release for lock release success") + lockedBy = null + } + resetLock() + } + + private def resetLock(): Unit = { + lock.release() + lock = new Semaphore(1) + } + + override def forceRelease(): Unit = { + if (isAcquired()) { + if (releaseTask != null) { + releaseTask.cancel(true) + releaseTask = null + releaseScheduler.purge() + } + lock.release() + lockedBy = null + } + resetLock() + } + + private def scheduleTimeout: Unit = { + synchronized { + if (null == releaseTask || releaseTask.isDone) { + releaseTask = releaseScheduler.schedule(new Runnable { + override def run(): Unit = { + synchronized { + if (isExpired()) { + lock.release() + // unlockCallback depends on lockedBy, so lockedBy cannot be set null before unlockCallback + unlockCallback(lock.toString) + info(s"Lock : [${lock.toString} was released due to timeout." ) + resetLock() + } + } + } + }, timeout, TimeUnit.MILLISECONDS) + } + } + } + + override def isAcquired(): Boolean = { + lock.availablePermits() < 1 + } + + override def isExpired(): Boolean = { + if (lastLockTime == 0) return false + System.currentTimeMillis() - lastLockTime > timeout + } + + + override def numOfPending(): Int = { + lock.getQueueLength + } + + override def renew(): Boolean = { + if (lockedBy != null && lockedBy == Thread.currentThread()) { + if (isAcquired && releaseTask != null) { + if (releaseTask.cancel(false)) { + releaseScheduler.purge() + scheduleTimeout + lastLockTime = System.currentTimeMillis() + return true + } + } + } + false + } + + override def resetTimeout(timeout: Long): Unit = synchronized { + if (isAcquired()) { + if (null != releaseTask && !isExpired()) { + releaseTask.cancel(true) + this.timeout = timeout + } + scheduleTimeout + } else { + error("Lock is not acquired, so cannot be reset-Timeout") + } + } + + private def unlockCallback(lockStr: String): Unit = { + if (null != lockedBy) { + lockedBy.transition(NodeStatus.Unlock) + } + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorUnLockEvent(null, lockStr.toString)) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala new file mode 100644 index 0000000000..8ecdb30ffd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor + +trait TimedLock { + + @throws[Exception] + def acquire(executor: AccessibleExecutor): Unit + + def tryAcquire(executor: AccessibleExecutor): Boolean + + @throws[Exception] + def release(): Unit + + @throws[Exception] + def forceRelease(): Unit + + def numOfPending(): Int + + def isAcquired(): Boolean + + def isExpired(): Boolean + + @throws[Exception] + def renew(): Boolean + + def resetTimeout(timeout: Long): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala new file mode 100644 index 0000000000..e6590c35c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log + +import java.util + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.LogListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent +import org.slf4j.LoggerFactory + +object LogHelper { + private val logger = LoggerFactory.getLogger(getClass) + val logCache = new MountLogCache(AccessibleExecutorConfiguration.ENGINECONN_LOG_CACHE_NUM.getValue) + + private var logListener: LogListener = _ + + def setLogListener(logListener: LogListener): Unit = this.logListener = logListener + + def pushAllRemainLogs(): Unit = { +// logger.info(s"start to push all remain logs") + Thread.sleep(30) + //logCache.synchronized{ + if (logListener == null) { + logger.warn("logListener is null, can not push remain logs") + //return + } else { + var logs: util.List[String] = null + logCache.synchronized { + logs = logCache.getRemain + } + if (logs != null && logs.size > 0) { + val sb: StringBuilder = new StringBuilder + import scala.collection.JavaConversions._ + logs map (log => log + "\n") foreach sb.append + logger.info(s"remain logs is ${sb.toString()}") + logListener.onLogUpdate(TaskLogUpdateEvent(null, sb.toString)) + } + } + logger.info("end to push all remain logs") + // } + // if (sendAppender == null){ + // logger.error("SendAppender has not been initialized") + // }else{ + // val logCache = sendAppender.getLogCache + // val logListener = SendAppender.getLogListener + // logCache.synchronized{ + // val logs: util.List[String] = logCache.getRemain + // if (logs.size > 0) { + // val sb: StringBuilder = new StringBuilder + // import scala.collection.JavaConversions._ + // logs map (log => log + "\n") foreach sb.append + // logListener.onLogUpdate(null, sb.toString) + // } + // } + // } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala new file mode 100644 index 0000000000..66bb93b6fa --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.ExecutorStatusListener +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineSuicideRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext + +trait AccessibleService extends ExecutorStatusListener { + + def stopExecutor: Unit + + def pauseExecutor: Unit + + def reStartExecutor: Boolean + + def dealEngineStopRequest(engineSuicideRequest: EngineSuicideRequest, smc: ServiceMethodContext): Unit + + + /** + * service 需要加定时任务判断Executor是否空闲很久,然后调用该方法进行释放 + */ + def requestManagerReleaseExecutor(msg: String): Unit + + + def dealRequestNodeStatus(requestNodeStatus: RequestNodeStatus): ResponseNodeStatus + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala new file mode 100644 index 0000000000..adf6dc19ad --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala @@ -0,0 +1,177 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorCompletedEvent, ExecutorCreateEvent, ExecutorStatusChangedEvent} +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, SensibleExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineConnReleaseRequest, EngineSuicideRequest} +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.rpc.Sender +import javax.annotation.PostConstruct +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import scala.collection.JavaConverters._ + + +@Service +class DefaultAccessibleService extends AccessibleService with Logging { + + @Autowired + private var executorHeartbeatService: ExecutorHeartbeatService = _ + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + + @Receiver + override def dealEngineStopRequest(engineSuicideRequest: EngineSuicideRequest, smc: ServiceMethodContext): Unit = { + // todo check user + if (DataWorkCloudApplication.getServiceInstance.equals(engineSuicideRequest.getServiceInstance)) { + stopEngine() + info(s"engine will suiside now.") + ShutdownHook.getShutdownHook.notifyStop() + } else { + if (null != engineSuicideRequest.getServiceInstance) { + error(s"Invalid serviceInstance : ${engineSuicideRequest.getServiceInstance.toString}, will not suicide.") + } else { + error("Invalid empty serviceInstance.") + } + } + } + + private def executorShutDownHook(): Unit = { + var executor: Executor = ExecutorManager.getInstance().getDefaultExecutor + if (null != executor) { + executor.asInstanceOf[SensibleExecutor].transition(NodeStatus.ShuttingDown) + } else { + executor = SensibleExecutor.getDefaultErrorSensibleExecutor() + } + executorHeartbeatService.reportHeartBeatMsg(executor) + info("Reported status shuttingDown to manager.") + } + + override def stopExecutor: Unit = { + // todo + } + + + override def pauseExecutor: Unit = { + + } + + override def reStartExecutor: Boolean = { + true + } + + /** + * Service启动后则启动定时任务 空闲释放 + */ + @PostConstruct + private def init(): Unit = { + val context = EngineConnObject.getEngineCreationContext + val maxFreeTimeVar = AccessibleExecutorConfiguration.ENGINECONN_MAX_FREE_TIME.getValue(context.getOptions) + val maxFreeTimeStr = maxFreeTimeVar.toString + val maxFreeTime = maxFreeTimeVar.toLong + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val executor = ExecutorManager.getInstance().getDefaultExecutor + if (null == executor || !executor.isInstanceOf[AccessibleExecutor]) { + warn("Default is not AccessibleExecutor,do noting") + return + } + info("maxFreeTimeMills is " + maxFreeTime) + val accessibleExecutor = ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[AccessibleExecutor] + if (NodeStatus.isCompleted(accessibleExecutor.getStatus)) { + error(s"${accessibleExecutor.getId()} has completed with status ${accessibleExecutor.getStatus}, now stop it.") + ShutdownHook.getShutdownHook.notifyStop() + } else if (accessibleExecutor.getStatus == NodeStatus.ShuttingDown) { + warn(s"${accessibleExecutor.getId()} is ShuttingDown...") + ShutdownHook.getShutdownHook.notifyStop() + } else if (maxFreeTime > 0 && NodeStatus.isIdle(accessibleExecutor.getStatus) && System.currentTimeMillis - accessibleExecutor.getLastActivityTime > maxFreeTime) { + warn(s"${accessibleExecutor.getId()} has not been used for $maxFreeTimeStr, now try to shutdown it.") + requestManagerReleaseExecutor(" idle release") + } + } + }, 10 * 60 * 1000, AccessibleExecutorConfiguration.ENGINECONN_HEARTBEAT_TIME.getValue.toLong, TimeUnit.MILLISECONDS) + asyncListenerBusContext.addListener(this) + Utils.addShutdownHook(executorShutDownHook()) + } + + private def stopEngine(): Unit = { + Utils.tryAndWarn { + ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[SensibleExecutor].transition(NodeStatus.ShuttingDown) + val executors = ExecutorManager.getInstance().getAllExecutorsMap() + executors.asScala.map{ + kv => kv._2.tryShutdown() + } + executors.clear() + } + } + + /** + * service 需要加定时任务判断Executor是否空闲很久,然后调用该方法进行释放 + */ + + override def requestManagerReleaseExecutor(msg: String): Unit = { + val engineReleaseRequest = new EngineConnReleaseRequest(Sender.getThisServiceInstance, Utils.getJvmUser, msg, EngineConnManager.getEngineConnManager.getEngineConn().getEngineCreationContext.getTicketId) + ManagerService.getManagerService.requestReleaseEngineConn(engineReleaseRequest) + } + + @Receiver + override def dealRequestNodeStatus(requestNodeStatus: RequestNodeStatus): ResponseNodeStatus = { + val status = ExecutorManager.getInstance().getDefaultExecutor match { + case executor: SensibleExecutor => + executor.getStatus + case _ => NodeStatus.Starting + } + val responseNodeStatus = new ResponseNodeStatus + responseNodeStatus.setNodeStatus(status) + responseNodeStatus + } + + override def onExecutorCreated(executorCreateEvent: ExecutorCreateEvent): Unit = { + + } + + override def onExecutorCompleted(executorCompletedEvent: ExecutorCompletedEvent): Unit = { + + } + + override def onExecutorStatusChanged(executorStatusChangedEvent: ExecutorStatusChangedEvent): Unit = { + if (!ExecutorManager.getInstance().getDefaultExecutor.isInstanceOf[AccessibleExecutor]) { + warn("Default is not AccessibleExecutor,do noting") + return + } + val executor = ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[AccessibleExecutor] + executorHeartbeatService.reportHeartBeatMsg(executor) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala new file mode 100644 index 0000000000..f135cae735 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.info.{NodeHealthyInfoManager, NodeHeartbeatMsgManager, NodeOverLoadInfoManager} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.NodeHealthyListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.NodeHealthyUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, ResourceExecutor, SensibleExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import javax.annotation.PostConstruct +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +@Service +class DefaultExecutorHeartbeatService extends ExecutorHeartbeatService with NodeHealthyListener with Logging { + + + @Autowired + private var nodeHealthyInfoManager: NodeHealthyInfoManager = _ + + @Autowired + private var nodeOverLoadInfoManager: NodeOverLoadInfoManager = _ + + @Autowired(required = false) + private var nodeHeartbeatMsgManager: NodeHeartbeatMsgManager = _ + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + + @PostConstruct + private def init(): Unit = { + asyncListenerBusContext.addListener(this) + val heartbeatTime = AccessibleExecutorConfiguration.ENGINECONN_HEARTBEAT_TIME.getValue.toLong + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val executor = ExecutorManager.getInstance().getDefaultExecutor + reportHeartBeatMsg(executor) + } + }, 3 * 60 * 1000, heartbeatTime, TimeUnit.MILLISECONDS) + } + + /** + * 定时上报心跳信息,依据Executor不同进行实现 + * + * @param executor + */ + override def reportHeartBeatMsg(executor: Executor): Unit = { + ManagerService.getManagerService.heartbeatReport(generateHeartBeatMsg(executor)) + } + + + @Receiver + override def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg = { + val executor = ExecutorManager.getInstance().getDefaultExecutor + generateHeartBeatMsg(executor) + } + + + override def onNodeHealthyUpdate(nodeHealthyUpdateEvent: NodeHealthyUpdateEvent): Unit = { + warn(s"node healthy update, tiger heartbeatReport") + val executor = ExecutorManager.getInstance().getDefaultExecutor + reportHeartBeatMsg(executor) + } + + override def generateHeartBeatMsg(executor: Executor): NodeHeartbeatMsg = { + val nodeHeartbeatMsg = new NodeHeartbeatMsg + + nodeHeartbeatMsg.setServiceInstance(Sender.getThisServiceInstance) + nodeHeartbeatMsg.setOverLoadInfo(nodeOverLoadInfoManager.getNodeOverLoadInfo) + nodeHeartbeatMsg.setHealthyInfo(nodeHealthyInfoManager.getNodeHealthyInfo()) + executor match { + case sensibleExecutor: SensibleExecutor => + nodeHeartbeatMsg.setStatus(sensibleExecutor.getStatus) + case _ => + } + executor match { + case resourceExecutor: ResourceExecutor => + nodeHeartbeatMsg.setNodeResource(resourceExecutor.getCurrentNodeResource()) + case _ => + } + if (null != nodeHeartbeatMsgManager) { + nodeHeartbeatMsg.setHeartBeatMsg(nodeHeartbeatMsgManager.getHeartBeatMsg()) + } + nodeHeartbeatMsg + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala new file mode 100644 index 0000000000..7500d9f22b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala @@ -0,0 +1,67 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util + +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnReleaseRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.label.LabelReportRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.rpc.Sender + +class DefaultManagerService extends ManagerService { + + + protected def getManagerSender: Sender = { + Sender.getSender(GovernanceCommonConf.MANAGER_SPRING_NAME.getValue) + } + + protected def getEngineConnManagerSender: Sender = { + Sender.getSender(GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue) + } + + + override def labelReport(labels: util.List[Label[_]]): Unit = { + val labelReportRequest = LabelReportRequest(labels, Sender.getThisServiceInstance) + getManagerSender.send(labelReportRequest) + } + + + override def statusReport(status: NodeStatus): Unit = { + val responseNodeStatus = new ResponseNodeStatus + responseNodeStatus.setNodeStatus(status) + getManagerSender.send(responseNodeStatus) + } + + override def requestReleaseEngineConn(engineConnReleaseRequest: EngineConnReleaseRequest): Unit = { + getManagerSender.send(engineConnReleaseRequest) + } + + override def heartbeatReport(nodeHeartbeatMsg: NodeHeartbeatMsg): Unit = { + getManagerSender.send(nodeHeartbeatMsg) + } + + override def reportUsedResource(resourceUsedProtocol: ResourceUsedProtocol): Unit = { + getManagerSender.send(resourceUsedProtocol) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala new file mode 100644 index 0000000000..e12c0650ce --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala @@ -0,0 +1,202 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorLockEvent, ExecutorUnLockEvent} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock.EngineConnTimedLock +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineLockType +import com.webank.wedatasphere.linkis.manager.common.protocol.{RequestEngineLock, RequestEngineUnlock, ResponseEngineLock, ResponseEngineUnlock} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + + +class EngineConnTimedLockService extends LockService with Logging { + + private var engineConnLock: EngineConnTimedLock = null + private var lockString: String = null + private var lockType: EngineLockType = EngineLockType.Timed + + + private def isSupportParallelism: Boolean = AccessibleExecutorConfiguration.ENGINECONN_SUPPORT_PARALLELISM.getValue + + /** + * + * + * @param lock + * @return + */ + override def isLockExist(lock: String = null): Boolean = synchronized { + if (isSupportParallelism) true + else if (null != engineConnLock && engineConnLock.isAcquired()) { + if (StringUtils.isNotBlank(lock)) { + if (lock.equals(lockString)) true + else false + } else { + false + } + } else { + false + } + + } + + /** + * Try to lock an Executor in the ExecutorManager. If the lock is successful, it will return the Executor ID as the ID. + * 尝试去锁住ExecutorManager里的一个Executor,如果锁成功的话,将返回Executor ID作为标识 + * + * @return + */ + @throws[EngineConnExecutorErrorException] + override def tryLock(requestEngineLock: RequestEngineLock): Option[String] = synchronized { + if (null != engineConnLock && engineConnLock.isAcquired()) return None + this.lockType = requestEngineLock.lockType + lockType match { + case EngineLockType.Always => + timedLock(-1) + case EngineLockType.Timed => + timedLock(requestEngineLock.timeout) + case o: Any => + error("Invalid lockType : " + BDPJettyServerHelper.gson.toJson(o)) + return Some(null) + } + + } + + private def timedLock(timeout: Long): Option[String] = { + + // Lock is binded to engineconn, so choose default executor + ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + debug("try to lock for executor state is " + accessibleExecutor.getStatus) + debug("try to lock for executor id is " + accessibleExecutor.getId) + if (null == engineConnLock) { + engineConnLock = new EngineConnTimedLock(timeout) + debug("try to lock for executor get new lock " + engineConnLock) + } + if (engineConnLock.tryAcquire(accessibleExecutor)) { + debug("try to lock for tryAcquire is true ") + this.lockString = engineConnLock.lock.toString + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorLockEvent(accessibleExecutor, lockString)) + accessibleExecutor.transition(NodeStatus.Idle) + Some(lockString) + } else None + case _ => + val msg = s"Invalid executor or not instance of SensibleEngine." + error(msg) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_ENGINE_TYPE, msg) + } + } + + /** + * Unlock(解锁) + * + * @param lock + */ + override def unlock(lock: String): Boolean = synchronized { + info("try to unlock for lockEntity is " + engineConnLock.toString + ",and lock is " + lock + ",acquired is " + engineConnLock.isAcquired().toString) + if (isLockExist(lock)) { + info(s"try to unlock lockEntity : lockString=${lockString},lockedBy=${engineConnLock.lockedBy.getId()}") + engineConnLock.release() + this.lockString = null + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorUnLockEvent(null, lock)) + ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + accessibleExecutor.transition(NodeStatus.Unlock) + case _ => + val msg = s"Invalid executor or not instance of SensibleEngine." + error(msg) + } + true + } else { + false + } + } + + @Receiver + override def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock = { + if (StringUtils.isBlank(requestEngineUnlock.lock)) { + error("Invalid requestEngineUnlock: ") + ResponseEngineUnlock(false) + } else { + ResponseEngineUnlock(unlock(requestEngineUnlock.lock)) + } + } + + override def onAddLock(addLockEvent: ExecutorLockEvent): Unit = { + + } + + override def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit = { + + } + + + @Receiver + override def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + super.requestLock(requestEngineLock) + } +} + +class EngineConnConcurrentLockService extends LockService { + + override def isLockExist(lock: String): Boolean = true + + override def tryLock(requestEngineLock: RequestEngineLock): Option[String] = { + /*ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + // Concurrent Engine don't change status when get lock, status will change in other rules +// accessibleExecutor.transition(NodeStatus.Idle) + case _ => + }*/ + Some("lock") + } + + /** + * Unlock(解锁) + * + * @param lock + */ + override def unlock(lock: String): Boolean = { + /*ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + accessibleExecutor.transition(NodeStatus.Unlock) + case _ => + }*/ + true + } + + @Receiver + override def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock = ResponseEngineUnlock(true) + + override def onAddLock(addLockEvent: ExecutorLockEvent): Unit = {} + + override def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit = {} + + @Receiver + override def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + super.requestLock(requestEngineLock) + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala new file mode 100644 index 0000000000..21a16cc922 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} + +trait ExecutorHeartbeatService { + + /** + * 定时上报心跳信息,依据Executor不同进行实现 + * + * @param executor + */ + def reportHeartBeatMsg(executor: Executor): Unit + + def generateHeartBeatMsg(executor: Executor): NodeHeartbeatMsg + + + def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala new file mode 100644 index 0000000000..9f82f1345e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala @@ -0,0 +1,61 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.ExecutorLockListener +import com.webank.wedatasphere.linkis.manager.common.protocol.{RequestEngineLock, RequestEngineUnlock, ResponseEngineLock, ResponseEngineUnlock} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + +trait LockService extends ExecutorLockListener with Logging { + + def isLockExist(lock: String): Boolean + + def tryLock(requestEngineLock: RequestEngineLock): Option[String] + + /** + * Unlock(解锁) + * + * @param lock + */ + def unlock(lock: String): Boolean + + def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + var response: ResponseEngineLock = null + tryLock(requestEngineLock) match { + case Some(lockStr) => + // Engine can be locked + if (!StringUtils.isBlank(lockStr)) { + // lock success + response = ResponseEngineLock(true, lockStr, s"Lock for ${requestEngineLock.timeout} ms") + } else { + // lock failed + response = ResponseEngineLock(false, lockStr, "lock str is blank") + } + case None => + // Engine is busy + response = ResponseEngineLock(false, null, "Engine is busy.") + } + info ("RequestLock : " + BDPJettyServerHelper.gson.toJson(requestEngineLock) + "\nResponseLock : " + BDPJettyServerHelper.gson.toJson(response)) + response + } + + def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala new file mode 100644 index 0000000000..18e2e84969 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.log.LogCache + +trait LogService { + + + def getLogCache(): LogCache + + def sendLog(): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala new file mode 100644 index 0000000000..9c7e4b4654 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.utils + +object AccessibleExecutorUtils { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml new file mode 100644 index 0000000000..bff3c83f7d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml @@ -0,0 +1,83 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-callback-service + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala new file mode 100644 index 0000000000..2d4cd3f14b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import com.webank.wedatasphere.linkis.common.ServiceInstance + +class EngineConnAfterStartCallback(emInstance: ServiceInstance) extends AbstractEngineConnStartUpCallback(emInstance) { + + override def callback(): Unit = { + + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala new file mode 100644 index 0000000000..a19be12c8a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.rpc.Sender + +trait EngineConnCallback { + + protected def getEMSender: Sender + + def callback(): Unit + +} + +abstract class AbstractEngineConnStartUpCallback(emInstance: ServiceInstance) extends EngineConnCallback { + + override protected def getEMSender: Sender = { + Sender.getSender(emInstance) + } + + + def callback(protocol: RequestProtocol): Unit = { + getEMSender.send(protocol) + } +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala new file mode 100644 index 0000000000..31f8a3a2d1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import java.lang.management.ManagementFactory + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.rpc.Sender + + +class EngineConnPidCallback(emInstance: ServiceInstance) extends AbstractEngineConnStartUpCallback(emInstance) { + + override def callback(): Unit = { + val pid = ManagementFactory.getRuntimeMXBean.getName.split("@")(0) + val instance = Sender.getThisServiceInstance + val context = EngineConnObject.getEngineCreationContext + callback(ResponseEngineConnPid(instance, pid, context.getTicketId)) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala new file mode 100644 index 0000000000..318615644f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +/** + * 常规callBack + */ +trait EngineConnTimedCallback extends EngineConnCallback { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml new file mode 100644 index 0000000000..a2f59278e9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml @@ -0,0 +1,89 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-executor-core + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-common + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala new file mode 100644 index 0000000000..88ab804753 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + +object EngineConnExecutorConfiguration { + + + val TMP_PATH = CommonVars("wds.linkis.dataworkclod.engine.tmp.path", "file:///tmp/") + + val ENGINE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.engine.application.name", "") + + val ENGINE_LOG_PREFIX = CommonVars("wds.linkis.log4j2.prefix", "/appcom/logs/linkis/" + ENGINE_SPRING_APPLICATION_NAME.getValue) + + val CLEAR_LOG = CommonVars("wds.linkis.log.clear", false) + + + val ENGINE_IGNORE_WORDS = CommonVars("wds.linkis.engine.ignore.words", "org.apache.spark.deploy.yarn.Client") + + val ENGINE_PASS_WORDS = CommonVars("wds.linkis.engine.pass.words", "org.apache.hadoop.hive.ql.exec.Task") + + + + + val ENTRANCE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.entrance.application.name", "linkis-cg-entrance") + + val ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY = CommonVars("wds.linkis.engine.listener.async.queue.size.max", 300) + + val ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX = CommonVars("wds.linkis.engine.listener.async.consumer.thread.max", 5) + + val ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX = CommonVars("wds.linkis.engine.listener.async.consumer.freetime.max", new TimeType("5000ms")) + + // todo better to rename + val EXECUTOR_MANAGER_SERVICE_CLAZZ = CommonVars("wds.linkis.engineconn.executor.manager.service.clazz", "com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.DefaultManagerService") + + /*val EXECUTOR_MANAGER_CLAZZ = CommonVars("wds.linkis.engineconn.executor.manager.claazz", "")*/ + + val DEFAULT_EXECUTOR_NAME = CommonVars("wds.linkis.engineconn.executor.default.name", "ComputationExecutor") +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala new file mode 100644 index 0000000000..f9e0619b97 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.common.utils.Logging + +trait Executor extends Logging { + + def getId(): String + + def init(): Unit + + def tryReady(): Boolean + + def tryShutdown(): Boolean + + def tryFailed(): Boolean + + /** + * 仅用于Kill Executor + * EngineConn kill 在AccessibleService + */ + def close(): Unit = { + warn(s"executor ${getId()} exit by close") + } + + def isClosed(): Boolean + +} + +trait ConcurrentExecutor extends Executor { + + def getConcurrentLimit: Int + + def killAll(): Unit + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala new file mode 100644 index 0000000000..e95bdd6cb9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import java.util + +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait LabelExecutor extends Executor { + + def getExecutorLabels(): util.List[Label[_]] + + def setExecutorLabels(labels: util.List[Label[_]]): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala new file mode 100644 index 0000000000..8ec322dab6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource + +trait ResourceExecutor extends Executor { + + + def requestExpectedResource(expectedResource: NodeResource): NodeResource + + def getCurrentNodeResource(): NodeResource + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala new file mode 100644 index 0000000000..83ee4d39c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala @@ -0,0 +1,80 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus + +import scala.beans.BeanProperty + +trait SensibleExecutor extends Executor { + + protected var status: NodeStatus = NodeStatus.Starting + + @BeanProperty + var lastActivityTime = System.currentTimeMillis + + def getStatus: NodeStatus = status + + protected def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit + + def transition(toStatus: NodeStatus) = this synchronized { + lastActivityTime = System.currentTimeMillis + this.status match { + case NodeStatus.Failed | NodeStatus.Success => + warn(s"$toString attempt to change status ${this.status} => $toStatus, ignore it.") + case NodeStatus.ShuttingDown => + toStatus match { + case NodeStatus.Failed | NodeStatus.Success => + val oldState = status + this.status = toStatus + onStatusChanged(oldState, toStatus) + case _ => warn(s"$toString attempt to change a Executor.ShuttingDown session to $toStatus, ignore it.") + } + case _ => + + } + info(s"$toString change status ${status} => $toStatus.") + val oldState = status + this.status = toStatus + onStatusChanged(oldState, toStatus) + } + +} + +object SensibleExecutor { + + lazy val defaultErrorSensibleExecutor: SensibleExecutor = new SensibleExecutor { + override def getStatus: NodeStatus = NodeStatus.ShuttingDown + + override protected def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit = {} + + override def getId(): String = "0" + + override def init(): Unit = {} + + override def tryReady(): Boolean = false + + override def tryShutdown(): Boolean = true + + override def tryFailed(): Boolean = true + + override def isClosed(): Boolean = true + } + + def getDefaultErrorSensibleExecutor(): SensibleExecutor = defaultErrorSensibleExecutor + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala new file mode 100644 index 0000000000..368ad78027 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import scala.beans.BeanProperty + +trait YarnExecutor extends Executor { + + @BeanProperty + var applicationId: String + + @BeanProperty + var applicationURL: String + + @BeanProperty + var yarnMode: String + + @BeanProperty + var queue: String + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala new file mode 100644 index 0000000000..5d68f71eef --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.EventListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait EngineConnAsyncListener extends EventListener { + + def onEvent(event: EngineConnAsyncEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala new file mode 100644 index 0000000000..160f4b7a1c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerEventBus +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +class EngineConnAsyncListenerBus(eventQueueCapacity: Int, name: String, + listenerConsumerThreadSize: Int, + listenerThreadMaxFreeTime: Long) + extends ListenerEventBus[EngineConnAsyncListener, EngineConnAsyncEvent](eventQueueCapacity, name)(listenerConsumerThreadSize, listenerThreadMaxFreeTime) { + + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: EngineConnAsyncListener, event: EngineConnAsyncEvent): Unit = { + listener.onEvent(event) + } + +} + +object EngineConnAsyncListenerBus { + + def NAME: String = "EngineServerAsyncListenerBus" + + lazy val getInstance = new EngineConnAsyncListenerBus( + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY.getValue, + NAME, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX.getValue, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX.getValue.toLong) + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala new file mode 100644 index 0000000000..e40263eeae --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.EventListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +trait EngineConnSyncListener extends EventListener { + + def onEvent(event: EngineConnSyncEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala new file mode 100644 index 0000000000..9a147375f0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerBus +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +class EngineConnSyncListenerBus extends ListenerBus[EngineConnSyncListener, EngineConnSyncEvent] with Logging { + + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: EngineConnSyncListener, event: EngineConnSyncEvent): Unit = { + debug(s"$listener start to deal event $event") + listener.onEvent(event) + debug(s"$listener Finished to deal event $event") + } +} + +object EngineConnSyncListenerBus { + + def NAME: String = "EngineServerSyncListenerBus" + + lazy val getInstance = new EngineConnSyncListenerBus() + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala new file mode 100644 index 0000000000..cfb2837210 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala @@ -0,0 +1,45 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration + +class ExecutorListenerBusContext { + + private val engineConnAsyncListenerBus: EngineConnAsyncListenerBus = new EngineConnAsyncListenerBus( + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY.getValue, + "EngineConn-Asyn-Thread", + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX.getValue, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX.getValue.toLong + ) + + private val engineConnSyncListenerBus: EngineConnSyncListenerBus = new EngineConnSyncListenerBus + + def getEngineConnAsyncListenerBus: EngineConnAsyncListenerBus = { + engineConnAsyncListenerBus + } + + def getEngineConnSyncListenerBus: EngineConnSyncListenerBus = engineConnSyncListenerBus + +} + +object ExecutorListenerBusContext { + + private val executorListenerBusContext = new ExecutorListenerBusContext + + def getExecutorListenerBusContext() = executorListenerBusContext +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala new file mode 100644 index 0000000000..6161fa2212 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener.event + +import com.webank.wedatasphere.linkis.common.listener.Event + +trait EngineConnAsyncEvent extends Event { + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala new file mode 100644 index 0000000000..4c9a56801b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener.event + +import com.webank.wedatasphere.linkis.common.listener.Event + +trait EngineConnSyncEvent extends Event { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala new file mode 100644 index 0000000000..30ae088f6d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala @@ -0,0 +1,53 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.service + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait LabelService { + + /*def labelUpdate(labelUpdateRequest: LabelUpdateRequest): Unit*/ + + def labelReport(labels: util.List[Label[_]], executor: Executor): Unit + +} + +class DefaultLabelService extends LabelService with Logging { + + + /*override def labelUpdate(labelUpdateRequest: LabelUpdateRequest): Unit = ???*/ + + override def labelReport(labels: util.List[Label[_]], executor: Executor): Unit = { + info(s"executor ${executor.getId()} prepare to report Labels ") + ManagerService.getManagerService.labelReport(labels) + info(s"executor ${executor.getId()} end to report Labels ") + } + + +} + +object LabelService { + + private val labelService = new DefaultLabelService + + def getLabelService: LabelService = this.labelService + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala new file mode 100644 index 0000000000..a79ae003eb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala @@ -0,0 +1,46 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnReleaseRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.NodeHeartbeatMsg +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait ManagerService { + + def labelReport(labels: java.util.List[Label[_]]): Unit + + def statusReport(status: NodeStatus): Unit + + def requestReleaseEngineConn(engineConnReleaseRequest: EngineConnReleaseRequest): Unit + + def heartbeatReport(nodeHeartbeatMsg: NodeHeartbeatMsg): Unit + + def reportUsedResource(resourceUsedProtocol: ResourceUsedProtocol): Unit + +} + +object ManagerService { + + private val managerService: ManagerService = Utils.getClassInstance[ManagerService](EngineConnExecutorConfiguration.EXECUTOR_MANAGER_SERVICE_CLAZZ.getValue) + + def getManagerService = managerService +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml new file mode 100644 index 0000000000..383a4f6d4b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml @@ -0,0 +1,70 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-resource-executor + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml new file mode 100644 index 0000000000..df14b7a979 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml @@ -0,0 +1,72 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-launch + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala new file mode 100644 index 0000000000..4b8fb5de9f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala @@ -0,0 +1,98 @@ +package com.webank.wedatasphere.linkis.engineconn.launch + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.{DefaultEngineCreationContext, EngineCreationContext} +import com.webank.wedatasphere.linkis.engineconn.common.execution.EngineExecution +import com.webank.wedatasphere.linkis.engineconn.common.hook.EngineConnHook +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.util.EngineConnUtils +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.utils.EngineConnArgumentsParser +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.Environment +import com.webank.wedatasphere.linkis.manager.label.builder.factory.{LabelBuilderFactory, StdLabelBuilderFactory} +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +import scala.collection.JavaConversions._ +import scala.collection.mutable.ArrayBuffer + + +object EngineConnServer extends Logging { + + + private val engineCreationContext: EngineCreationContext = new DefaultEngineCreationContext + private val labelBuilderFactory: LabelBuilderFactory = new StdLabelBuilderFactory + + var isReady = false + + def main(args: Array[String]): Unit = { + info("<<---------------------EngineConnServer Start --------------------->>") + + Utils.tryCatch { + // 1. 封装EngineCreationContext + init(args) + info("Finished to create EngineCreationContext") + EngineConnHook.getEngineConnHooks.foreach(_.beforeCreateEngineConn(getEngineCreationContext)) + info("Finished to execute hook of beforeCreateEngineConn") + //2. 创建EngineConn + val engineConn = getEngineConnManager.createEngineConn(getEngineCreationContext) + info(s"Finished to create engineConn that type is ${engineConn.getEngineType()}") + EngineConnHook.getEngineConnHooks.foreach(_.beforeExecutionExecute(getEngineCreationContext, engineConn)) + info("Finished to execute hook of beforeExecutionExecute") + //3. 注册的executions 执行 + getEngineExecutions.foreach(_.execute(getEngineCreationContext, engineConn)) + EngineConnObject.setReady + info("Finished to execute executions") + EngineConnHook.getEngineConnHooks.foreach(_.afterExecutionExecute(getEngineCreationContext, engineConn)) + info("Finished to execute hook of afterExecutionExecute") + EngineConnHook.getEngineConnHooks.foreach(_.afterEngineServerStartSuccess(getEngineCreationContext, engineConn)) + } { t => + EngineConnHook.getEngineConnHooks.foreach(_.afterEngineServerStartFailed(getEngineCreationContext, t)) + } + + //4. 等待Executions执行完毕 + ShutdownHook.getShutdownHook.waitForStopOrError() + info("<<---------------------EngineConnServer Exit --------------------->>") + System.exit(ShutdownHook.getShutdownHook.getExitCode()) + } + + /** + * + * @param args + */ + private def init(args: Array[String]): Unit = { + val arguments = EngineConnArgumentsParser.getEngineConnArgumentsParser.parseToObj(args) + val engineConf = arguments.getEngineConnConfMap + this.engineCreationContext.setUser(engineConf.getOrElse("user", Utils.getJvmUser)) + this.engineCreationContext.setTicketId(engineConf.getOrElse("ticketId", "")) + val host = CommonVars(Environment.ECM_HOST.toString, "127.0.0.1").getValue + val port = CommonVars(Environment.ECM_PORT.toString, "80").getValue + this.engineCreationContext.setEMInstance(ServiceInstance(GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue, s"$host:$port")) + val labels = new ArrayBuffer[Label[_]] + val labelArgs = engineConf.filter(_._1.startsWith(EngineConnArgumentsParser.LABEL_PREFIX)) + if (labelArgs.nonEmpty) { + labelArgs.foreach { case (key, value) => + labels += labelBuilderFactory.createLabel[Label[_]](key.replace(EngineConnArgumentsParser.LABEL_PREFIX, ""), value) + } + engineCreationContext.setLabels(labels.toList) + } + val jMap = new java.util.HashMap[String, String](engineConf.size) + jMap.putAll(engineConf) + this.engineCreationContext.setOptions(jMap) + this.engineCreationContext.setArgs(args) + EngineConnObject.setEngineCreationContext(this.engineCreationContext) + info("Finished to init engineCreationContext" + EngineConnUtils.GSON.toJson(engineCreationContext)) + } + + def getEngineCreationContext: EngineCreationContext = this.engineCreationContext + + private def getEngineConnManager: EngineConnManager = EngineConnManager.getEngineConnManager + + private def getEngineExecutions: Array[EngineExecution] = EngineExecution.getEngineExecutions + + private def getShutdownHook: ShutdownHook = ShutdownHook.getShutdownHook + +} diff --git a/linkis-computation-governance/linkis-engineconn/pom.xml b/linkis-computation-governance/linkis-engineconn/pom.xml new file mode 100644 index 0000000000..07d1c6d4a0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/pom.xml @@ -0,0 +1,42 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-engineconn + pom + + linkis-engineconn-common + linkis-engineconn-core + linkis-engineconn-executor/executor-core + linkis-engineconn-launch + linkis-engineconn-executor/accessible-executor + linkis-engineconn-executor/resource-executor + linkis-engineconn-executor/callback-service + linkis-computation-engineconn + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/pom.xml b/linkis-computation-governance/linkis-entrance-client/pom.xml new file mode 100644 index 0000000000..e88dff6d64 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/pom.xml @@ -0,0 +1,73 @@ + + + + + 4.0.0 + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + linkis-entrance-client + + + + com.webank.wedatasphere.linkis + linkis-entrance + ${linkis.version} + + + com.webank.wedatasphere.linkis + linkis-io-entrance + + + + + com.webank.wedatasphere.linkis + linkis-rpc + ${linkis.version} + provided + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + + \ No newline at end of file diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java index 06c3415bb1..231eca71f5 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineBuilderBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java index daf155ebd0..98f3c0f3fd 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineRequesterBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java index 6bf9968452..6a51a80923 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineSelectorBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java index daf074b80a..94a0735f51 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEntranceParserBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java index be9f298ff4..9f1d949062 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientGroupFactoryBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java index 4ac97bece0..6b7a58f2c1 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientInterceptorsBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java index 5a606c0290..f327db1982 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = DefaultEntranceClientBeanAnnotation.BEAN_NAME) diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java new file mode 100644 index 0000000000..ac0fbb3c3c --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java @@ -0,0 +1,97 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.conf; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import com.webank.wedatasphere.linkis.common.conf.CommonVars; +import com.webank.wedatasphere.linkis.entrance.conf.EntranceSpringConfiguration; +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext; +import com.webank.wedatasphere.linkis.entranceclient.EntranceClient; +import com.webank.wedatasphere.linkis.entranceclient.EntranceClientImpl; +import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEntranceParserBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientInterceptorsBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.annotation.DefaultEntranceClientBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.context.ClientEntranceParser; +import com.webank.wedatasphere.linkis.rpc.RPCReceiveRestful; +import com.webank.wedatasphere.linkis.rpc.conf.RPCConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +@AutoConfigureBefore({EntranceSpringConfiguration.class, RPCReceiveRestful.class}) +class ClientSpringConfiguration { + + private Logger logger = LoggerFactory.getLogger(getClass()); + + { + logger.info("start a multi-entrance application..."); + } + + @ClientEntranceParserBeanAnnotation + @ConditionalOnMissingBean(name = {ClientEntranceParserBeanAnnotation.BEAN_NAME}) + public ClientEntranceParser generateClientEntranceParser() { + return new ClientEntranceParser(); + } + + + @ClientInterceptorsBeanAnnotation + @ConditionalOnMissingBean(name = {ClientInterceptorsBeanAnnotation.BEAN_NAME}) + public EntranceInterceptor[] generateEntranceInterceptor() { + return new EntranceInterceptor[0]; + } + + + @DefaultEntranceClientBeanAnnotation + @Conditional(MultiEntranceCondition.class) + public EntranceClient generateEntranceClient(@ClientEntranceParserBeanAnnotation.ClientEntranceParserAutowiredAnnotation ClientEntranceParser clientEntranceParser, + @ClientInterceptorsBeanAnnotation.ClientInterceptorsAutowiredAnnotation EntranceInterceptor[] clientInterceptors, + @Autowired EntranceSchedulerContext entranceSchedulerContext) { + logger.warn("try to check the rpc receiver consumer threadPool..."); + setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY_FOR_CLIENT()); + setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX_FOR_CLIENT()); + EntranceClientImpl client = EntranceClientImpl.apply(ClientConfiguration.CLIENT_DEFAULT_NAME()); + logger.warn("Multi-entrance application is ready to initial EntranceClient " + client.getEntranceClientName()); + client.init(clientEntranceParser, entranceSchedulerContext, clientInterceptors, ClientConfiguration.CLIENT_DEFAULT_PARALLELISM_USERS().getValue()); + return client; + } + +// @EventListener +// public void onApplicationStarting(ApplicationStartingEvent applicationStartingEvent) { +// if(MultiEntranceCondition.isMultiEntranceApplication()) { +// logger.warn("start a multi-entrance application, now try to check the rpc receiver consumer threadPool..."); +// setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY_FOR_CLIENT()); +// setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX_FOR_CLIENT()); +// setClientValue(EntranceConfiguration.CONCURRENT_ENGINE_MAX_PARALLELISM(), ClientConfiguration.CONCURRENT_ENGINE_MAX_PARALLELISM_FOR_CLIENT()); +// } +// } + + private void setClientValue(CommonVars> fromConf, CommonVars toConf) { + int queueSize = Integer.parseInt(fromConf.getValue().toString()); + int queueSizeValue = toConf.getValue(); + if (queueSize < queueSizeValue) { + String key = fromConf.key(); + DataWorkCloudApplication.setProperty(key, String.valueOf(queueSizeValue)); + logger.warn("Multi-entrance application set " + key + "=" + queueSizeValue); + } + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories b/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..715812457a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.webank.wedatasphere.linkis.entranceclient.conf.ClientForEntranceSpringConfiguration,\ +com.webank.wedatasphere.linkis.entranceclient.conf.ClientSpringConfiguration \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala index cb3d225d3e..f4a4ce35c8 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient import com.webank.wedatasphere.linkis.entranceclient.conf.ClientConfiguration.{CLIENT_ENGINE_MANAGER_SPRING_APPLICATION_NAME, CLIENT_ENGINE_SPRING_APPLICATION_NAME} -/** - * Created by johnnwang on 2019/1/22. - */ trait EngineApplicationNameFactory { private var engineApplicationName: String = CLIENT_ENGINE_SPRING_APPLICATION_NAME.getValue diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala similarity index 96% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala index ef47c59060..d0cd9fb041 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient import com.webank.wedatasphere.linkis.entranceclient.execute.ClientJob -/** - * Created by johnnwang on 2019/1/22. - */ trait EntranceClient { def getEntranceClientName: String diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala new file mode 100644 index 0000000000..fe4923a63f --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala @@ -0,0 +1,131 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.context.DefaultEntranceContext +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext +import com.webank.wedatasphere.linkis.entrance.server.DefaultEntranceServer +import com.webank.wedatasphere.linkis.entrance.{EntranceContext, EntranceServer} +import com.webank.wedatasphere.linkis.entranceclient.execute._ +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +class EntranceClientImpl private() extends EntranceClient with EngineApplicationNameFactory + with EngineManagerApplicationNameFactory with Logging { + + private var entranceServer: EntranceServer = _ + private var clientName: String = _ + + + def setClientName(clientName: String): Unit = this.clientName = clientName + + + def init(entranceServer: EntranceServer): Unit = { + this.entranceServer = entranceServer + } + + def init(entranceContext: EntranceContext): Unit = init(new DefaultEntranceServer(entranceContext)) + + def init(clientEntranceParser: context.ClientEntranceParser, schedulerContext: EntranceSchedulerContext, interceptors: Array[EntranceInterceptor], + maxParallelismUsers: Int): Unit = if (entranceServer == null) synchronized { + if (entranceServer == null) { + val scheduler = new ParallelScheduler(schedulerContext) + scheduler.init() + scheduler.start() + val entranceContext = new DefaultEntranceContext(clientEntranceParser, new context.ClientPersistenceManager, new context.ClientLogManager, + scheduler, interceptors, null, Array.empty) + init(entranceContext) + } + } + + private def executeUntil[T](code: String, user: String, creator: String, + params: java.util.Map[String, Any], op: ClientJob => T): T = { + val execId = executeJob(code, user, creator, params) + entranceServer.getJob(execId).foreach { + case job: ClientJob => + job.waitForComplete() + return op(job) + } + throw new EntranceErrorException(50003, s"execute failed, cannot find the job $execId.") + } + + override def getEntranceClientName: String = if(StringUtils.isNotEmpty(clientName)) clientName else entranceServer.getName + + override def execute(code: String, user: String, creator: String): Boolean = execute(code, user, creator, null) + + override def execute(code: String, user: String, creator: String, + params: java.util.Map[String, Any]): Boolean = + executeUntil(code, user, creator, params, job => + if (job.isSucceed) true else false) + + override def executeJob(code: String, user: String, creator: String): String = executeJob(code, user, creator, null) + + override def executeJob(code: String, user: String, creator: String, params: util.Map[String, Any]): String = { + val requestMap = new JMap[String, Any] + requestMap.put(TaskConstant.EXECUTIONCODE, code) + requestMap.put(TaskConstant.UMUSER, user) + requestMap.put(TaskConstant.REQUESTAPPLICATIONNAME, creator) + if(params != null && !params.isEmpty) { + if(params.containsKey(EntranceServer.DO_NOT_PRINT_PARAMS_LOG)) { + requestMap.put(EntranceServer.DO_NOT_PRINT_PARAMS_LOG, params.get(EntranceServer.DO_NOT_PRINT_PARAMS_LOG)) + params.remove(EntranceServer.DO_NOT_PRINT_PARAMS_LOG) + } + if(!params.isEmpty) requestMap.put(TaskConstant.PARAMS, params) + } + entranceServer.execute(requestMap) + } + + override def getJob(jobId: String): Option[ClientJob] = entranceServer.getJob(jobId).map { case job: ClientJob => job } + + override def executeResult(code: String, user: String, creator: String): Array[String] = + executeResult(code, user, creator, null) + + override def executeResult(code: String, user: String, creator: String, + params: java.util.Map[String, Any]): Array[String] = + executeUntil(code, user, creator, params, job => + if(job.isSucceed) job.getResultSets + else if(job.getErrorResponse != null) { + val exception = new EntranceErrorException(22001, job.getErrorResponse.message) + if(job.getErrorResponse.t != null) exception.initCause(job.getErrorResponse.t) + throw exception + } else throw new EntranceErrorException(22002, "execute failed, unknown reason.")) + +} +object EntranceClientImpl { + + private val clientNameToEntranceClient = new JMap[String, EntranceClientImpl] + + def apply(clientName: String): EntranceClientImpl = { + if(!clientNameToEntranceClient.containsKey(clientName)) synchronized { + if(!clientNameToEntranceClient.containsKey(clientName)) { + val client = new EntranceClientImpl + client.setClientName(clientName) + clientNameToEntranceClient.put(clientName, client) + } + } + clientNameToEntranceClient.get(clientName) + } + + def getClientNames = clientNameToEntranceClient.keySet() +} \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala index ad46e5caad..68e381de44 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient.conf import com.webank.wedatasphere.linkis.common.conf.CommonVars -/** - * Created by johnnwang on 2019/1/22. - */ object ClientConfiguration { val CLIENT_ENGINE_MANAGER_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.client.enginemanager.application.name.default", "IOEngineManager") diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala new file mode 100644 index 0000000000..93a0342932 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.conf + +import com.webank.wedatasphere.linkis.common.utils.Logging +//import com.webank.wedatasphere.linkis.entrance.annotation.EntranceServerBeanAnnotation.EntranceServerAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entrance.annotation._ +//import com.webank.wedatasphere.linkis.entrance.conf.EntranceSpringConfiguration +//import com.webank.wedatasphere.linkis.entrance.execute._ +//import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +//import com.webank.wedatasphere.linkis.entrance.log.LogManager +//import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +//import com.webank.wedatasphere.linkis.entrance.{EntranceParser, EntranceServer} +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEngineSelectorBeanAnnotation.ClientEngineSelectorAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEntranceParserBeanAnnotation.ClientEntranceParserAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientInterceptorsBeanAnnotation.ClientInterceptorsAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.DefaultEntranceClientBeanAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.{EntranceClient, EntranceClientImpl, _} +//import com.webank.wedatasphere.linkis.rpc.{RPCMessageEvent, Receiver, ReceiverChooser} +//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +//import org.springframework.boot.autoconfigure.{AutoConfigureAfter, AutoConfigureBefore} +//import org.springframework.context.annotation.{Conditional, Configuration} + +/*@Configuration +@AutoConfigureBefore(Array(classOf[EntranceSpringConfiguration])) +@AutoConfigureAfter(Array(classOf[ClientSpringConfiguration])) +@Conditional(Array(classOf[SingleEntranceCondition]))*/ +class ClientForEntranceSpringConfiguration extends Logging { + + warn(s"start a single-entrance application...") + + /*@DefaultEntranceClientBeanAnnotation + def generateEntranceClient(@EntranceServerAutowiredAnnotation entranceServer: EntranceServer): EntranceClient = { + val client = EntranceClientImpl(ClientConfiguration.CLIENT_DEFAULT_NAME) + warn(s"ready to initial EntranceClient ${client.getEntranceClientName}...") + client.init(entranceServer) + client + }*/ +/* + + @ReceiverChooserBeanAnnotation + def generateEntranceReceiverChooser(): ReceiverChooser = new ReceiverChooser{ + override def chooseReceiver(event: RPCMessageEvent): Option[Receiver] = None + } + + @PersistenceManagerBeanAnnotation + @ConditionalOnMissingBean(value = Array(classOf[context.ClientPersistenceManager])) + def generatePersistenceManager(): PersistenceManager = new context.ClientPersistenceManager + + @EntranceParserBeanAnnotation + def generateEntranceParser(@ClientEntranceParserAutowiredAnnotation clientEntranceParser: context.ClientEntranceParser): EntranceParser = clientEntranceParser + + @LogManagerBeanAnnotation + @ConditionalOnMissingBean(value = Array(classOf[context.ClientLogManager])) + def generateLogManager(): LogManager = new context.ClientLogManager + + + @EntranceInterceptorBeanAnnotation + def generateEntranceInterceptor(@ClientInterceptorsAutowiredAnnotation clientInterceptors: Array[EntranceInterceptor]): Array[EntranceInterceptor] = clientInterceptors +*/ + + +// @EngineSelectorBeanAnnotation +// def generateEngineSelector(@ClientEngineSelectorAutowiredAnnotation clientEngineSelector: EngineSelector): EngineSelector = clientEngineSelector + + +} \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala similarity index 86% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala index 90d1077584..f3bac7e5f0 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala @@ -18,13 +18,9 @@ package com.webank.wedatasphere.linkis.entranceclient.conf import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entranceclient -import org.apache.commons.lang.StringUtils import org.springframework.context.annotation.{Condition, ConditionContext} import org.springframework.core.`type`.AnnotatedTypeMetadata -/** - * Created by johnnwang on 2019/1/22. - */ class MultiEntranceCondition extends Condition { override def matches(conditionContext: ConditionContext, annotatedTypeMetadata: AnnotatedTypeMetadata): Boolean = entranceclient.conf.MultiEntranceCondition.isMultiEntranceApplication @@ -34,5 +30,5 @@ class SingleEntranceCondition extends Condition { !entranceclient.conf.MultiEntranceCondition.isMultiEntranceApplication } object MultiEntranceCondition { - def isMultiEntranceApplication: Boolean = StringUtils.isNotBlank(EntranceConfiguration.ENGINE_MANAGER_SPRING_APPLICATION_NAME.getValue) + def isMultiEntranceApplication: Boolean = EntranceConfiguration.MULTI_ENTRANCE_CONDITION.getValue } \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala new file mode 100644 index 0000000000..e12fcf7e49 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.context + +import java.util + +import com.webank.wedatasphere.linkis.entrance.parser.CommonEntranceParser +import com.webank.wedatasphere.linkis.entranceclient.execute +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.scheduler.queue.Job + +class ClientEntranceParser extends CommonEntranceParser { + + override def parseToTask(job: Job): Task = job match { + case j: execute.ClientJob => j.getTask + } + + override def parseToJob(task: Task): Job = { + val job = new execute.ClientJob + task match { + case t: RequestPersistTask => + job.setTask(t) + job.setCreator(t.getRequestApplicationName) + job.setUser(t.getUmUser) + if (t.getParams != null) job.setParams(t.getParams.asInstanceOf[util.Map[String, Any]]) + } + job + } +} diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala index fd15742125..1b1b4d5bc7 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala @@ -24,9 +24,6 @@ import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import org.apache.commons.io.input.NullInputStream import org.apache.commons.io.output.NullOutputStream -/** - * Created by johnnwang on 2018/10/30. - */ class ClientLogManager extends CacheLogManager { override def getLogReader(execId: String): LogReader = { new CacheLogReader("", ServerConfiguration.BDP_SERVER_ENCODING.getValue, diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala index 1f5e31d503..d69fe21aea 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala @@ -21,9 +21,6 @@ import java.lang import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceEngine import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * Created by johnnwang on 2018/10/30. - */ class ClientPersistenceEngine extends PersistenceEngine { override def persist(task: Task): Unit = {} diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala index c9254c4fb3..c8320f9a76 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala @@ -23,9 +23,6 @@ import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse import com.webank.wedatasphere.linkis.scheduler.queue.Job -/** - * Created by johnnwang on 2018/10/30. - */ class ClientPersistenceManager extends PersistenceManager { private val persistenceEngine = new ClientPersistenceEngine override def getEntranceContext: EntranceContext = null diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala similarity index 100% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala similarity index 80% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala index 58332dad65..23834cf411 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala @@ -17,27 +17,25 @@ package com.webank.wedatasphere.linkis.entranceclient.execute import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob -import com.webank.wedatasphere.linkis.entranceclient.context.ClientTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.scheduler.executer.{ExecuteRequest, JobExecuteRequest} import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState.SchedulerEventState import com.webank.wedatasphere.linkis.scheduler.queue.{JobInfo, SchedulerEventState} import scala.collection.mutable.ArrayBuffer -/** - * Created by johnnwang on 2018/10/30. - */ class ClientJob extends EntranceJob { private val resultSets = ArrayBuffer[String]() def addResultSet(resultSet: String): Unit = resultSets += resultSet + def getResultSets: Array[String] = resultSets.toArray def waitForComplete(): Unit = { - if(SchedulerEventState.isCompleted(this.getState)) return + if (SchedulerEventState.isCompleted(this.getState)) return resultSets synchronized { - while(!SchedulerEventState.isCompleted(this.getState)) resultSets.wait() + while (!SchedulerEventState.isCompleted(this.getState)) resultSets.wait() } } @@ -51,11 +49,11 @@ class ClientJob extends EntranceJob { override def init(): Unit = {} override protected def jobToExecuteRequest: ExecuteRequest = new ExecuteRequest with JobExecuteRequest { - override val code: String = getTask.asInstanceOf[ClientTask].getCode + override val code: String = getTask.asInstanceOf[RequestPersistTask].getCode override val jobId: String = getId } - override def getName: String = getTask.asInstanceOf[ClientTask].getCreator + "_" + getTask.asInstanceOf[ClientTask].getUser + "_" + getId + override def getName: String = getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName + "_" + getTask.asInstanceOf[RequestPersistTask].getUmUser + "_" + getId override def getJobInfo: JobInfo = null diff --git a/linkis-computation-governance/linkis-entrance/pom.xml b/linkis-computation-governance/linkis-entrance/pom.xml new file mode 100644 index 0000000000..c9e6678a1e --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/pom.xml @@ -0,0 +1,142 @@ + + + + + 4.0.0 + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + linkis-entrance + + + + com.webank.wedatasphere.linkis + linkis-scheduler + ${linkis.version} + + + com.webank.wedatasphere.linkis + linkis-common + + + + + + com.webank.wedatasphere.linkis + linkis-rpc + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-cs-engine-support + ${linkis.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + provided + + + + junit + junit + 4.12 + test + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-orchestrator-ecm-plugin + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + false + + + make-assembly + package + + single + + + + src/main/assembly/distribution.xml + + + + + + false + out + false + false + + src/main/assembly/distribution.xml + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml b/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml new file mode 100644 index 0000000000..6781dc2891 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml @@ -0,0 +1,319 @@ + + + + linkis-ujes-spark-entrance + + dir + zip + + false + linkis-ujes-linkis-entrance + + + + + + lib + true + true + false + false + true + + + antlr:antlr:jar + aopalliance:aopalliance:jar + asm:asm:jar + cglib:cglib:jar + com.amazonaws:aws-java-sdk-autoscaling:jar + com.amazonaws:aws-java-sdk-core:jar + com.amazonaws:aws-java-sdk-ec2:jar + com.amazonaws:aws-java-sdk-route53:jar + com.amazonaws:aws-java-sdk-sts:jar + com.amazonaws:jmespath-java:jar + com.fasterxml.jackson.core:jackson-annotations:jar + com.fasterxml.jackson.core:jackson-core:jar + com.fasterxml.jackson.core:jackson-databind:jar + com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:jar + com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar + com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar + com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:jar + com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar + com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar + com.fasterxml.jackson.module:jackson-module-parameter-names:jar + com.fasterxml.jackson.module:jackson-module-paranamer:jar + com.fasterxml.jackson.module:jackson-module-scala_2.11:jar + com.github.andrewoma.dexx:dexx-collections:jar + com.github.vlsi.compactmap:compactmap:jar + com.google.code.findbugs:annotations:jar + com.google.code.findbugs:jsr305:jar + com.google.code.gson:gson:jar + com.google.guava:guava:jar + com.google.inject:guice:jar + com.google.protobuf:protobuf-java:jar + com.netflix.archaius:archaius-core:jar + com.netflix.eureka:eureka-client:jar + com.netflix.eureka:eureka-core:jar + com.netflix.hystrix:hystrix-core:jar + com.netflix.netflix-commons:netflix-commons-util:jar + com.netflix.netflix-commons:netflix-eventbus:jar + com.netflix.netflix-commons:netflix-infix:jar + com.netflix.netflix-commons:netflix-statistics:jar + com.netflix.ribbon:ribbon:jar + com.netflix.ribbon:ribbon-core:jar + com.netflix.ribbon:ribbon-eureka:jar + com.netflix.ribbon:ribbon-httpclient:jar + com.netflix.ribbon:ribbon-loadbalancer:jar + com.netflix.ribbon:ribbon-transport:jar + com.netflix.servo:servo-core:jar + com.ning:async-http-client:jar + com.sun.jersey.contribs:jersey-apache-client4:jar + com.sun.jersey:jersey-client:jar + com.sun.jersey:jersey-core:jar + com.sun.jersey:jersey-json:jar + com.sun.jersey:jersey-server:jar + com.sun.jersey:jersey-servlet:jar + com.sun.xml.bind:jaxb-impl:jar + com.thoughtworks.paranamer:paranamer:jar + com.thoughtworks.xstream:xstream:jar + com.webank.wedatasphere.linkis:linkis-common:jar + com.webank.wedatasphere.linkis:linkis-module:jar + commons-beanutils:commons-beanutils:jar + commons-beanutils:commons-beanutils-core:jar + commons-cli:commons-cli:jar + commons-codec:commons-codec:jar + commons-collections:commons-collections:jar + commons-configuration:commons-configuration:jar + commons-daemon:commons-daemon:jar + commons-dbcp:commons-dbcp:jar + commons-digester:commons-digester:jar + commons-httpclient:commons-httpclient:jar + commons-io:commons-io:jar + commons-jxpath:commons-jxpath:jar + commons-lang:commons-lang:jar + commons-logging:commons-logging:jar + commons-net:commons-net:jar + commons-pool:commons-pool:jar + io.micrometer:micrometer-core:jar + io.netty:netty:jar + io.netty:netty-all:jar + io.netty:netty-buffer:jar + io.netty:netty-codec:jar + io.netty:netty-codec-http:jar + io.netty:netty-common:jar + io.netty:netty-handler:jar + io.netty:netty-transport:jar + io.netty:netty-transport-native-epoll:jar + io.reactivex:rxjava:jar + io.reactivex:rxnetty:jar + io.reactivex:rxnetty-contexts:jar + io.reactivex:rxnetty-servo:jar + javax.activation:activation:jar + javax.annotation:javax.annotation-api:jar + javax.inject:javax.inject:jar + javax.servlet:javax.servlet-api:jar + javax.servlet.jsp:jsp-api:jar + javax.validation:validation-api:jar + javax.websocket:javax.websocket-api:jar + javax.ws.rs:javax.ws.rs-api:jar + javax.xml.bind:jaxb-api:jar + javax.xml.stream:stax-api:jar + joda-time:joda-time:jar + log4j:log4j:jar + mysql:mysql-connector-java:jar + net.databinder.dispatch:dispatch-core_2.11:jar + net.databinder.dispatch:dispatch-json4s-jackson_2.11:jar + org.antlr:antlr-runtime:jar + org.antlr:stringtemplate:jar + org.apache.commons:commons-compress:jar + org.apache.commons:commons-math:jar + org.apache.commons:commons-math3:jar + org.apache.curator:curator-client:jar + org.apache.curator:curator-framework:jar + org.apache.curator:curator-recipes:jar + org.apache.directory.api:api-asn1-api:jar + org.apache.directory.api:api-util:jar + org.apache.directory.server:apacheds-i18n:jar + org.apache.directory.server:apacheds-kerberos-codec:jar + org.apache.hadoop:hadoop-annotations:jar + org.apache.hadoop:hadoop-auth:jar + org.apache.hadoop:hadoop-common:jar + org.apache.hadoop:hadoop-hdfs:jar + org.apache.htrace:htrace-core:jar + org.apache.httpcomponents:httpclient:jar + org.apache.httpcomponents:httpcore:jar + org.apache.logging.log4j:log4j-api:jar + org.apache.logging.log4j:log4j-core:jar + org.apache.logging.log4j:log4j-jul:jar + org.apache.logging.log4j:log4j-slf4j-impl:jar + org.apache.zookeeper:zookeeper:jar + org.aspectj:aspectjweaver:jar + org.bouncycastle:bcpkix-jdk15on:jar + org.bouncycastle:bcprov-jdk15on:jar + org.codehaus.jackson:jackson-jaxrs:jar + org.codehaus.jackson:jackson-xc:jar + org.codehaus.jettison:jettison:jar + org.codehaus.woodstox:stax2-api:jar + org.codehaus.woodstox:woodstox-core-asl:jar + org.eclipse.jetty:jetty-annotations:jar + org.eclipse.jetty:jetty-client:jar + org.eclipse.jetty:jetty-continuation:jar + org.eclipse.jetty:jetty-http:jar + org.eclipse.jetty:jetty-io:jar + org.eclipse.jetty:jetty-jndi:jar + org.eclipse.jetty:jetty-plus:jar + org.eclipse.jetty:jetty-security:jar + org.eclipse.jetty:jetty-server:jar + org.eclipse.jetty:jetty-servlet:jar + org.eclipse.jetty:jetty-servlets:jar + org.eclipse.jetty:jetty-util:jar + org.eclipse.jetty:jetty-webapp:jar + org.eclipse.jetty:jetty-xml:jar + org.eclipse.jetty.websocket:javax-websocket-client-impl:jar + org.eclipse.jetty.websocket:javax-websocket-server-impl:jar + org.eclipse.jetty.websocket:websocket-api:jar + org.eclipse.jetty.websocket:websocket-client:jar + org.eclipse.jetty.websocket:websocket-common:jar + org.eclipse.jetty.websocket:websocket-server:jar + org.eclipse.jetty.websocket:websocket-servlet:jar + org.fusesource.leveldbjni:leveldbjni-all:jar + org.glassfish.hk2:class-model:jar + org.glassfish.hk2:config-types:jar + org.glassfish.hk2.external:aopalliance-repackaged:jar + org.glassfish.hk2.external:asm-all-repackaged:jar + org.glassfish.hk2.external:bean-validator:jar + org.glassfish.hk2.external:javax.inject:jar + org.glassfish.hk2:hk2:jar + org.glassfish.hk2:hk2-api:jar + org.glassfish.hk2:hk2-config:jar + org.glassfish.hk2:hk2-core:jar + org.glassfish.hk2:hk2-locator:jar + org.glassfish.hk2:hk2-runlevel:jar + org.glassfish.hk2:hk2-utils:jar + org.glassfish.hk2:osgi-resource-locator:jar + org.glassfish.hk2:spring-bridge:jar + org.glassfish.jersey.bundles:jaxrs-ri:jar + org.glassfish.jersey.bundles.repackaged:jersey-guava:jar + org.glassfish.jersey.containers:jersey-container-servlet:jar + org.glassfish.jersey.containers:jersey-container-servlet-core:jar + org.glassfish.jersey.core:jersey-client:jar + org.glassfish.jersey.core:jersey-common:jar + org.glassfish.jersey.core:jersey-server:jar + org.glassfish.jersey.ext:jersey-entity-filtering:jar + org.glassfish.jersey.ext:jersey-spring3:jar + org.glassfish.jersey.media:jersey-media-jaxb:jar + org.glassfish.jersey.media:jersey-media-json-jackson:jar + org.glassfish.jersey.media:jersey-media-multipart:jar + org.hdrhistogram:HdrHistogram:jar + org.javassist:javassist:jar + org.json4s:json4s-ast_2.11:jar + org.json4s:json4s-core_2.11:jar + org.json4s:json4s-jackson_2.11:jar + org.jsoup:jsoup:jar + org.jvnet.mimepull:mimepull:jar + org.jvnet:tiger-types:jar + org.latencyutils:LatencyUtils:jar + org.mortbay.jasper:apache-el:jar + org.mortbay.jetty:jetty:jar + org.mortbay.jetty:jetty-util:jar + org.ow2.asm:asm-analysis:jar + org.ow2.asm:asm-commons:jar + org.ow2.asm:asm-tree:jar + org.reflections:reflections:jar + org.scala-lang.modules:scala-parser-combinators_2.11:jar + org.scala-lang.modules:scala-xml_2.11:jar + org.scala-lang:scala-compiler:jar + org.scala-lang:scala-library:jar + org.scala-lang:scala-reflect:jar + org.scala-lang:scalap:jar + org.slf4j:jul-to-slf4j:jar + org.slf4j:slf4j-api:jar + org.springframework.boot:spring-boot:jar + org.springframework.boot:spring-boot-actuator:jar + org.springframework.boot:spring-boot-actuator-autoconfigure:jar + org.springframework.boot:spring-boot-autoconfigure:jar + org.springframework.boot:spring-boot-starter:jar + org.springframework.boot:spring-boot-starter-actuator:jar + org.springframework.boot:spring-boot-starter-aop:jar + org.springframework.boot:spring-boot-starter-jetty:jar + org.springframework.boot:spring-boot-starter-json:jar + org.springframework.boot:spring-boot-starter-log4j2:jar + org.springframework.boot:spring-boot-starter-web:jar + org.springframework.cloud:spring-cloud-commons:jar + org.springframework.cloud:spring-cloud-config-client:jar + org.springframework.cloud:spring-cloud-context:jar + org.springframework.cloud:spring-cloud-netflix-archaius:jar + org.springframework.cloud:spring-cloud-netflix-core:jar + org.springframework.cloud:spring-cloud-netflix-eureka-client:jar + org.springframework.cloud:spring-cloud-netflix-ribbon:jar + org.springframework.cloud:spring-cloud-starter:jar + org.springframework.cloud:spring-cloud-starter-config:jar + org.springframework.cloud:spring-cloud-starter-eureka:jar + org.springframework.cloud:spring-cloud-starter-netflix-archaius:jar + org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:jar + org.springframework.cloud:spring-cloud-starter-netflix-ribbon:jar + org.springframework.security:spring-security-crypto:jar + org.springframework.security:spring-security-rsa:jar + org.springframework:spring-aop:jar + org.springframework:spring-beans:jar + org.springframework:spring-context:jar + org.springframework:spring-core:jar + org.springframework:spring-expression:jar + org.springframework:spring-jcl:jar + org.springframework:spring-web:jar + org.springframework:spring-webmvc:jar + org.tukaani:xz:jar + org.yaml:snakeyaml:jar + software.amazon.ion:ion-java:jar + xerces:xercesImpl:jar + xmlenc:xmlenc:jar + xmlpull:xmlpull:jar + xpp3:xpp3_min:jar + + + + + + + ${basedir}/src/main/resources + + * + + 0777 + conf + unix + + + + + + diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java new file mode 100644 index 0000000000..ac80d687bb --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + + +public class LinkisEntranceApplication { + + private static final Log logger = LogFactory.getLog(DataWorkCloudApplication.class); + + public static void main(String[] args) throws ReflectiveOperationException { + logger.info("Start to running LinkisManagerApplication"); + DataWorkCloudApplication.main(args); + } +} diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java similarity index 97% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java index 902733be5f..38659f6e1f 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java @@ -35,7 +35,7 @@ @Bean(value = EntranceExecutorManagerBeanAnnotation.BEAN_NAME) @Component(value = EntranceExecutorManagerBeanAnnotation.BEAN_NAME) public @interface EntranceExecutorManagerBeanAnnotation { - String BEAN_NAME = "entranceExecutorManager"; + String BEAN_NAME = "executorManager"; @AliasFor(annotation = Component.class) String value() default BEAN_NAME; diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java similarity index 84% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java index 360e8ffa1f..d9e27e299c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,15 +13,15 @@ package com.webank.wedatasphere.linkis.entrance.conf; -import com.webank.wedatasphere.linkis.entrance.EntranceContext; import com.webank.wedatasphere.linkis.entrance.EntranceParser; +import com.webank.wedatasphere.linkis.entrance.EntranceServer; import com.webank.wedatasphere.linkis.entrance.annotation.*; import com.webank.wedatasphere.linkis.entrance.background.BackGroundService; import com.webank.wedatasphere.linkis.entrance.event.EntranceEvent; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListener; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListenerBus; -import com.webank.wedatasphere.linkis.entrance.execute.*; -import com.webank.wedatasphere.linkis.entrance.execute.impl.*; +import com.webank.wedatasphere.linkis.entrance.execute.EntranceExecutionService; +import com.webank.wedatasphere.linkis.entrance.execute.impl.EntranceExecutorManagerImpl; import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; import com.webank.wedatasphere.linkis.entrance.interceptor.impl.*; import com.webank.wedatasphere.linkis.entrance.log.*; @@ -32,26 +29,29 @@ import com.webank.wedatasphere.linkis.entrance.persistence.*; import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceGroupFactory; import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext; -import com.webank.wedatasphere.linkis.rpc.ReceiverChooser; +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManagerBuilder; +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManagerBuilder$; +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Policy; import com.webank.wedatasphere.linkis.scheduler.Scheduler; import com.webank.wedatasphere.linkis.scheduler.SchedulerContext; +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorManager; import com.webank.wedatasphere.linkis.scheduler.queue.ConsumerManager; import com.webank.wedatasphere.linkis.scheduler.queue.GroupFactory; import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelConsumerManager; import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Configuration; import static com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration.ENTRANCE_SCHEDULER_MAX_PARALLELISM_USERS; /** - * created by enjoyyin on 2018/10/16 * Description:This configuration class is used to generate some singleton classes in the entity module.(该配置类用于生成entrance模块中的一些单例类) */ @Configuration +@AutoConfigureBefore({EntranceServer.class, EntranceExecutionService.class}) public class EntranceSpringConfiguration { private Logger logger = LoggerFactory.getLogger(getClass()); @@ -59,11 +59,7 @@ public class EntranceSpringConfiguration { logger.info("load the ujes-entrance spring configuration."); } - @EntranceParserBeanAnnotation - @ConditionalOnMissingBean(name = {EntranceParserBeanAnnotation.BEAN_NAME}) - public EntranceParser generateEntranceParser(){ - return new CommonEntranceParser(); - } + @PersistenceEngineBeanAnnotation @ConditionalOnMissingBean(name = {PersistenceEngineBeanAnnotation.BEAN_NAME}) @@ -81,12 +77,18 @@ public ResultSetEngine generateResultSetEngine(){ @ConditionalOnMissingBean(name = {PersistenceManagerBeanAnnotation.BEAN_NAME}) public PersistenceManager generatePersistenceManager(@PersistenceEngineBeanAnnotation.PersistenceEngineAutowiredAnnotation PersistenceEngine persistenceEngine, @ResultSetEngineBeanAnnotation.ResultSetEngineAutowiredAnnotation ResultSetEngine resultSetEngine){ + logger.info("init PersistenceManager."); QueryPersistenceManager persistenceManager = new QueryPersistenceManager(); persistenceManager.setPersistenceEngine(persistenceEngine); persistenceManager.setResultSetEngine(resultSetEngine); return persistenceManager; } + @EntranceParserBeanAnnotation + @ConditionalOnMissingBean(name = {EntranceParserBeanAnnotation.BEAN_NAME}) + public EntranceParser generateEntranceParser(){ + return new CommonEntranceParser(); + } @EntranceListenerBusBeanAnnotation @ConditionalOnMissingBean(name = {EntranceListenerBusBeanAnnotation.BEAN_NAME}) @@ -104,7 +106,7 @@ public EntranceEventListenerBus generateEn @EntranceInterceptorBeanAnnotation @ConditionalOnMissingBean(name = {EntranceInterceptorBeanAnnotation.BEAN_NAME}) public EntranceInterceptor[] generateEntranceInterceptors() { - return new EntranceInterceptor[]{new CSEntranceInterceptor(), new PythonCodeCheckInterceptor(), new DBInfoCompleteInterceptor(), new SparkCodeCheckInterceptor(), + return new EntranceInterceptor[]{new CSEntranceInterceptor(), new PythonCodeCheckInterceptor(), new DBInfoCompleteInterceptor(), new SparkCodeCheckInterceptor(), new SQLCodeCheckInterceptor(), new VarSubstitutionInterceptor(), new LogPathCreateInterceptor(), new StorePathEntranceInterceptor(), new ScalaCodeInterceptor(), new SQLLimitEntranceInterceptor(), new CommentInterceptor(), }; @@ -152,18 +154,18 @@ public ConsumerManager generateConsumerManager(){ @SchedulerContextBeanAnnotation @ConditionalOnMissingBean(name = {SchedulerContextBeanAnnotation.BEAN_NAME}) public SchedulerContext generateSchedulerContext(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory, - @EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation EntranceExecutorManager executorManager, + @EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation ExecutorManager executorManager, @ConsumerManagerBeanAnnotation.ConsumerManagerAutowiredAnnotation ConsumerManager consumerManager) { return new EntranceSchedulerContext(groupFactory, consumerManager, executorManager); } - @EngineRequesterBeanAnnotation + /* @EngineRequesterBeanAnnotation @ConditionalOnMissingBean(name = {EngineRequesterBeanAnnotation.BEAN_NAME}) public EngineRequester generateEngineRequester(){ return new EngineRequesterImpl(); } - - @EngineSelectorBeanAnnotation +*/ + /* @EngineSelectorBeanAnnotation @ConditionalOnMissingBean(name = {EngineSelectorBeanAnnotation.BEAN_NAME}) public EngineSelector generateEngineSelector(@EntranceListenerBusBeanAnnotation.EntranceListenerBusAutowiredAnnotation EntranceEventListenerBus entranceEventListenerBus) { @@ -171,8 +173,8 @@ public EngineSelector generateEngineSelector(@EntranceListenerBusBeanAnnotation. singleEngineSelector.setEntranceEventListenerBus(entranceEventListenerBus); return singleEngineSelector; } - - @EngineBuilderBeanAnnotation +*/ + /*@EngineBuilderBeanAnnotation @ConditionalOnMissingBean(name = {EngineBuilderBeanAnnotation.BEAN_NAME}) public EngineBuilder generateEngineBuilder(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory) { return new AbstractEngineBuilder(groupFactory) { @@ -181,49 +183,39 @@ public EntranceEngine createEngine(long id) { return new SingleEntranceEngine(id); } }; - } + }*/ - @EngineManagerBeanAnnotation + /* @EngineManagerBeanAnnotation @ConditionalOnMissingBean(name = {EngineManagerBeanAnnotation.BEAN_NAME}) public EngineManager generateEngineManager() { return new EngineManagerImpl(); - } + }*/ @EntranceExecutorManagerBeanAnnotation @ConditionalOnMissingBean(name = {EntranceExecutorManagerBeanAnnotation.BEAN_NAME}) - public EntranceExecutorManager generateExecutorManager(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory, - @EngineBuilderBeanAnnotation.EngineBuilderAutowiredAnnotation EngineBuilder engineBuilder, - @EngineRequesterBeanAnnotation.EngineRequesterAutowiredAnnotation EngineRequester engineRequester, - @EngineSelectorBeanAnnotation.EngineSelectorAutowiredAnnotation EngineSelector engineSelector, - @EngineManagerBeanAnnotation.EngineManagerAutowiredAnnotation EngineManager engineManager, - @Autowired EntranceExecutorRuler[] entranceExecutorRulers){ - return new EntranceExecutorManagerImpl(groupFactory, engineBuilder, - engineRequester, engineSelector, engineManager, entranceExecutorRulers); + public ExecutorManager generateExecutorManager(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory) { + EngineConnManagerBuilder engineConnManagerBuilder = EngineConnManagerBuilder$.MODULE$.builder(); + engineConnManagerBuilder.setPolicy(Policy.Process); + return new EntranceExecutorManagerImpl(groupFactory, engineConnManagerBuilder.build()); } @SchedulerBeanAnnotation @ConditionalOnMissingBean(name = {SchedulerBeanAnnotation.BEAN_NAME}) - public Scheduler generateScheduler(@SchedulerContextBeanAnnotation.SchedulerContextAutowiredAnnotation SchedulerContext schedulerContext){ + public Scheduler generateScheduler(@SchedulerContextBeanAnnotation.SchedulerContextAutowiredAnnotation SchedulerContext schedulerContext) { Scheduler scheduler = new ParallelScheduler(schedulerContext); scheduler.init(); scheduler.start(); return scheduler; } - @ReceiverChooserBeanAnnotation - @ConditionalOnMissingBean(name = {ReceiverChooserBeanAnnotation.BEAN_NAME}) - public ReceiverChooser generateEntranceReceiverChooser(@EntranceContextBeanAnnotation.EntranceContextAutowiredAnnotation - EntranceContext entranceContext) { - return new EntranceReceiverChooser(entranceContext); - } @BackGroundServiceBeanAnnotation @ConditionalOnMissingBean(name = {BackGroundServiceBeanAnnotation.BEAN_NAME}) - public BackGroundService[] generateBackGroundService(){ + public BackGroundService[] generateBackGroundService() { return new BackGroundService[]{}; } - @NewEngineBroadcastListenerBeanAnnotation + /* @NewEngineBroadcastListenerBeanAnnotation @ConditionalOnMissingBean(name = {NewEngineBroadcastListenerBeanAnnotation.BEAN_NAME}) public NewEngineBroadcastListener generateNewEngineBroadcastListener(@EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation EntranceExecutorManager entranceExecutorManager) { @@ -239,5 +231,5 @@ public ResponseEngineStatusChangedBroadcastListener generateResponseEngineStatus ResponseEngineStatusChangedBroadcastListener broadcastListener = new ResponseEngineStatusChangedBroadcastListener(); broadcastListener.setEntranceExecutorManager(entranceExecutorManager); return broadcastListener; - } + }*/ } diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java index e0ad6babb9..7bb61e9f0c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java @@ -29,16 +29,18 @@ import com.webank.wedatasphere.linkis.entrance.event.EntranceEvent; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListener; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListenerBus; -import com.webank.wedatasphere.linkis.entrance.execute.EntranceExecutorManager; import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; import com.webank.wedatasphere.linkis.entrance.log.LogManager; import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager; import com.webank.wedatasphere.linkis.scheduler.Scheduler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; @EntranceContextBeanAnnotation public class DefaultEntranceContext extends EntranceContext { + private static Logger logger = LoggerFactory.getLogger(DefaultEntranceContext.class); @EntranceParserBeanAnnotation.EntranceParserAutowiredAnnotation private EntranceParser entranceParser; @@ -79,11 +81,12 @@ public DefaultEntranceContext() { @PostConstruct public void init() { entranceParser.setEntranceContext(this); + logger.info("Finished init entranceParser from postConstruct end!"); persistenceManager.setEntranceContext(this); logManager.setEntranceContext(this); - if(scheduler.getSchedulerContext().getOrCreateExecutorManager() instanceof EntranceExecutorManager) { + /* if(scheduler.getSchedulerContext().getOrCreateExecutorManager() instanceof EntranceExecutorManager) { listenerBus.addListener(((EntranceExecutorManager) scheduler.getSchedulerContext().getOrCreateExecutorManager()).getOrCreateEngineManager()); - } + }*/ } @Override diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java similarity index 86% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java index dbf48ab111..e6b144283d 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java @@ -27,7 +27,10 @@ public enum EntranceErrorCode { * */ CACHE_NOT_READY(200, "shared cache not ready"), - ENTRANCE_CAST_FAIL(20002, "class cast failed") + ENTRANCE_CAST_FAIL(20002, "class cast failed"), + PARAM_CANNOT_EMPTY(20008, "params cannot be empty "), + LABEL_PARAMS_INVALID(20009, "Label params invalid. ") + ; private int errCode; private String desc; diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java similarity index 84% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java index 82da5b66b5..8497c9edc1 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java @@ -18,15 +18,14 @@ import com.webank.wedatasphere.linkis.common.exception.ErrorException; -/** - * created by enjoyyin on 2018/10/8 - * Description: - */ + public class EntranceIllegalParamException extends ErrorException { public EntranceIllegalParamException(int errCode, String message){ super(errCode, message); } - + public EntranceIllegalParamException(EntranceErrorCode entranceErrorCode) { + super(entranceErrorCode.getErrCode(), entranceErrorCode.getDesc()); + } } diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java index 1f5585b500..1a7c36b1c3 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java @@ -21,8 +21,9 @@ import com.webank.wedatasphere.linkis.entrance.execute.*; import com.webank.wedatasphere.linkis.entrance.log.*; import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils; import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest; @@ -37,12 +38,10 @@ import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.List; import java.util.Map; -/** - * created by enjoyyin on 2018/10/17 - * Description: - */ + public class EntranceExecutionJob extends EntranceJob implements LogHandler { private LogReader logReader; @@ -51,14 +50,15 @@ public class EntranceExecutionJob extends EntranceJob implements LogHandler { private WebSocketLogWriter webSocketLogWriter; private static final Logger logger = LoggerFactory.getLogger(EntranceExecutionJob.class); - public class EntranceExecuteRequest implements ExecuteRequest, LockExecuteRequest, JobExecuteRequest, RuntimePropertiesExecuteRequest { + public class EntranceExecuteRequest implements ExecuteRequest, LabelExecuteRequest, JobExecuteRequest, RuntimePropertiesExecuteRequest { private String executionCode; - public void setExecutionCode(){ + + public void setExecutionCode() { Task task = getTask(); - if (task instanceof RequestPersistTask){ - this.executionCode = ((RequestPersistTask) task).getExecutionCode(); + if (task instanceof RequestPersistTask) { + this.executionCode = ((RequestPersistTask) task).getExecutionCode(); } } @@ -67,24 +67,29 @@ public String code() { return this.executionCode; } - @Override - public String lock() { - return getLock(); - } - @Override public String jobId() { return getId(); } + @Override public Map properties() { Map properties = TaskUtils.getRuntimeMap(getParams()); - if(getTask() instanceof RequestPersistTask) { + if (getTask() instanceof RequestPersistTask) { properties.put(TaskConstant.RUNTYPE, ((RequestPersistTask) getTask()).getRunType()); } return properties; } + + @Override + public List> labels() { + Task task = getTask(); + if (task instanceof RequestPersistTask) { + return ((RequestPersistTask) task).getLabels(); + } + return null; + } } public class StorePathEntranceExecuteRequest extends EntranceExecuteRequest implements StorePathExecuteRequest { diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java similarity index 79% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java index 78a2777917..c911e481c3 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java @@ -21,19 +21,19 @@ import com.webank.wedatasphere.linkis.entrance.exception.EntranceIllegalParamException; import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.utils.GovernanceConstant; import com.webank.wedatasphere.linkis.protocol.task.Task; +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils; import com.webank.wedatasphere.linkis.scheduler.queue.Job; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; +import java.util.Map; + -/** - * created by enjoyyin on 2018/10/11 - * Description: - */ public abstract class AbstractEntranceParser extends EntranceParser { private EntranceContext entranceContext; @@ -61,26 +61,21 @@ public Task parseToTask(Job job) throws EntranceIllegalParamException{ if (job == null){ throw new EntranceIllegalParamException(20002, "job can't be null"); } - Task task = ((EntranceJob)job).getTask(); + Task task = ((EntranceJob) job).getTask(); if(StringUtils.isEmpty(task.getExecId())) { task.setExecId(job.getId()); } - if (task instanceof RequestPersistTask){ + if (task instanceof RequestPersistTask) { ((RequestPersistTask) task).setProgress(job.getProgress()); ((RequestPersistTask) task).setStatus(job.getState().toString()); ((RequestPersistTask) task).setUpdatedTime(new Date(System.currentTimeMillis())); ((RequestPersistTask) task).setProgress(job.getProgress()); - if(job.isCompleted() && !job.isSucceed() && job.getErrorResponse() != null + if (job.isCompleted() && !job.isSucceed() && job.getErrorResponse() != null && StringUtils.isBlank(((RequestPersistTask) task).getErrDesc()) - && StringUtils.isNotEmpty(job.getErrorResponse().message())) { + && StringUtils.isNotEmpty(job.getErrorResponse().message())) { ((RequestPersistTask) task).setErrDesc(job.getErrorResponse().message()); } - //if job is successful, errCode and errDesc needs to be null - if (job.isSucceed()){ - ((RequestPersistTask) task).setErrCode(null); - ((RequestPersistTask) task).setErrDesc(null); - } - }else{ + } else { logger.warn("not supported task type"); } return task; @@ -92,25 +87,27 @@ protected EntranceJob createEntranceJob() { /** * Parse a task into an executable job(将一个task解析成一个可执行的job) + * * @param task * @return */ @Override public Job parseToJob(Task task) throws EntranceIllegalParamException { - if (task == null){ + if (task == null) { throw new EntranceIllegalParamException(20001, "task can't be null"); } EntranceJob job = null; - if (task instanceof RequestPersistTask){ + if (task instanceof RequestPersistTask) { job = createEntranceJob(); job.setTask(task); job.setUser(((RequestPersistTask) task).getUmUser()); job.setCreator(((RequestPersistTask) task).getRequestApplicationName()); + job.setParams(((RequestPersistTask) task).getParams()); - //job.setLogListener(entranceContext.getOrCreateLogManager()); - //job.setProgressListener(entranceContext.getOrCreatePersistenceManager()); - //job.setJobListener(entranceContext.getOrCreatePersistenceManager()); + //TODO 放置source到RequestTask的properties中,后续会进行优化 + Map properties = TaskUtils.getRuntimeMap(job.getParams()); + properties.put(GovernanceConstant.TASK_SOURCE_MAP_KEY(), ((RequestPersistTask) task).getSource()); job.setEntranceListenerBus(entranceContext.getOrCreateEventListenerBus()); job.setEntranceContext(entranceContext); job.setListenerEventBus(null); diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java similarity index 95% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java index bc3aff72ab..b1816e298f 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java @@ -17,7 +17,7 @@ package com.webank.wedatasphere.linkis.entrance.parser; import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration$; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import org.apache.commons.lang.StringUtils; @@ -25,10 +25,7 @@ import java.util.Date; import java.util.HashMap; import java.util.Map; -/** - * created by enjoyyin on 2018/10/17 - * Description: - */ + public final class ParserUtils { diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java similarity index 95% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java index 67daab244a..80ff979281 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java @@ -23,13 +23,12 @@ package com.webank.wedatasphere.linkis.entrance.persistence; import com.google.gson.Gson; -import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration; import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration$; import com.webank.wedatasphere.linkis.entrance.exception.EntranceIllegalParamException; import com.webank.wedatasphere.linkis.entrance.exception.EntranceRPCException; import com.webank.wedatasphere.linkis.entrance.exception.QueryFailedException; +import com.webank.wedatasphere.linkis.governance.common.entity.task.*; import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; -import com.webank.wedatasphere.linkis.protocol.query.*; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.rpc.Sender; import org.slf4j.Logger; @@ -49,7 +48,7 @@ public class QueryPersistenceEngine extends AbstractPersistenceEngine{ public QueryPersistenceEngine(){ /* - Get the corresponding sender through datawork-cloud-publicservice(通过datawork-cloud-publicservice 拿到对应的sender) + Get the corresponding sender through datawork-linkis-publicservice(通过datawork-linkis-publicservice 拿到对应的sender) */ sender = Sender.getSender(EntranceConfiguration$.MODULE$.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME().getValue()); } @@ -84,7 +83,7 @@ public void persist(Task task) throws QueryFailedException, EntranceIllegalParam throw new QueryFailedException(20011, "insert task failed, reason: " + message); } String taskStr = object.toString(); - Long taskID = Long.parseLong(taskStr.substring(0,taskStr.indexOf("."))); + Long taskID = Long.parseLong(taskStr); ((RequestPersistTask) task).setTaskID(taskID); } }else{ @@ -116,7 +115,7 @@ public Task retrieve(Long taskID)throws EntranceIllegalParamException, QueryFail logger.error("By taskID: {} request the corresponding task return status code is not 0, the query fails(通过taskID: {} 请求相应的task返回状态码不为0,查询失败)", taskID); throw new QueryFailedException(20010, "retrieve task failed, reason: " + message); } - java.util.Map data = responsePersist.getData(); + Map data = responsePersist.getData(); if (data != null){ Object object = data.get(TaskConstant.TASK); if (object instanceof List){ diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java index a73cd8d8e8..ebfed2bff1 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,8 +24,8 @@ import com.webank.wedatasphere.linkis.entrance.EntranceContext; import com.webank.wedatasphere.linkis.entrance.cs.CSEntranceHelper; import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse; import com.webank.wedatasphere.linkis.scheduler.queue.Job; @@ -84,7 +81,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { path = createResultSetEngine().persistResultSet(job, response); } catch (Throwable e) { job.onFailure("persist resultSet failed!", e); - if(isEntranceJob) ((EntranceJob)job).incrementResultSetPersisted(); + if (isEntranceJob) ((EntranceJob) job).incrementResultSetPersisted(); return; } if(StringUtils.isNotBlank(path)) { @@ -99,7 +96,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { logger.error("job {} onLogUpdate error, reason:", job.getId(), e1); } //ignore it if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } return; } @@ -108,7 +105,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { if(StringUtils.isEmpty(requestPersistTask.getResultLocation())) synchronized (task) { if(StringUtils.isNotEmpty(requestPersistTask.getResultLocation())) { if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } return; } @@ -122,13 +119,13 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { } } if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } } @Override public void onResultSizeCreated(Job job, int resultSize) { - if(job instanceof EntranceJob) { + if (job instanceof EntranceJob) { ((EntranceJob) job).setResultSize(resultSize); } } @@ -136,9 +133,6 @@ public void onResultSizeCreated(Job job, int resultSize) { @Override public void onProgressUpdate(Job job, float progress, JobProgressInfo[] progressInfo) { job.setProgress(progress); - if (job instanceof EntranceJob){ - ((EntranceJob) job).setProgressInfo(progressInfo); - } updateJobStatus(job); } @@ -162,7 +156,7 @@ public void onJobWaitForRetry(Job job) { @Override public void onJobCompleted(Job job) { - //update by peaceWong(2020/05/10) to set jobID to CS + //update by peaceWong to set jobID to CS try { if (job.isSucceed()) { CSEntranceHelper.registerCSRSData(job); @@ -170,7 +164,6 @@ public void onJobCompleted(Job job) { } catch (Throwable e) { logger.error("Failed to register cs rs data ", e); } - //end update updateJobStatus(job); } diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java new file mode 100644 index 0000000000..93b2c3264a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java @@ -0,0 +1,405 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.restful; + +import com.google.gson.Gson; +import com.google.gson.internal.LinkedTreeMap; +import com.webank.wedatasphere.linkis.common.log.LogUtils; +import com.webank.wedatasphere.linkis.entrance.EntranceServer; +import com.webank.wedatasphere.linkis.entrance.annotation.EntranceServerBeanAnnotation; +import com.webank.wedatasphere.linkis.entrance.background.BackGroundService; +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration; +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; +import com.webank.wedatasphere.linkis.entrance.log.LogReader; +import com.webank.wedatasphere.linkis.entrance.utils.JobHistoryHelper; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo; +import com.webank.wedatasphere.linkis.protocol.task.Task; +import com.webank.wedatasphere.linkis.protocol.utils.ZuulEntranceUtils; +import com.webank.wedatasphere.linkis.rpc.Sender; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; +import com.webank.wedatasphere.linkis.server.Message; +import com.webank.wedatasphere.linkis.server.security.SecurityFilter; +import com.webank.wedatasphere.linkis.server.socket.controller.ServerEvent; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import scala.Option; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.*; + +/** + * Description: an implementation class of EntranceRestfulRemote + */ +@Path("/entrance") +@Component +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class EntranceRestfulApi implements EntranceRestfulRemote { + + private EntranceServer entranceServer; + + private static final Logger logger = LoggerFactory.getLogger(EntranceRestfulApi.class); + + @EntranceServerBeanAnnotation.EntranceServerAutowiredAnnotation + public void setEntranceServer(EntranceServer entranceServer) { + this.entranceServer = entranceServer; + } + + /** + * The execute function handles the request submitted by the user to execute the task, and the execution ID is returned to the user. + * execute函数处理的是用户提交执行任务的请求,返回给用户的是执行ID + * json Incoming key-value pair(传入的键值对) + * Repsonse + */ + @Override + @POST + @Path("/execute") + public Response execute(@Context HttpServletRequest req, Map json) { + Message message = null; +// try{ + logger.info("Begin to get an execID"); + json.put(TaskConstant.UMUSER, SecurityFilter.getLoginUsername(req)); + String execID = entranceServer.execute(json); + Job job = entranceServer.getJob(execID).get(); + Task task = ((EntranceJob) job).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + pushLog(LogUtils.generateInfo("You have submitted a new job, script code (after variable substitution) is"), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(((RequestPersistTask) task).getCode(), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(LogUtils.generateInfo("Your job is accepted, jobID is " + execID + " and taskID is " + taskID + ". Please wait it to be scheduled"), job); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/execute"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); +// }catch(ErrorException e){ +// message = Message.error(e.getDesc()); +// message.setStatus(1); +// message.setMethod("/api/entrance/execute"); +// } + return Message.messageToResponse(message); + + } + + @Override + @POST + @Path("/submit") + public Response submit(@Context HttpServletRequest req, Map json) { + Message message = null; + logger.info("Begin to get an execID"); + json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req)); + String execID = entranceServer.execute(json); + Job job = entranceServer.getJob(execID).get(); + Task task = ((EntranceJob) job).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + pushLog(LogUtils.generateInfo("You have submitted a new job, script code (after variable substitution) is"), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(((RequestPersistTask) task).getCode(), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(LogUtils.generateInfo("Your job is accepted, jobID is " + execID + " and taskID is " + taskID + ". Please wait it to be scheduled"), job); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/submit"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); + return Message.messageToResponse(message); + } + + private void pushLog(String log, Job job) { + entranceServer.getEntranceContext().getOrCreateLogManager().onLogUpdate(job, log); + } + + @Override + @GET + @Path("/{id}/status") + public Response status(@PathParam("id") String id, @QueryParam("taskID") String taskID) { + Message message = null; + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = Option.apply(null); + try { + job = entranceServer.getJob(realId); + } catch (Exception e) { + logger.warn("获取任务 {} 状态时出现错误", realId, e); + //如果获取错误了,证明在内存中已经没有了,去jobhistory找寻一下taskID代表的任务的状态,然后返回 + long realTaskID = Long.parseLong(taskID); + String status = JobHistoryHelper.getStatusByTaskID(realTaskID); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/status"); + message.data("status", status).data("execID", id); + return Message.messageToResponse(message); + } + if (job.isDefined()) { + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/status"); + message.data("status", job.get().getState().toString()).data("execID", id); + } else { + message = Message.error("ID The corresponding job is empty and cannot obtain the corresponding task status.(ID 对应的job为空,不能获取相应的任务状态)"); + } + return Message.messageToResponse(message); + } + + + + + @Override + @GET + @Path("/{id}/progress") + public Response progress(@PathParam("id") String id) { + Message message = null; + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = entranceServer.getJob(realId); + if (job.isDefined()) { + JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo(); + if (jobProgressInfos == null) { + message = Message.error("Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)"); + message.setMethod("/api/entrance/" + id + "/progress"); + } else { + List> list = new ArrayList<>(); + for (JobProgressInfo jobProgressInfo : jobProgressInfos) { + if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())) { + Map map = new HashMap<>(); + map.put("id", jobProgressInfo.id()); + map.put("succeedTasks", jobProgressInfo.succeedTasks()); + map.put("failedTasks", jobProgressInfo.failedTasks()); + map.put("runningTasks", jobProgressInfo.runningTasks()); + map.put("totalTasks", jobProgressInfo.totalTasks()); + list.add(map); + } else if (jobProgressInfo.failedTasks() > 0 || jobProgressInfo.runningTasks() > 0) { + Map map = new HashMap<>(); + map.put("id", jobProgressInfo.id()); + map.put("succeedTasks", jobProgressInfo.succeedTasks()); + map.put("failedTasks", jobProgressInfo.failedTasks()); + map.put("runningTasks", jobProgressInfo.runningTasks()); + map.put("totalTasks", jobProgressInfo.totalTasks()); + list.add(map); + } + } + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/progress"); + message.data("progress", job.get().getProgress()).data("execID", id).data("progressInfo", list); + } + } else { + message = Message.error("The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)"); + } + return Message.messageToResponse(message); + } + + @Override + @GET + @Path("/{id}/log") + public Response log(@Context HttpServletRequest req, @PathParam("id") String id) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = Option.apply(null); + Message message = null; + try { + job = entranceServer.getJob(realId); + } catch (final Throwable t) { + message = Message.error("The job you just executed has ended. This interface no longer provides a query. It is recommended that you download the log file for viewing.(您刚刚执行的job已经结束,本接口不再提供查询,建议您下载日志文件进行查看)"); + message.setMethod("/api/entrance/" + id + "/log"); + return Message.messageToResponse(message); + } + if (job.isDefined()) { + logger.debug("开始获取 {} 的日志", job.get().getId()); + LogReader logReader = entranceServer.getEntranceContext().getOrCreateLogManager().getLogReader(realId); + int fromLine = 0; + int size = 100; + boolean distinctLevel = true; + if (req != null) { + String fromLineStr = req.getParameter("fromLine"); + String sizeStr = req.getParameter("size"); + if (StringUtils.isNotBlank(fromLineStr)) { + fromLine = Math.max(Integer.parseInt(fromLineStr), 0); + } + if (StringUtils.isNotBlank(sizeStr)) { + size = Integer.parseInt(sizeStr) >= 0 ? Integer.parseInt(sizeStr) : 10000; + } + String distinctLevelStr = req.getParameter("distinctLevel"); + if ("false".equals(distinctLevelStr)) { + distinctLevel = false; + } + } + + Object retLog = null; + int retFromLine = 0; + try { + if (distinctLevel) { + String[] logs = new String[4]; + retFromLine = logReader.readArray(logs, fromLine, size); + retLog = new ArrayList(Arrays.asList(logs)); + } else { + StringBuilder sb = new StringBuilder(); + retFromLine = logReader.read(sb, fromLine, size); + retLog = sb.toString(); + } + } catch (IllegalStateException e) { + logger.error("为 {} 获取日志失败 原因:{}", job.get().getId(), e.getMessage()); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + } catch (final IllegalArgumentException e) { + logger.error("为 {} 获取日志失败", job.get().getId()); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + return Message.messageToResponse(message); + } catch (final Exception e1) { + logger.error("为 {} 获取日志失败", job.get().getId(), e1); + message = Message.error("Failed to get log information(获取日志信息失败)"); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + return Message.messageToResponse(message); + } + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", retLog).data("execID", id).data("fromLine", retFromLine + fromLine); + logger.debug("获取 {} 日志成功", job.get().getId()); + } else { + message = Message.error("Can't find execID(不能找到execID): " + id + "Corresponding job, can not get the corresponding log(对应的job,不能获得对应的日志)"); + message.setMethod("/api/entrance/" + id + "/log"); + } + return Message.messageToResponse(message); + } + + + @Override + @GET + @Path("/{id}/kill") + public Response kill(@PathParam("id") String id, @QueryParam("taskID") long taskID) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + //通过jobid获取job,可能会由于job找不到而导致有looparray的报错,一旦报错的话,就可以将该任务直接置为Cancenlled + Option job = Option.apply(null); + try { + job = entranceServer.getJob(realId); + } catch (Exception e) { + logger.warn("can not find a job in entranceServer, will force to kill it", e); + //如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的 + JobHistoryHelper.forceKill(taskID); + Message message = Message.ok("强制杀死任务"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(0); + return Message.messageToResponse(message); + } + Message message = null; + if (job.isEmpty()) { + message = Message.error("Can't find execID(不能找到execID): " + id + "Corresponding job, can't kill(对应的job,不能进行kill)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(1); + } else { + try { + logger.info("begin to kill job {} ", job.get().getId()); + job.get().kill(); + message = Message.ok("Successfully killed the job(成功kill了job)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(0); + message.data("execID", id); + //ensure the job's state is cancelled in database + if (job.get() instanceof EntranceJob) { + EntranceJob entranceJob = (EntranceJob) job.get(); + Task task = entranceJob.getTask(); + ((RequestPersistTask) task).setStatus("Cancelled"); + this.entranceServer.getEntranceContext().getOrCreatePersistenceManager().createPersistenceEngine().updateIfNeeded(task); + } + logger.info("end to kill job {} ", job.get().getId()); + } catch (Throwable t) { + logger.error("kill job {} failed ", job.get().getId(), t); + message = Message.error("An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(1); + } + } + return Message.messageToResponse(message); + } + + @Override + @GET + @Path("/{id}/pause") + public Response pause(@PathParam("id") String id) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = entranceServer.getJob(realId); + Message message = null; + if (job.isEmpty()) { + message = Message.error("不能找到execID: " + id + "对应的job,不能进行pause"); + message.setMethod("/api/entrance/" + id + "/pause"); + message.setStatus(1); + } else { + try { + //todo job pause 接口还未实现和给出 + //job.pause(); + logger.info("begin to pause job {} ", job.get().getId()); + message = Message.ok("成功pause了job"); + message.setStatus(0); + message.data("execID", id); + message.setMethod("/api/entrance/" + id + "/pause"); + logger.info("end to pause job {} ", job.get().getId()); + } catch (Throwable t) { + logger.info("pause job {} failed ", job.get().getId()); + message = Message.error("Abnormal when pausing job, pause failed(pause job的时候出现了异常,pause失败)"); + message.setMethod("/api/entrance/" + id + "/pause"); + message.setStatus(1); + } + } + return Message.messageToResponse(message); + } + + @Override + @POST + @Path("/backgroundservice") + public Response backgroundservice(@Context HttpServletRequest req, Map json) { + Message message = null; + logger.info("Begin to get an execID"); + String backgroundType = (String) json.get("background"); + BackGroundService[] bgServices = entranceServer.getEntranceContext().getOrCreateBackGroundService(); + BackGroundService bgService = null; + for (BackGroundService backGroundService : bgServices) { + if (backgroundType.equals(backGroundService.serviceType())) { + bgService = backGroundService; + break; + } + } + Gson gson = new Gson(); + Map executionCode = (Map) json.get("executionCode"); + executionCode = gson.fromJson(gson.toJson(executionCode), LinkedTreeMap.class); + json.put("executionCode", executionCode); + json.put(TaskConstant.UMUSER, SecurityFilter.getLoginUsername(req)); + ServerEvent serverEvent = new ServerEvent(); + serverEvent.setData(json); + serverEvent.setUser(SecurityFilter.getLoginUsername(req)); + ServerEvent operation = bgService.operation(serverEvent); + String execID = entranceServer.execute(operation.getData()); + Task task = ((EntranceJob) entranceServer.getJob(execID).get()).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/backgroundservice"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); + return Message.messageToResponse(message); + + } +} diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java similarity index 94% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java index 7813eccf89..3bfd3f3f0c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java @@ -25,10 +25,7 @@ import javax.annotation.PostConstruct; -/** - * created by enjoyyin on 2018/10/12 - * Description: - */ + @EntranceServerBeanAnnotation public class DefaultEntranceServer extends EntranceServer { @@ -46,6 +43,7 @@ public DefaultEntranceServer(EntranceContext entranceContext) { @PostConstruct public void init() { getEntranceWebSocketService(); + addRunningJobEngineStatusMonitor(); } @Override @@ -63,4 +61,7 @@ public LogReader logReader(String execId) { return getEntranceContext().getOrCreateLogManager().getLogReader(execId); } + private void addRunningJobEngineStatusMonitor() { + + } } diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml b/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml new file mode 100644 index 0000000000..62b82b3283 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml @@ -0,0 +1,27 @@ +server: + port: 9104 +spring: + application: + name: linkis-cg-entrance + + +eureka: + client: + serviceUrl: + defaultZone: http://127.0.0.1:20303/eureka/ + instance: + metadata-map: + test: + +management: + endpoints: + web: + exposure: + include: refresh,info +logging: + config: classpath:log4j2.xml +# register-with-eureka: false +# fetch-registry: false +ribbon: + ReadTimeout: 10000 + ConnectTimeout: 10000 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties b/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties new file mode 100644 index 0000000000..c34c581003 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties @@ -0,0 +1,20 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +##restful +wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful +wds.linkis.server.socket.mode=false +#wds.linkis.entrance.config.log.path=hdfs:///tmp/linkis/ +#wds.linkis.resultSet.store.path=hdfs:///tmp/linkis \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml b/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..0f19fc3c17 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala similarity index 97% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala index 881f544158..3f216504f3 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala @@ -23,9 +23,7 @@ import com.webank.wedatasphere.linkis.entrance.log.LogManager import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager import com.webank.wedatasphere.linkis.scheduler.Scheduler -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class EntranceContext { def getOrCreateScheduler(): Scheduler @@ -40,6 +38,7 @@ abstract class EntranceContext { /** * Please note: it can be empty(请注意:可以为空) + * * @return */ def getOrCreateEventListenerBus: EntranceEventListenerBus[EntranceEventListener, EntranceEvent] diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala similarity index 97% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala index da2188f763..d12199fb8b 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,15 +18,13 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.exception.{EntranceErrorException, SubmitFailedException} import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob import com.webank.wedatasphere.linkis.entrance.log.LogReader -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import org.apache.commons.lang.StringUtils import org.apache.commons.lang.exception.ExceptionUtils -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class EntranceServer extends Logging { private var entranceWebSocketService: Option[EntranceWebSocketService] = None diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala similarity index 92% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala index 89ae6100fd..ec0e0ef792 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala @@ -30,9 +30,9 @@ import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob import com.webank.wedatasphere.linkis.entrance.log.LogReader import com.webank.wedatasphere.linkis.entrance.restful.EntranceRestfulApi +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.utils.ZuulEntranceUtils import com.webank.wedatasphere.linkis.rpc.Sender import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} @@ -41,9 +41,7 @@ import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import com.webank.wedatasphere.linkis.server.socket.controller.{ServerEvent, ServerEventService, SocketServerEvent} import org.apache.commons.lang.StringUtils -/** - * Created by enjoyyin on 2018/9/14. - */ + class EntranceWebSocketService extends ServerEventService with EntranceEventListener { private val jobIdToEventId = new util.HashMap[String, Integer] @@ -59,7 +57,6 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList private val killUrlPattern = (restfulURI + """entrance/(.+)/kill""").r private val pauseUrlPattern = (restfulURI + """entrance/(.+)/pause""").r private val backgroundUrlPattern = restfulURI + """entrance/backgroundservice""" - private val runtimeTuningUrlPattern = (restfulURI + """entrance/(.+)/runtimeTuning""").r def setEntranceServer(entranceServer: EntranceServer):Unit = this.entranceServer = entranceServer def setEntranceRestfulApi(entranceRestfulApi: EntranceRestfulApi):Unit = this.entranceRestfulApi = entranceRestfulApi @@ -140,13 +137,9 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList LogUtils.generateInfo(s"Your job's execution code is (after variable substitution and code check) ")) entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, "************************************SCRIPT CODE************************************") -// entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,task.asInstanceOf[RequestPersistTask].getCode) val code = task.asInstanceOf[RequestPersistTask].getCode val codeLength = code.length() - val pushLog = if (codeLength > 1000){ - code.substring(0, 1000) + " ... " - } else code - entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,pushLog) + entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,code) entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, "************************************SCRIPT CODE************************************") entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, @@ -167,11 +160,11 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => { + case entranceExecutionJob: EntranceExecutionJob => { info(s"begin to get job $realID log via websocket") - val logsArr:Array[String] = new Array[String](4) + val logsArr: Array[String] = new Array[String](4) entranceExecutionJob.getWebSocketLogReader.foreach(logReader => logReader.readArray(logsArr, 0, 100)) - val logList:util.List[String] = new util.ArrayList[String]() + val logList: util.List[String] = new util.ArrayList[String]() logsArr foreach logList.add retMessage = Message.ok("Successfully obtained log information(成功获取到日志信息)") retMessage.data("execID", id).data("log", logList).data("websocketTag", websocketTagJobID.get(realID)) @@ -196,11 +189,11 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList //val realID:String = if (entranceServer.getJob(id).isDefined) id else ZuulEntranceUtils.parseExecID(id)(2) val realID:String = if (!id.contains(":")) id else ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => + case entranceExecutionJob: EntranceExecutionJob => val longExecID = ZuulEntranceUtils.generateExecID(realID, entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName, Sender.getThisInstance, entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName) - if(!jobIdToEventId.containsKey(realID) && event != null) jobIdToEventId synchronized jobIdToEventId.put(realID, event.getId) + if (!jobIdToEventId.containsKey(realID) && event != null) jobIdToEventId synchronized jobIdToEventId.put(realID, event.getId) val status = entranceExecutionJob.getState retMessage = Message.ok("Get the status of the task successfully(获取任务状态成功)") @@ -226,7 +219,7 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => { + case entranceExecutionJob: EntranceExecutionJob => { val progress = entranceExecutionJob.getProgress retMessage = Message.ok("Get the task progress successfully(获取任务进度成功)") val taskID = entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getTaskID @@ -254,16 +247,16 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => - try{ + case entranceExecutionJob: EntranceExecutionJob => + try { entranceExecutionJob.kill() retMessage = Message.ok("Kill task succeeded(kill任务成功)") retMessage.setMethod(restfulURI + "entrance/" + id + "/kill") retMessage.setStatus(0) return retMessage - }catch{ - case e:Exception => retMessage = Message.error("Kill task failed(kill任务失败)", e) - case t:Throwable => retMessage = Message.error("Kill task failed(kill任务失败)", t) + } catch { + case e: Exception => retMessage = Message.error("Kill task failed(kill任务失败)", e) + case t: Throwable => retMessage = Message.error("Kill task failed(kill任务失败)", t) } case _ => } @@ -380,27 +373,33 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList } } }) - val logList:util.List[String] = new util.ArrayList[String]() + if (StringUtils.isBlank(info.toString()) && + StringUtils.isBlank(warn.toString()) && + StringUtils.isBlank(error.toString()) && + StringUtils.isBlank(all.toString())) { + return + } + val logList: util.List[String] = new util.ArrayList[String]() logList.add(error.toString()) logList.add(warn.toString()) logList.add(info.toString()) logList.add(all.toString()) message = Message.ok("Return log information(返回日志信息)") val executeApplicationName = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName - val creator:String = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName - val execID:String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) + val creator: String = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName + val execID: String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) message.setMethod(restfulURI + "entrance/" + execID + "/log") val taskID = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getTaskID - message.data("execID",execID).data("log", logList).data("websocketTag", websocketTagJobID.get(job.getId)).data("taskID", taskID) + message.data("execID", execID).data("log", logList).data("websocketTag", websocketTagJobID.get(job.getId)).data("taskID", taskID) sendMsg(job, message) } def pushProgressToFrontend(job: Job, progress: Float, progressInfo: Array[JobProgressInfo]): Unit = { val progressInfoMap = progressInfo.map(info => toJavaMap(Map("id" -> info.id, "succeedTasks" -> info.succeedTasks, - "failedTasks" -> info.failedTasks , "runningTasks" -> info.runningTasks, "totalTasks" -> info.totalTasks))) + "failedTasks" -> info.failedTasks, "runningTasks" -> info.runningTasks, "totalTasks" -> info.totalTasks))) val executeApplicationName = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName val creator = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName job.asInstanceOf[EntranceJob].setProgressInfo(progressInfo) - val execID:String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) + val execID: String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) val message = Message.ok("返回进度信息!") message.setMethod(restfulURI + "entrance/" + execID + "/progress") val taskID = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getTaskID diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala similarity index 85% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala index f2258e1563..f5532539d1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala @@ -15,18 +15,17 @@ */ package com.webank.wedatasphere.linkis.entrance.cache + import java.util import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.protocol.conf.{RequestQueryGlobalConfig, ResponseQueryConfig} import com.webank.wedatasphere.linkis.protocol.CacheableProtocol -import com.webank.wedatasphere.linkis.protocol.config.{RequestQueryGlobalConfig, ResponseQueryConfig} -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.rpc.RPCMapCache -/** - * Created by enjoyyin on 2018/11/4. - */ + object GlobalConfigurationKeyValueCache extends RPCMapCache[RequestPersistTask, String, String](EntranceConfiguration.CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME.getValue) { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala new file mode 100644 index 0000000000..ff2ff61dd5 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala @@ -0,0 +1,157 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + + +object EntranceConfiguration { + + val ENTRANCE_SCHEDULER_MAX_PARALLELISM_USERS = CommonVars("wds.linkis.entrance.scheduler.maxParallelismUsers", new Integer(1000)) + val ENTRANCE_LISTENER_BUS_EVENT_QUEUE_CAPACITY = CommonVars("wds.linkis.entrance.listenerBus.queue.capacity", new Integer(5000)) + + val JOB_MAX_PERSIST_WAIT_TIME = CommonVars("wds.linkis.entrance.job.persist.wait.max", new TimeType("5m")) + + val MULTI_ENTRANCE_CONDITION = CommonVars("wds.linkis.entrance.multi.entrance.flag", true) + + val RESULT_SET_STORE_PATH = CommonVars("wds.linkis.resultSet.store.path", CommonVars[String]("wds.linkis.filesystem.hdfs.root.path").getValue) + + /** + * QUERY_PERSISTENCE_SPRING_APPLICATION_NAME is the name of the application that represents the query module in springcloud + * QUERY_PERSISTENCE_SPRING_APPLICATION_NAME 是表示query模块在springcloud中的应用名称 + */ + val QUERY_PERSISTENCE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.query.application.name", "linkis-ps-publicservice") + /** + * DEFAULT_LOGPATH_PREFIX is the prefix that represents the default log storage path + * DEFAULT_LOGPATH_PREFIX 是表示默认的日志存储路径的前缀 + */ + val DEFAULT_LOGPATH_PREFIX = CommonVars[String]("wds.linkis.entrance.config.log.path", CommonVars[String]("wds.linkis.filesystem.hdfs.root.path").getValue) + /** + * Default_Cache_Max is used to specify the size of the LoopArray of the CacheLogWriter + * Default_Cache_Max 是用来指定CacheLogWriter的LoopArray的大小 + */ + val DEFAULT_CACHE_MAX = CommonVars("wds.linkis.entrance.log.cacheMax", 500) + /** + * Default_Log_CharSet is used to specify the encoding mode of the log storage. + * Default_Log_CharSet 是用来指定日志存储的编码方式 + */ + val DEFAULT_LOG_CHARSET = CommonVars("wds.linkis.entrance.log.defaultCharSet", "utf-8") + /** + * The application name of the console module in spring-cloud + * console 模块在spring-cloud中的应用名称 + */ + val CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.console.configuration.application.name", "linkis-ps-publicservice") + val CLOUD_CONSOLE_VARIABLE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.console.variable.application.name", "linkis-ps-publicservice") + /** + * The logPath in the console module returns the key in the map. + * console 模块中logPath在返回map中的key + */ + val CLOUD_CONSOLE_LOGPATH_KEY = CommonVars("wds.linkis.console.config.logPath", "wds.linkis.config.logPath") + /** + * requestApplicationName(Creator) The default service name, the default is IDE + * requestApplicationName(Creator) 默认的服务名,默认为IDE + */ + val DEFAULT_REQUEST_APPLICATION_NAME = CommonVars("wds.linkis.default.requestApplication.name", "IDE") + /** + * runType + */ + val DEFAULT_RUN_TYPE = CommonVars("wds.linkis.default.runType", "sql") + + val DEFAULT_CREATE_SERVICE = CommonVars("wds.linkis.default.create.service", "dss") + + val LOG_WARN_EXCLUDE = CommonVars("wds.linkis.warn.log.exclude", "org.apache,hive.ql,hive.metastore,com.netflix,com.webank.wedatasphere") + + val CLEAR_LOG = CommonVars("wds.linkis.log.clear", false) + + /** + * LOG_EXCLUDE is used to remove the log of the framework log, such as hive spark spring, so that it is not pushed to the front end through websocket. + * LOG_EXCLUDE 是用来进行把框架日志,比如hive spark spring等日志进行剔除,不让其通过websocket进行推送到前端 + */ + val LOG_EXCLUDE = CommonVars("wds.linkis.log.exclude", "org.apache,hive.ql,hive.metastore,com.netflix,com.webank.wedatasphere,com.webank") + + /** + * wds.linkis.dwc.instance is a parameter used to control the number of engines each user starts. + *wds.linkis.instance 是用来进行控制每个用户启动engine数量的参数 + */ + val WDS_LINKIS_INSTANCE = CommonVars("wds.linkis.instance", 3) + + val LOG_EXCLUDE_ALL = CommonVars("wds.linkis.log.exclude.all", "com.netflix") + + val MAX_ASK_EXECUTOR_TIME = CommonVars("wds.linkis.max.ask.executor.time", new TimeType("5m")) + + val ERROR_CODE_FILE_DIR = CommonVars("wds.linkis.errorcode.file.dir", "") + + val ENTRANCE_USER = CommonVars("wds.linkis.entrance.user", "") + + val ERROR_CODE_FILE = CommonVars("wds.linkis.errorcode.file", "") + + //todo enjoyyin Simple processing first, this log is not filtered, and subsequent optimization is performed.(先简单处理 不过滤这个日志,后续进行优化) + val HIVE_SPECIAL_LOG_INCLUDE = CommonVars("wds.linkis.hive.special.log.include", "org.apache.hadoop.hive.ql.exec.Task") + + val SHARE_FILE_PRE = CommonVars("wds.linkis.share.file.prefix", "") + + val HIVE_THREAD_NAME = CommonVars("wds.linkis.hive.thread.name", "[Thread") + + val HIVE_STAGE_NAME = CommonVars("wds.linkis.hive.stage.name", "Stage-") + + val SPARK_SPECIAL_LOG_INCLUDE = CommonVars("wds.linkis.spark.special.log.include", "com.webank.wedatasphere.linkis.engine.spark.utils.JobProgressUtil") + + + val SPARK_PROGRESS_NAME = CommonVars("wds.linkis.spark.progress.name", "com.webank.wedatasphere.linkis.engine.spark.utils.JobProgressUtil$") + + val END_FLAG = CommonVars("bdp.dataworkcloud.entrance.end.flag", "info -") + + val HIVE_CREATE_TABLE_LOG = CommonVars("wds.linkis.hive.create.table.log", "numFiles") + + val HIVE_PRINT_INFO_LOG = CommonVars("wds.linkis.hive.printinfo.log", "printInfo -") + + val DATAMAP_APPID = CommonVars("wds.linkis.entrance.datawmap.appid", "75116e6f690e6d222fb55f2dd6f9cb5a") + + val DATAMAP_APPTOKEN = CommonVars("wds.linkis.entrance.datamap.apptoken", + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJjb29wZXJ5YW5nIiwiYXBwa2V5IjoiNzUxMTZlNmY2OTBlNmQyMjJmYjU1ZjJkZDZmOWNiNWEiLCJpYXQiOjE1NzE4MTQxOTYzNDZ9.JfjvsiNMWSc1RnQh1k7vsNjwp4YRquT_XXbYmlEgBgc") + + + val DATA_MAP_IP = CommonVars("wds.linkis.entrance.datamap.ip", "") + + //val DATA_MAP_PORT = CommonVars("wds.linkis.entrance.datamap.port", "8122") + val DATA_MAP_PORT = CommonVars("wds.linkis.entrance.datamap.port", "9001") + + val IS_BDP_ENV = CommonVars("wds.linkis.entrance.bdp.env", "true") + + + val SHELL_DANGER_CHECK_SWITCH = CommonVars("wds.linkis.entrance.shell.danger.check.enabled", false) + val SHELL_DANGER_USAGE = CommonVars("wds.linkis.shell.danger.usage", "rm,sh,find,kill,python,for,source,hdfs,hadoop,spark-sql,spark-submit,pyspark,spark-shell,hive,yarn") + val SHELL_WHITE_USAGE = CommonVars("wds.linkis.shell.white.usage", "cd,ls") + + val FLOW_EXECUTION_CREATOR = CommonVars("wds.linkis.entrance.flow.creator", "nodeexecution") + + val SCHEDULER_CREATOR = CommonVars("wds.linkis.entrance.scheduler.creator", "scheduler") + + + val IS_QML = CommonVars("wds.linkis.entrance.is.qml", false) + + val PROGRESS_PUSH = CommonVars[String]("wds.linkis.entrance.push.progress", "false") + + val CONCURRENT_FACTORY_MAX_CAPACITY = CommonVars("wds.linkis.concurrent.group.factory.capacity", 1000) + + val CONCURRENT_MAX_RUNNING_JOBS = CommonVars("wds.linkis.concurrent.group.factory.running.jobs", 30) + + val CONCURRENT_EXECUTOR_TIME = CommonVars("wds.linkis.concurrent.group.factory.executor.time", 5 * 60 * 1000) + + val ENGINE_MANAGER_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.enginemanager.application.name", "linkis-cg-engineconnmanager") + + val ENTRANCE_ENGINE_LASTUPDATE_TIMEOUT = CommonVars("wds.linkis.entrance.engine.lastupdate.timeout", new TimeType("5s")) + val ENTRANCE_ENGINE_ACTIVITY_TIMEOUT = CommonVars("wds.linkis.entrance.engine.timeout", new TimeType("10s")) + val ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL = CommonVars("wds.linkis.entrance.engine.activity_monitor.interval", new TimeType("3s")) +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala new file mode 100644 index 0000000000..06f49e5655 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.conf + +import com.google.gson.Gson + + +object EntranceConstant { + + val GSON = new Gson() + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala similarity index 95% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala index 1caa1325a4..44139ff5ea 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala @@ -25,8 +25,8 @@ import com.webank.wedatasphere.linkis.cs.common.entity.source.{CommonContextKey, import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils import com.webank.wedatasphere.linkis.scheduler.queue.Job import org.apache.commons.lang.StringUtils @@ -34,10 +34,7 @@ import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions._ import scala.collection.mutable -/** - * @author peacewong - * @date 2020/3/5 15:33 - */ + object CSEntranceHelper extends Logging { @@ -150,7 +147,7 @@ object CSEntranceHelper extends Logging { * @return */ def addCSVariable(requestPersistTask: RequestPersistTask): Unit = { - val variableMap = new mutable.HashMap[String, String]() + val variableMap = new util.HashMap[String, Any]() val (contextIDValueStr, nodeNameStr) = getContextInfo(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) if (StringUtils.isNotBlank(contextIDValueStr)) { @@ -161,7 +158,9 @@ object CSEntranceHelper extends Logging { variableMap.put(linkisVariable.getKey, linkisVariable.getValue) } } - TaskUtils.addVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]], variableMap) + if(variableMap.nonEmpty){ + TaskUtils.addVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]], variableMap) + } info(s"parse variable end nodeName:$nodeNameStr") } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala new file mode 100644 index 0000000000..aae992b4ba --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class JobHistoryFailedException(errorMsg:String) extends ErrorException(50081, errorMsg) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala new file mode 100644 index 0000000000..7bd885c11e --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class SensitiveTablesCheckException(errorMsg:String) extends ErrorException(50079, errorMsg) + +case class DangerousGramsCheckException(errorMsg:String) extends ErrorException(50081, errorMsg) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala new file mode 100644 index 0000000000..ad72245900 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala @@ -0,0 +1,87 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, ResponseTaskStatus} +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Mark +import com.webank.wedatasphere.linkis.scheduler.executer.{ConcurrentTaskOperateSupport, ErrorExecuteResponse, ExecutorState, SubmitResponse} + + + +class DefaultEntranceExecutor(id: Long, mark: Mark) extends EntranceExecutor(id, mark) with ConcurrentTaskOperateSupport { + + + /* private def doMethod[T](exec: String => T): T = if (engineReturns.isEmpty) + throw new EntranceErrorException(20001, s"Engine${id} could not find a job in RUNNING state(Engine${id}找不到处于RUNNING状态的Job)") + else exec(engineReturns(0).execId)*/ + + + override protected def callExecute(request: RequestTask): EngineExecuteAsynReturn = { + val response = getEngineConnExecutor().execute(request) + response match { + case SubmitResponse(execId) => new EngineExecuteAsynReturn(request, getEngineConnExecutor().getServiceInstance.getInstance, execId, engineReturn => { + info("remove execId-" + execId + " with instance " + getEngineConnExecutor().getServiceInstance) + engineReturns -= engineReturn + }) + case ErrorExecuteResponse(message, t) => + info(s"failed to submit task to engineConn,reason: $message") + throw t + } + } + + override def close(): Unit = { + if (engineReturns.nonEmpty) engineReturns.foreach { e => + e.notifyError(s"$toString has already been completed with state $state.") + e.notifyStatus(ResponseTaskStatus(e.execId, ExecutionNodeStatus.Failed)) + } + } + + override def kill(jobId: String): Boolean = { + info(s"start to kill job $jobId") + engineReturns.find(_.getJobId.contains(jobId)).exists(e => killExecId(e.execId)) + } + + override def killAll(): Boolean = { + engineReturns.foreach(f => Utils.tryQuietly(killExecId(f.execId))) + true + } + + override def pause(jobId: String): Boolean = { + //TODO + true + } + + + override def pauseAll(): Boolean = { + //TODO + true + } + + override def resume(jobId: String): Boolean = { + //TODO + true + } + + override def resumeAll(): Boolean = { + //TODO + true + } + + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala similarity index 80% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala index 65a1df54dc..9f9a390705 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala @@ -16,10 +16,9 @@ package com.webank.wedatasphere.linkis.entrance.execute -/** - * Created by enjoyyin on 2018/9/15. - */ + trait EngineLockListener { - def onEngineLocked(engine: EntranceEngine, lock: String): Unit - def onEngineLockUsed(engine: EntranceEngine): Unit + def onEngineLocked(engine: EntranceExecutor, lock: String): Unit + + def onEngineLockUsed(engine: EntranceExecutor): Unit } \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala new file mode 100644 index 0000000000..994b8d1a4a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala @@ -0,0 +1,258 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.annotation.EntranceContextBeanAnnotation +import com.webank.wedatasphere.linkis.entrance.conf.{EntranceConfiguration, EntranceConstant} +import com.webank.wedatasphere.linkis.entrance.event.EntranceProgressEvent +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.entity.{ExecutionNodeStatus, NodeExistStatus} +import com.webank.wedatasphere.linkis.governance.common.protocol.engineconn.{RequestEngineStatusBatch, ResponseEngineStatusBatch} +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.governance.common.utils.GovernanceConstant +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.{EngineConnExecutor, TaskExecutionReceiver} +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.rpc.exception.DWCRPCRetryException +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.AliasOutputExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import org.springframework.stereotype.Service + +import javax.annotation.PostConstruct +import scala.collection.JavaConverters._ +import java.util +import java.util.concurrent.TimeUnit + + +@Service +class EntranceExecutionService extends TaskExecutionReceiver with Logging { + + @EntranceContextBeanAnnotation.EntranceContextAutowiredAnnotation + private var entranceContext: EntranceContext = _ + + @PostConstruct + private def init(): Unit = { + addEngineExecutorStatusMonitor() + } + + private[execute] def getEntranceExecutorManager = entranceContext.getOrCreateScheduler().getSchedulerContext + .getOrCreateExecutorManager.asInstanceOf[EntranceExecutorManager] + + private def findEngineExecuteAsyncReturn(execId: String, sender: Sender, message: String): Option[EngineExecuteAsynReturn] = { + val serviceInstance = RPCUtils.getServiceInstanceFromSender(sender) + if (serviceInstance == null || serviceInstance.getInstance == null) { + warn(s"because of not support sender $sender, cannot update the message $message for execId $execId.") + return None + } + val engine = getEntranceExecutorManager.getEntranceExecutorByInstance(serviceInstance.getInstance) + if (engine.isEmpty) { + warn(s"${getEntranceExecutorManager.getClass.getSimpleName} cannot find a entranceEngine to update the message $message for execId $execId from $sender.") + None + } else { + val jobReturn = engine.flatMap(_.getEngineReturns.find(_.execId == execId)) + if (jobReturn.isEmpty) warn(s"${engine.get} cannot find a job to update the message $message for execId $execId from $sender, EngineReturns List is ${engine.map(_.getEngineReturns.map(_.execId).toList).get}.") + jobReturn + } + } + + def onOperate(execId: String, sender: Sender, op: Job => Unit, message: String): Unit = findEngineExecuteAsyncReturn(execId, sender, message).foreach { er => + er.notifyHeartbeat() + er.getJobId.flatMap(entranceContext.getOrCreateScheduler().get).foreach { + case job: Job => op(job) + case _ => + } + } + + private def askRetryWhenExecuteAsyncReturnIsEmpty(execId: String, sender: Sender, message: String) = + findEngineExecuteAsyncReturn(execId, sender, message).getOrElse { + Utils.tryQuietly(Thread.sleep(50)) + findEngineExecuteAsyncReturn(execId, sender, toString) + .getOrElse(throw new DWCRPCRetryException(s"please retry, since $execId cannot be consumed by entrance!")) + } + + @Receiver + override def taskLogReceiver(taskLog: ResponseTaskLog, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + onOperate(taskLog.execId, sender, entranceContext.getOrCreateLogManager().onLogUpdate(_, taskLog.log), "ResponseTaskLog") + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + private def updateExecutorActivityTime(serviceInstance: ServiceInstance) = { + if (null != serviceInstance) { + val engineConnExecutor = getEntranceExecutorManager.engineConnManager.getEngineConnExecutorCache().getOrDefault(serviceInstance, null) + if (null != engineConnExecutor) synchronized { + engineConnExecutor.updateLastUpdateTime() + } else { + warn(s"EngineConnExecutor ${serviceInstance.toString} cannot be found in engineConnExecutorCache") + } + } + } + + @Receiver + override def taskProgressReceiver(taskProgress: ResponseTaskProgress, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + Utils.tryAndWarn { + onOperate(taskProgress.execId, sender, job => { + entranceContext.getOrCreateEventListenerBus.post(EntranceProgressEvent(job, taskProgress.progress, taskProgress.progressInfo)) + entranceContext.getOrCreatePersistenceManager().onProgressUpdate(job, taskProgress.progress, taskProgress.progressInfo) + job.asInstanceOf[EntranceJob].setProgressInfo(taskProgress.progressInfo) + }, "ResponseTaskProgress") + } + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + @Receiver + override def taskStatusReceiver(taskStatus: ResponseTaskStatus, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + if (ExecutionNodeStatus.isCompleted(taskStatus.status)) + info(s"The execId ${taskStatus.execId} from engine $sender is completed with state ${taskStatus.status}.") + askRetryWhenExecuteAsyncReturnIsEmpty(taskStatus.execId, sender, s"ResponseTaskStatus(${taskStatus.execId}, ${taskStatus.status})") + .notifyStatus(taskStatus) + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + @Receiver + override def taskResultSizeReceiver(taskResultSize: ResponseTaskResultSize, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + askRetryWhenExecuteAsyncReturnIsEmpty(taskResultSize.execId, sender, "ResponseTaskResultSize") + .getJobId.flatMap(entranceContext.getOrCreateScheduler().get).foreach { + case j: Job => entranceContext.getOrCreatePersistenceManager().onResultSizeCreated(j, taskResultSize.resultSize) + case _ => + } + } + + @Receiver + override def taskResultSetReceiver(taskResultSet: ResponseTaskResultSet, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + onOperate(taskResultSet.execId, sender + , entranceContext.getOrCreatePersistenceManager() + .onResultSetCreated(_, AliasOutputExecuteResponse(taskResultSet.alias, taskResultSet.output)) + , "ResponseTaskResultSet") + } + + @Receiver + override def taskErrorReceiver(taskTaskError: ResponseTaskError, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender +// askRetryWhenExecuteAsyncReturnIsEmpty(taskTaskError.execId, sender, s"ResponseTaskError(${taskTaskError.execId}, ${taskTaskError.errorMsg})") +// .notifyError(taskTaskError.errorMsg) + onOperate(taskTaskError.execId, sender, entranceContext.getOrCreateLogManager().onLogUpdate(_, taskTaskError.errorMsg), "ResponseTaskErrorLog") + } + + private def addEngineExecutorStatusMonitor(): Unit = { + val task = new Runnable { + override def run(): Unit = { + val startTime = System.currentTimeMillis() + val engineExecutorCache = getEntranceExecutorManager.engineConnManager.getEngineConnExecutorCache() + if (engineExecutorCache.size() > 0) { + info(s"Entrance Executor cache num : ${engineExecutorCache.size()}") + } + val unActivityEngines = engineExecutorCache.asScala.filter(startTime - _._2.getLastUpdateTime() > EntranceConfiguration.ENTRANCE_ENGINE_LASTUPDATE_TIMEOUT.getValue.toLong).keySet + if (null != unActivityEngines && !unActivityEngines.isEmpty) { + info(s"There are ${unActivityEngines.size} unActivity engines.") + val engineList = new util.ArrayList[ServiceInstance]() + unActivityEngines.foreach(engine => { + engineList.add(engine) + if (engineList.size() >= GovernanceConstant.REQUEST_ENGINE_STATUS_BATCH_LIMIT) { + queryEngineStatusAndHandle(engineList, engineExecutorCache) + engineList.clear() + } + }) + if (!engineList.isEmpty) { + queryEngineStatusAndHandle(engineList, engineExecutorCache) + engineList.clear() + } + } + val endTime = System.currentTimeMillis() + if (endTime - startTime >= EntranceConfiguration.ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL.getValue.toLong) { + error("Query engines status costs longer time than query task interval, you should increase interval.") + } + } + } + Utils.defaultScheduler.scheduleWithFixedDelay(task, 10000, EntranceConfiguration.ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL.getValue.toLong, TimeUnit.MILLISECONDS) + info("Entrance engineStatusMonitor inited.") + } + + private def queryEngineStatusAndHandle(engineList: util.List[ServiceInstance], engineExecutorCache: util.Map[ServiceInstance, EngineConnExecutor]): Unit = { + val requestEngineStatus = RequestEngineStatusBatch(engineList) + Utils.tryAndError { + Sender.getSender(GovernanceCommonConf.MANAGER_SPRING_NAME.getValue).ask(requestEngineStatus) match { + case response: ResponseEngineStatusBatch => + if (null != response.msg) { + info(s"ResponseEngineStatusBatch msg : ${response.msg}") + } + if (response.engineStatus.size() != requestEngineStatus.engineList.size()) { + error("ResponseEngineStatusBatch engines size is not euqal requet.") + } + response.engineStatus.asScala.foreach(status => { + status._2 match { + case NodeExistStatus.UnExist => + warn(s"Engine ${status._1.toString} is Failed, now go to clear its task.") + endJobByEngineInstance(status._1, NodeStatus.Failed) + case NodeExistStatus.Exist | NodeExistStatus.Unknown => + val engineConnExecutor = engineExecutorCache.getOrDefault(status._1, null) + if (null != engineConnExecutor) { + Utils.tryCatch { + // todo check - only for engine with accessible executor + val requestNodeStatus = new RequestNodeStatus + Sender.getSender(status._1).ask(requestNodeStatus) match { + case rs: ResponseNodeStatus => + if (NodeStatus.isCompleted(rs.getNodeStatus)) { + endJobByEngineInstance(status._1, rs.getNodeStatus) + } else { + warn("Will update engineConnExecutor lastupdated time") + updateExecutorActivityTime(status._1) + } + case o: Any => + Utils.tryAndWarn(warn(s"Unknown response : ${EntranceConstant.GSON.toJson(o)} for request : ${EntranceConstant.GSON.toJson(requestNodeStatus)}")) + } + } { + case t: Throwable => + error(s"Failed to get status of engineConn : ${status._1.toString}, now end the job. ", t) + endJobByEngineInstance(status._1, NodeStatus.Failed) + } + } + case o: Any => + error(s"Status of engine ${status._1.toString} is ${status._2}") + } + }) + case _ => + error(s"Invalid response. request : ${EntranceConstant.GSON.toJson(requestEngineStatus)}") + } + } + } + + private def endJobByEngineInstance(engineServiceInstance: ServiceInstance, engineNodeStatus: NodeStatus) = { + Utils.tryQuietly { + val entranceExecutor = getEntranceExecutorManager.getEntranceExecutorByInstance(engineServiceInstance.getInstance).getOrElse(null) + if (null != entranceExecutor) { + entranceExecutor.getEngineReturns.foreach(er => { + er.notifyError(s"Engine has exited unexpectedly with status : ${engineNodeStatus}") + er.notifyStatus(ResponseTaskStatus(er.execId, ExecutionNodeStatus.Failed)) + }) + } else { + warn(s"Cannot find entranceExecutor for ${engineServiceInstance.toString}") + } + } + } +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala new file mode 100644 index 0000000000..7c5193537d --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala @@ -0,0 +1,189 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus._ +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, ResponseTaskStatus} +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Mark +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.EngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.UserWithCreator +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorState.ExecutorState +import com.webank.wedatasphere.linkis.scheduler.executer._ + +import scala.collection.mutable.ArrayBuffer + + +abstract class EntranceExecutor(val id: Long, val mark: Mark) extends Executor with Logging { + + + private implicit var userWithCreator: UserWithCreator = _ + + private var engineConnExecutor: EngineConnExecutor = _ + + protected val engineReturns = ArrayBuffer[EngineExecuteAsynReturn]() + + protected var interceptors: Array[ExecuteRequestInterceptor] = Array(LabelExecuteRequestInterceptor, JobExecuteRequestInterceptor) + + + def setInterceptors(interceptors: Array[ExecuteRequestInterceptor]) = if (interceptors != null && interceptors.nonEmpty) { + this.interceptors = interceptors + } + + + def setUser(user: String): Unit = userWithCreator = if (userWithCreator != null) UserWithCreator(user, userWithCreator.creator) + else UserWithCreator(user, null) + + def getUser = if (userWithCreator != null) userWithCreator.user else null + + def setCreator(creator: String): Unit = userWithCreator = if (userWithCreator != null) UserWithCreator(userWithCreator.user, creator) + else UserWithCreator(null, creator) + + def getCreator = if (userWithCreator != null) userWithCreator.creator else null + + + def getEngineConnExecutor(): EngineConnExecutor = this.engineConnExecutor + + def setEngineConnExecutor(engineConnExecutor: EngineConnExecutor): Unit = { + this.engineConnExecutor = engineConnExecutor + } + + def getInstance: ServiceInstance = getEngineConnExecutor().getServiceInstance + + private[execute] def getEngineReturns = engineReturns.toArray + + override def execute(executeRequest: ExecuteRequest): ExecuteResponse = { + var request: RequestTask = null + interceptors.foreach(in => request = in.apply(request, executeRequest)) + if (request.getProperties != null && + request.getProperties.containsKey(ReconnectExecuteRequestInterceptor.PROPERTY_EXEC_ID)) { + val execId = ReconnectExecuteRequestInterceptor.PROPERTY_EXEC_ID.toString + Utils.tryCatch { + getEngineConnExecutor().status(execId) + val engineReturn = new EngineExecuteAsynReturn(request, getInstance.getInstance, execId, _ => callback()) + engineReturns synchronized engineReturns += engineReturn + return engineReturn + } { t: Throwable => + error(s"Failed to get execId $execId status", t) + } + } + val engineReturn = callExecute(request) + engineReturns synchronized engineReturns += engineReturn + engineReturn + } + + protected def callback(): Unit = {} + + protected def callExecute(request: RequestTask): EngineExecuteAsynReturn + + override def toString: String = s"${getInstance.getApplicationName}Engine($getId, $getUser, $getCreator, ${getInstance.getInstance})" + + protected def killExecId(execId: String): Boolean = { + info(s"begin to send killExecId, execID: $execId") + Utils.tryAndError(getEngineConnExecutor().killTask(execId)) + true + } + + override def getId: Long = this.id + + override def state: ExecutorState = ExecutorState.Idle + + override def getExecutorInfo: ExecutorInfo = { + null + } + + def canEqual(other: Any): Boolean = other.isInstanceOf[EntranceExecutor] + + override def equals(other: Any): Boolean = other match { + case that: EntranceExecutor => + (that canEqual this) && + getEngineConnExecutor().equals(that.getEngineConnExecutor()) + case _ => false + } + + def getExecId(jobId: String): String = { + val erOption = engineReturns.find(_.getJobId.contains(jobId)) + if ( erOption.isDefined ) { + erOption.get.execId + } else { + null + } + } + + override def hashCode(): Int = { + getEngineConnExecutor().hashCode() + } +} + +class EngineExecuteAsynReturn(request: RequestTask, val instance: String, + val execId: String, callback: EngineExecuteAsynReturn => Unit) extends AsynReturnExecuteResponse with Logging { + getJobId.foreach(id => info("Job " + id + " received a execId " + execId + " from engine " + instance)) + + private var notifyJob: ExecuteResponse => Unit = _ + + private var error: Throwable = _ + + private var errorMsg: String = _ + + private var lastNotifyTime = System.currentTimeMillis + + def getLastNotifyTime = lastNotifyTime + + private[execute] def notifyStatus(responseEngineStatus: ResponseTaskStatus): Unit = { + lastNotifyTime = System.currentTimeMillis() + val response = responseEngineStatus.status match { + case Succeed => Some(SuccessExecuteResponse()) + case Failed | Cancelled | Timeout => Some(ErrorExecuteResponse(errorMsg, error)) + case _ => None + } + response.foreach { r => + getJobId.foreach(id => info("Job " + id + " with execId-" + execId + " from engine " + instance + " completed with state " + r)) + callback(this) + if (notifyJob == null) this synchronized (while (notifyJob == null) this.wait(1000)) + notifyJob(r) + } + } + + private[execute] def notifyHeartbeat(): Unit = { + lastNotifyTime = System.currentTimeMillis() + } + + private[execute] def notifyError(errorMsg: String): Unit = { + lastNotifyTime = System.currentTimeMillis() + this.errorMsg = errorMsg + } + + private[execute] def notifyError(errorMsg: String, t: Throwable): Unit = { + lastNotifyTime = System.currentTimeMillis() + this.errorMsg = errorMsg + this.error = t + } + + private[execute] def getJobId: Option[String] = { + val jobId = request.getProperties.get(JobExecuteRequestInterceptor.PROPERTY_JOB_ID) + jobId match { + case j: String => Option(j) + case _ => None + } + } + + override def notify(rs: ExecuteResponse => Unit): Unit = { + notifyJob = rs + this synchronized notify() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala new file mode 100644 index 0000000000..7c0871461b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala @@ -0,0 +1,161 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import java.util +import java.util.Date +import java.util.concurrent.atomic.AtomicLong + +import com.webank.wedatasphere.linkis.common.exception.WarnException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManager +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.{DefaultMarkReq, MarkReq, Policy} +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.impl.ComputationConcurrentEngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{Executor, ExecutorManager} +import com.webank.wedatasphere.linkis.scheduler.queue.{GroupFactory, Job, SchedulerEvent} +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.Duration + + +abstract class EntranceExecutorManager(groupFactory: GroupFactory, val engineConnManager: EngineConnManager) extends ExecutorManager with Logging { + + private val idGenerator = new AtomicLong(0) + + private val idToEngines = new util.HashMap[Long, EntranceExecutor] + + private val instanceToEngines = new util.HashMap[String, EntranceExecutor] + + def getOrCreateInterceptors(): Array[ExecuteRequestInterceptor] + + override def delete(executor: Executor): Unit = { + if (null != executor) { + executor.close() + val entranceExecutor = idToEngines.remove(executor.getId) + instanceToEngines.remove(entranceExecutor.getInstance.getInstance) + entranceExecutor.getEngineConnExecutor() match { + case current: ComputationConcurrentEngineConnExecutor => + case _ => engineConnManager.releaseEngineConnExecutor(entranceExecutor.getEngineConnExecutor(), entranceExecutor.mark) + } + } + } + + protected def createMarkReq(requestPersistTask: RequestPersistTask): MarkReq = { + val markReq = new DefaultMarkReq + markReq.setPolicyObj(Policy.Task) + markReq.setCreateService(requestPersistTask.getCreateService) + markReq.setDescription(requestPersistTask.getDescription) + markReq.setEngineConnCount(3) + val properties = if (requestPersistTask.getParams == null) new util.HashMap[String, String] + else { + val startupMap = TaskUtils.getStartupMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) + val properties = new JMap[String, String] + startupMap.foreach { case (k, v) => if (v != null && StringUtils.isNotEmpty(v.toString)) properties.put(k, v.toString) } + properties + } + // todo get default config from db + markReq.setProperties(properties) + markReq.setUser(requestPersistTask.getUmUser) + markReq.setLabels(LabelUtils.labelsToMap(requestPersistTask.getLabels)) + markReq + } + + + override def askExecutor(schedulerEvent: SchedulerEvent): Option[Executor] = schedulerEvent match { + case job: Job => + val executor = createExecutor(job) + if (executor != null) { + job match { + case entranceExecutionJob: EntranceExecutionJob => val task = entranceExecutionJob.getTask + task.asInstanceOf[RequestPersistTask].setEngineStartTime(new Date()) + case _ => + } + Some(executor) + } else None + + } + + override def askExecutor(schedulerEvent: SchedulerEvent, wait: Duration): Option[Executor] = schedulerEvent match { + case job: Job => + val startTime = System.currentTimeMillis() + var warnException: WarnException = null + var executor: Option[Executor] = None + while (System.currentTimeMillis - startTime < wait.toMillis && executor.isEmpty) + Utils.tryCatch(askExecutor(job)) { + case warn: WarnException => + this.warn("request engine failed!", warn) + warnException = warn + None + case t: Throwable => throw t + } match { + case Some(e) => executor = Option(e) + case _ => + if (System.currentTimeMillis - startTime < wait.toMillis) { + val interval = math.min(3000, wait.toMillis - System.currentTimeMillis + startTime) + //getOrCreateEngineManager().waitForIdle(interval) + } + } + if (warnException != null && executor.isEmpty) throw warnException + executor + } + + override def getById(id: Long): Option[Executor] = { + Option(idToEngines.get(id)) + } + + override def getByGroup(groupName: String): Array[Executor] = { + //TODO by peaceWong + null + } + + override protected def createExecutor(schedulerEvent: SchedulerEvent): EntranceExecutor = schedulerEvent match { + case job: EntranceJob => + job.getTask match { + case requestPersistTask: RequestPersistTask => + // CreateMarkReq + val markReq = createMarkReq(requestPersistTask) + // getMark + val mark = engineConnManager.applyMark(markReq) + // getEngineConn Executor + job.getLogListener.foreach(_.onLogUpdate(job, "Background is starting a new engine for you, it may take several seconds, please wait")) + val engineConnExecutor = engineConnManager.getAvailableEngineConnExecutor(mark) + //TODO 修改Executor创建为builder模式 + val entranceEntranceExecutor = new DefaultEntranceExecutor(idGenerator.incrementAndGet(), mark) + idToEngines.put(entranceEntranceExecutor.getId, entranceEntranceExecutor) + instanceToEngines.put(engineConnExecutor.getServiceInstance.getInstance, entranceEntranceExecutor) + entranceEntranceExecutor.setEngineConnExecutor(engineConnExecutor) + entranceEntranceExecutor.setInterceptors(getOrCreateInterceptors()) + job.getLogListener.foreach(_.onLogUpdate(job, s" Congratulations! Your new engine has started successfully,Engine are ${engineConnExecutor.getServiceInstance}")) + entranceEntranceExecutor + case _ => + throw new EntranceErrorException(20001, "Task is not requestPersistTask, cannot to create Executor") + } + case _ => + throw new EntranceErrorException(20001, "Task is not EntranceJob, cannot to create Executor") + } + + override def shutdown(): Unit = {} + + def getEntranceExecutorByInstance(instance: String): Option[EntranceExecutor] = { + Option(instanceToEngines.get(instance)) + } + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala new file mode 100644 index 0000000000..9c2c7a4a04 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala @@ -0,0 +1,196 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import java.util +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.log.LogUtils +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.event._ +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.EngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{CompletedExecuteResponse, ErrorExecuteResponse} +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState._ +import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} + + +abstract class EntranceJob extends Job { + + private var creator: String = _ + private var user: String = _ + private var params: util.Map[String, Any] = new util.HashMap[String, Any](1) + private var task: Task = _ + + private var entranceListenerBus: Option[EntranceEventListenerBus[EntranceEventListener, EntranceEvent]] = None + private var progressInfo: Array[JobProgressInfo] = Array.empty + private val persistedResultSets = new AtomicInteger(0) + private var resultSize = -1 + private var entranceContext: EntranceContext = _ + + def getTask: Task = task + + def setTask(task: Task): Unit = this.task = task + + def setCreator(creator: String): Unit = this.creator = creator + + def getCreator: String = creator + + def setUser(user: String): Unit = this.user = user + + def getUser: String = user + + def setParams(params: util.Map[String, Any]): Unit = this.params = params + + def getParams: util.Map[String, Any] = params + + def setEntranceListenerBus(entranceListenerBus: EntranceEventListenerBus[EntranceEventListener, EntranceEvent]): Unit = + this.entranceListenerBus = Option(entranceListenerBus) + + def getEntranceListenerBus = this.entranceListenerBus + + def setProgressInfo(progressInfo: Array[JobProgressInfo]): Unit = this.progressInfo = progressInfo + + def getProgressInfo: Array[JobProgressInfo] = this.progressInfo + + def setEntranceContext(entranceContext: EntranceContext): Unit = this.entranceContext = entranceContext + + def getEntranceContext: EntranceContext = this.entranceContext + + + def setResultSize(resultSize: Int): Unit = { + this.resultSize = resultSize + persistedResultSets synchronized persistedResultSets.notify() + } + + def incrementResultSetPersisted(): Unit = { + persistedResultSets.incrementAndGet() + persistedResultSets synchronized persistedResultSets.notify() + } + + protected def isWaitForPersistedTimeout(startWaitForPersistedTime: Long): Boolean = + System.currentTimeMillis - startWaitForPersistedTime >= EntranceConfiguration.JOB_MAX_PERSIST_WAIT_TIME.getValue.toLong + + + override def beforeStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = { + if (SchedulerEventState.isCompleted(toState) && (resultSize < 0 || persistedResultSets.get() < resultSize)) { + val startWaitForPersistedTime = System.currentTimeMillis + persistedResultSets synchronized { + while ((resultSize < 0 || persistedResultSets.get() < resultSize) && getErrorResponse == null && !isWaitForPersistedTimeout(startWaitForPersistedTime)) + persistedResultSets.wait(3000) + } + if (isWaitForPersistedTimeout(startWaitForPersistedTime)) onFailure("persist resultSets timeout!", new EntranceErrorException(20305, "persist resultSets timeout!")) + if (isSucceed && getErrorResponse != null) { + val _toState = if (getErrorResponse.t == null) Cancelled else Failed + transition(_toState) + return + } + } + super.beforeStateChanged(fromState, toState) + } + + override def afterStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = { + if (SchedulerEventState.isRunning(toState)) { + def setEngineInstance(task: Task): Unit = task match { + case requestTask: RequestPersistTask => getExecutor match { + case engine: EntranceExecutor => requestTask.setEngineInstance(engine.getInstance.getInstance) + case _ => + } + case haTask: HaPersistenceTask => setEngineInstance(haTask.task) + case _ => + } + + setEngineInstance(task) + } + super.afterStateChanged(fromState, toState) + toState match { + case Scheduled => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is Scheduled. Please wait it to run."))) + case WaitForRetry => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is turn to retry. Please wait it to schedule."))) + case Running => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is Running now. Please wait it to complete."))) + //TODO job start event + case _ if SchedulerEventState.isCompleted(toState) => + endTime = System.currentTimeMillis() + if (getJobInfo != null) getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo(getJobInfo.getMetric))) + if (isSucceed) + getLogListener.foreach(_.onLogUpdate(this, + LogUtils.generateInfo("Congratulations. Your job completed with status Success."))) + else getLogListener.foreach(_.onLogUpdate(this, + LogUtils.generateInfo(s"Sorry. Your job completed with a status $toState. You can view logs for the reason."))) + this.setProgress(1.0f) + entranceListenerBus.foreach(_.post(EntranceProgressEvent(this, 1.0f, this.getProgressInfo))) + this.getProgressListener.foreach(listener => listener.onProgressUpdate(this, 1.0f, Array[JobProgressInfo]())) + case _ => + } + entranceListenerBus.foreach(_.post(EntranceJobEvent(this.getId))) + } + + override def onFailure(errorMsg: String, t: Throwable): Unit = { + this.entranceListenerBus.foreach(_.post( + EntranceLogEvent(this, LogUtils.generateERROR(s"Sorry, your job executed failed with reason: $errorMsg")))) + super.onFailure(errorMsg, t) + } + + override protected def transitionCompleted(executeCompleted: CompletedExecuteResponse): Unit = { + executeCompleted match { + case error: ErrorExecuteResponse if RPCUtils.isReceiverNotExists(error.t) => + entranceListenerBus.foreach(_.post(MissingEngineNotifyEvent(this, error.t, getExecutor))) + case _ => + } + Utils.tryAndErrorMsg(clearInstanceInfo())("Failed to clear executor") + super.transitionCompleted(executeCompleted) + } + + private def clearInstanceInfo(): Unit = { + val executorManager = entranceContext.getOrCreateScheduler().getSchedulerContext.getOrCreateExecutorManager + executorManager.delete(getExecutor) + } + + def transitionCompleted(executeCompleted: CompletedExecuteResponse, reason: String): Unit = { + info("Job directly completed with reason: " + reason) + transitionCompleted(executeCompleted) + } + + override protected def isJobShouldRetry(errorExecuteResponse: ErrorExecuteResponse): Boolean = isJobSupportRetry && errorExecuteResponse != null && + (if (RPCUtils.isReceiverNotExists(errorExecuteResponse.t)) { + getExecutor match { + case e: EntranceExecutor => + val instance = e.getInstance.getInstance + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateSystemWarn(s"Since the submitted engine rejects the connection, the system will automatically retry and exclude the engine $instance.(由于提交的引擎拒绝连接,系统将自动进行重试,并排除引擎 $instance.)"))) + case _ => + } + true + } else super.isJobShouldRetry(errorExecuteResponse)) + + def operation[T](operate: EntranceExecutor => T ): T = { + this.getExecutor match { + case entranceExecutor: EntranceExecutor => + operate(entranceExecutor) + case _ => throw new EntranceErrorException(10000, "不支持的操作") + } + + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala similarity index 81% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala index aa79e922e3..188680df82 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala @@ -16,28 +16,26 @@ package com.webank.wedatasphere.linkis.entrance.execute -import com.webank.wedatasphere.linkis.protocol.engine.{RequestTask, RequestTaskExecute} +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, RequestTaskExecute} import com.webank.wedatasphere.linkis.scheduler.executer.{ExecuteRequest, JobExecuteRequest} import scala.collection.JavaConversions -/** - * Created by enjoyyin on 2018/9/17. - */ + trait ExecuteRequestInterceptor { def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask } -object LockExecuteRequestInterceptor extends ExecuteRequestInterceptor { +object LabelExecuteRequestInterceptor extends ExecuteRequestInterceptor { override def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask = executeRequest match { - case lock: LockExecuteRequest => - val rq = if(requestTask == null) { + case labelExecuteRequest: LabelExecuteRequest => + val rq = if (requestTask == null) { val requestTask = new RequestTaskExecute requestTask.setCode(executeRequest.code) requestTask } else requestTask - rq.setLock(lock.lock) + rq.setLabels(labelExecuteRequest.labels) rq case _ => requestTask } @@ -87,15 +85,3 @@ object RuntimePropertiesExecuteRequestInterceptor extends ExecuteRequestIntercep case _ => requestTask } } - -//object RunTypeExecuteRequestInterceptor extends ExecuteRequestInterceptor{ -// private val runType:String = "runType" -// override def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask = { -// executeRequest match { -// case r:RunTypeExecuteRequest => -// requestTask.data(runType, r.runType) -// case _ => -// } -// requestTask -// } -//} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala similarity index 86% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala index dbd09ce10a..7dbe9c4351 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala @@ -16,15 +16,15 @@ package com.webank.wedatasphere.linkis.entrance.execute -/** - * Created by enjoyyin on 2018/9/15. - */ +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + trait ReconnectExecuteRequest { val execId: String } -trait LockExecuteRequest { - val lock: String +trait LabelExecuteRequest { + val labels: java.util.List[Label[_]] } trait StorePathExecuteRequest { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala new file mode 100644 index 0000000000..a86227ddf9 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute.impl + +import com.webank.wedatasphere.linkis.entrance.execute._ +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManager +import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener +import com.webank.wedatasphere.linkis.scheduler.queue.GroupFactory + +/** + * Created by enjoyyin on 2018/9/26. + */ +class EntranceExecutorManagerImpl(groupFactory: GroupFactory, + engineConnManager: EngineConnManager) extends EntranceExecutorManager(groupFactory, engineConnManager) { + + + override def getOrCreateInterceptors(): Array[ExecuteRequestInterceptor] = Array(JobExecuteRequestInterceptor, + LabelExecuteRequestInterceptor, ReconnectExecuteRequestInterceptor, StorePathExecuteRequestInterceptor, RuntimePropertiesExecuteRequestInterceptor) + + override def setExecutorListener(engineListener: ExecutorListener): Unit = {} +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala similarity index 88% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala index 0d88e5afdb..b966dc6d42 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,16 +16,16 @@ package com.webank.wedatasphere.linkis.entrance.interceptor import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * Created by enjoyyin on 2018/9/4. - */ + + trait EntranceInterceptor { /** * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. - * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * * @param task * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) * @return diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala similarity index 89% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala index 3b14958a6c..4a3101d983 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala @@ -15,18 +15,18 @@ */ package com.webank.wedatasphere.linkis.entrance.interceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask + +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/12/5 * Description: this interceptor is used to complete code with run type for * further use in engine */ class RuntypeInterceptor extends EntranceInterceptor { - override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType.toLowerCase() match { case "python" | "py" | "pyspark" => val code = requestPersistTask.getExecutionCode requestPersistTask.setExecutionCode("%python\n" + code) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala similarity index 79% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala index 2a8469c5db..2f648b7a9a 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala @@ -18,11 +18,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/20 - * Description: - */ -case class CodeCheckException(errCode:Int, - errDesc:String) extends ErrorException(errCode, errDesc){ + +case class CodeCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala new file mode 100644 index 0000000000..47bb4a12df --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class LabelCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala index 708b2a8dcf..3d4b2e43b1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala @@ -18,11 +18,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/20 - * Description: - */ -case class LimitCheckException(errCode:Int, - errDesc:String) extends ErrorException(errCode, errDesc) { + +case class LimitCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala index 7ab4a857b6..8db8a6a3e4 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala @@ -18,12 +18,9 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/23 - * Description: - */ -case class LogPathCreateException(errCode:Int, - errDesc:String) - extends ErrorException(errCode,errDesc){ + +case class LogPathCreateException(errCode: Int, + errDesc: String) + extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala similarity index 80% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala index 273e2a78a9..f91767bf53 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala @@ -18,12 +18,9 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/22 - * Description: - */ -case class PythonCodeCheckException(errCode:Int, - errDesc:String)extends ErrorException(errCode, errDesc) { + +case class PythonCodeCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala index b371fdacbe..2b965e291f 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala @@ -18,10 +18,7 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/19 - * Description: - */ -case class VarSubstitutionException(errCode:Int, - errDesc:String) extends ErrorException(errCode,errDesc){ + +case class VarSubstitutionException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala similarity index 92% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala index 26629f847a..943b1b298f 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala @@ -18,13 +18,10 @@ import java.lang import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.cs.CSEntranceHelper import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * @author peacewong - * @date 2020/3/24 18:28 - */ + class CSEntranceInterceptor extends EntranceInterceptor with Logging { override def apply(task: Task, logAppender: lang.StringBuilder): Task = { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala new file mode 100644 index 0000000000..a9e1911657 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala @@ -0,0 +1,104 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import java.lang +import java.util.regex.Pattern + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import org.slf4j.{Logger, LoggerFactory} + +import scala.util.matching.Regex + + +class CommentInterceptor extends EntranceInterceptor { + /** + * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 + * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * + * @param task + * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) + * @return + */ + override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType match { + case "sql" | "hql" => requestPersistTask.setExecutionCode(SQLCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "python" | "py" => requestPersistTask.setExecutionCode(PythonCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "scala" | "java" => requestPersistTask.setExecutionCode(ScalaCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "sh" | "shell" => + case _ => + } + requestPersistTask + case _ => task + } +} + +trait CommentHelper { + val commentPattern: Regex + + def dealComment(code: String): String +} + +object SQLCommentHelper extends CommentHelper { + override val commentPattern: Regex = """\s*--.+\s*""".r.unanchored + private val comment = "(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/|#.*?$|" + private val logger: Logger = LoggerFactory.getLogger(getClass) + + override def dealComment(code: String): String = { + try { + val p = Pattern.compile(comment) + val sql = p.matcher(code).replaceAll("$1") + sql + } catch { + case e: Exception => logger.warn("sql comment failed") + code + case t: Throwable => logger.warn("sql comment failed") + code + } + } +} + +object PythonCommentHelper extends CommentHelper { + override val commentPattern: Regex = """^\s*#.+\s*""".r.unanchored + val pythonCommentPattern: String = "(?ms)([\"'](?:|[^'])*['\"])|#.*?$|/\\*.*?\\*/" + + override def dealComment(code: String): String = { + code + } +} + + +object ScalaCommentHelper extends CommentHelper { + override val commentPattern: Regex = """^\s*//.+\s*""".r.unanchored + private val scalaCommentPattern: String = "(?ms)([\"'](?:|[^'])*['\"])|//.*?$|/\\*.*?\\*/" + + override def dealComment(code: String): String = code +} + + +object CommentMain { + def main(args: Array[String]): Unit = { + val sqlCode = "select * from default.user;--你好;show tables" + val sqlCode1 = "select * from default.user--你好;show tables" + println(SQLCommentHelper.dealComment(sqlCode)) + } +} + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala similarity index 81% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala index 334960e7ac..3ac8e8057e 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,7 +13,6 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl - import java.text.SimpleDateFormat import java.util import java.util.{Calendar, Date} @@ -24,7 +20,7 @@ import java.util.{Calendar, Date} import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.exception.VarSubstitutionException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils import com.webank.wedatasphere.linkis.protocol.variable.{RequestQueryAppVariable, ResponseQueryVariable} @@ -37,9 +33,7 @@ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.util.control.Exception._ -/** - * Created by enjoyyin on 11/14/17. - */ + object CustomVariableUtils extends Logging { //hql sql jdbc to sql python to py val SQL_TYPE = "sql" @@ -49,36 +43,37 @@ object CustomVariableUtils extends Logging { val R_TYPE:String = "r" val RUN_DATE = "run_date" val TEAM:String = "team" - val SHELL_TYPE:String="shell" /** * date Format */ val dateFormat = new SimpleDateFormat("yyyyMMdd") val dateFormat_std = new SimpleDateFormat("yyyy-MM-dd") + /** * replace custom variable * 1. Get the user-defined variable from the code and replace it - * 2. If 1 is not done, then get the user-defined variable from args and replace it. - * 3. If 2 is not done, get the user-defined variable from the console and replace it. - + * * 2. If 1 is not done, then get the user-defined variable from args and replace it. + * * 3. If 2 is not done, get the user-defined variable from the console and replace it. + * * 1. 从代码中得到用户定义的变量,进行替换 * 2. 如果1没有做,那么从args中得到用户定义的变量,进行替换 * 3. 如果2没有做,从CS中得到用户定义的变量,进行替换 *3. 如果3没有做,从控制台中得到用户定义的变量,进行替换 + * * @param task : requestPersistTask * @return */ def replaceCustomVar(task: Task, runType: String): (Boolean, String) = { - val code:String = task.asInstanceOf[RequestPersistTask].getExecutionCode - val umUser:String = task.asInstanceOf[RequestPersistTask].getUmUser + val code: String = task.asInstanceOf[RequestPersistTask].getExecutionCode + val umUser: String = task.asInstanceOf[RequestPersistTask].getUmUser var codeType = SQL_TYPE runType match { - case "hql" | "sql" | "jdbc" | "hive" | "psql" | "essql" => codeType = SQL_TYPE - case "python" => codeType = PY_TYPE + case "hql" | "sql" | "jdbc" | "hive" => codeType = SQL_TYPE + case "python" | "py" => codeType = PY_TYPE case "java" => codeType = JAVA_TYPE - case "scala" | "esjson" => codeType = SCALA_TYPE - case "shell" | "sh" => codeType = SHELL_TYPE + case "scala" => codeType = SCALA_TYPE + case "sh" | "shell" => codeType = SQL_TYPE case _ => return (false, code) } @@ -101,7 +96,7 @@ object CustomVariableUtils extends Logging { } else { nameAndType(key) = StringType(value) } - } + } } } @@ -110,26 +105,26 @@ object CustomVariableUtils extends Logging { putNameAndType(nameAndValue) task match { - case requestPersistTask:RequestPersistTask => + case requestPersistTask: RequestPersistTask => /* Perform the second step to replace the parameters passed in args*/ /* 进行第二步,对args传进的参数进行替换*/ val variableMap = TaskUtils.getVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) - .map{case (k, v) => k -> v.asInstanceOf[String]} + .map { case (k, v) => k -> v.asInstanceOf[String] } putNameAndType(variableMap) case _ => } - /* Go to the four step and take the user's parameters to the cloud-publicservice module.*/ - /*进行第四步,向cloud-publicservice模块去拿用户的参数*/ + /* Go to the four step and take the user's parameters to the linkis-ps-publicservice module.*/ + /*进行第四步,向linkis-ps-publicservice模块去拿用户的参数*/ val sender = Sender.getSender(EntranceConfiguration.CLOUD_CONSOLE_VARIABLE_SPRING_APPLICATION_NAME.getValue) task match { - case requestPersistTask:RequestPersistTask => - val umUser:String = requestPersistTask.getUmUser - val creator:String = requestPersistTask.getRequestApplicationName - val runType:String = requestPersistTask.getRunType - val requestQueryAppVariable:RequestQueryAppVariable = RequestQueryAppVariable(umUser, creator, runType) - val response:ResponseQueryVariable = sender.ask(requestQueryAppVariable).asInstanceOf[ResponseQueryVariable] + case requestPersistTask: RequestPersistTask => + val umUser: String = requestPersistTask.getUmUser + val creator: String = requestPersistTask.getRequestApplicationName + val runType: String = requestPersistTask.getRunType + val requestQueryAppVariable: RequestQueryAppVariable = RequestQueryAppVariable(umUser, creator, runType) + val response: ResponseQueryVariable = sender.ask(requestQueryAppVariable).asInstanceOf[ResponseQueryVariable] val keyAndValue = response.getKeyAndValue - val keyAndValueScala:mutable.Map[String, String] = keyAndValue + val keyAndValueScala: mutable.Map[String, String] = keyAndValue putNameAndType(keyAndValueScala) case _ => } @@ -163,59 +158,55 @@ object CustomVariableUtils extends Logging { */ def parserVar(code: String, nameAndType: mutable.Map[String, VariableType]): String = { - val codeReg = "\\$\\{\\s*[A-Za-z][A-Za-z0-9_]*\\s*[\\+\\-\\*/]?\\s*[A-Za-z0-9_\\.]*\\s*\\}".r - val calReg = "(\\s*[A-Za-z][A-Za-z0-9_]*\\s*)([\\+\\-\\*/]?)(\\s*[A-Za-z0-9_\\.]*\\s*)".r + val codeReg = "\\$\\{\\s*[A-Za-z][A-Za-z0-9_\\.]*\\s*[\\+\\-\\*/]?\\s*[A-Za-z0-9_\\.]*\\s*\\}".r + val calReg = "(\\s*[A-Za-z][A-Za-z0-9_\\.]*\\s*)([\\+\\-\\*/]?)(\\s*[A-Za-z0-9_\\.]*\\s*)".r + val parseCode = new StringBuilder + val codes = codeReg.split(code) val expressionCache = mutable.HashSet[String]() - var targetCode = code - var noChange = false - while (!noChange && codeReg.findFirstIn(targetCode).isDefined) { - var i = 0 - val parseCode = new StringBuilder - val codes = codeReg.split(targetCode) - codeReg.findAllIn(targetCode).foreach(str => { - calReg.findFirstMatchIn(str).foreach(ma => { - i = i + 1 - val name = ma.group(1) - val signal = ma.group(2) - val bValue = ma.group(3) - - if (name == null || name.trim.isEmpty) { - throw VarSubstitutionException(20041,s"[$str] replaced var is null") + + var i = 0 + + codeReg.findAllIn(code).foreach(str => { + calReg.findFirstMatchIn(str).foreach(ma => { + i = i + 1 + val name = ma.group(1) + val signal = ma.group(2) + val bValue = ma.group(3) + + if (name == null || name.trim.isEmpty) { + throw VarSubstitutionException(20041,s"[$str] replaced var is null") + } else { + var expression = name.trim + val varType = nameAndType.get(name.trim).orNull + if (varType == null) { + warn(s"Use undefined variables or use the set method: [$str](使用了未定义的变量或者使用了set方式:[$str])") + parseCode ++= codes(i - 1) ++ str } else { - var expression = name.trim - val varType = nameAndType.get(name.trim).orNull - if (varType == null) { - warn(s"Use undefined variables or use the set method: [$str](使用了未定义的变量或者使用了set方式:[$str])") - parseCode ++= codes(i - 1) ++ str - } else { - var res: String = varType.getValue - if (signal != null && !signal.trim.isEmpty) { - if (bValue == null || bValue.trim.isEmpty) { - throw VarSubstitutionException(20042, s"[$str] expression is not right, please check") - } else { - expression = expression + "_" + signal.trim + "_" + bValue.trim - res = varType.calculator(signal.trim, bValue.trim) - } + var res: String = varType.getValue + if (signal != null && !signal.trim.isEmpty) { + if (bValue == null || bValue.trim.isEmpty) { + throw VarSubstitutionException(20042, s"[$str] expression is not right, please check") + } else { + expression = expression + "_" + signal.trim + "_" + bValue.trim + res = varType.calculator(signal.trim, bValue.trim) } - if (!expressionCache.contains(expression)) { - info(s"Variable expression [$str] = $res(变量表达式[$str] = $res)") - //println(s"变量表达式[$str] = $res") - expressionCache += expression - } - //println(s"变量表达式序号:$i\t[$str] = $res") - parseCode ++= codes(i - 1) ++ res } + if (!expressionCache.contains(expression)) { + info(s"Variable expression [$str] = $res(变量表达式[$str] = $res)") + //println(s"变量表达式[$str] = $res") + expressionCache += expression + } + //println(s"变量表达式序号:$i\t[$str] = $res") + parseCode ++= codes(i - 1) ++ res } - }) + } }) - if (i == codes.length - 1) { - parseCode ++= codes(i) - } - val parsedCode = org.apache.commons.lang.StringUtils.strip(deleteUselessSemicolon(parseCode)) - if (targetCode.equals(parsedCode)) noChange = true - targetCode = parsedCode + }) + if (i == codes.length - 1) { + parseCode ++= codes(i) } - targetCode + val parsedCode = deleteUselessSemicolon(parseCode) + org.apache.commons.lang.StringUtils.strip(parsedCode) // Utils.trimBlank() } @@ -310,8 +301,6 @@ object CustomVariableUtils extends Logging { case SCALA_TYPE => varString = """\s*//@set\s*.+\s*""" errString = """\s*//@.+""" case JAVA_TYPE => varString = """\s*!!@set\s*.+\s*""" - case SHELL_TYPE => varString = """\s*#@set\s*.+\s*""" - errString = """\s*#@""" } val customRegex = varString.r.unanchored @@ -387,7 +376,7 @@ object CustomVariableUtils extends Logging { def main(args: Array[String]): Unit = { val code = "--@set a=1\n--@set b=2\nselect ${a +2},${a + 1},${a},${a },${b},${b}" val task = new RequestPersistTask - val args:java.util.Map[String, Object] = new util.HashMap[String, Object]() + val args: java.util.Map[String, Object] = new util.HashMap[String, Object]() args.put(RUN_DATE, "20181030") task.setExecutionCode(code) task.setParams(args) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala similarity index 83% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala index f3a65260ee..890963680b 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala @@ -19,11 +19,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * created by enjoyyin on 2018/10/19 - * Description: For database information completion(用于数据库信息补全) - */ -class DBInfoCompleteInterceptor extends EntranceInterceptor{ + +class DBInfoCompleteInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { //todo Database information completion(数据库信息补全) task diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala index e6c54a95f4..6b4eb7a131 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala @@ -22,17 +22,15 @@ import com.webank.wedatasphere.linkis.common.conf.CommonVars import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.common.log.LogUtils import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.exception.{PythonCodeCheckException, ScalaCodeCheckException} -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import org.apache.commons.lang.StringUtils import org.slf4j.{Logger, LoggerFactory} import scala.collection.mutable.ArrayBuffer -/** - * created by enjoyyin on 2018/10/19 - * Description: - */ + abstract class Explain extends Logging { /** * 用于检查code是否符合规范 @@ -50,18 +48,18 @@ object SparkExplain extends Explain { private val sy = Pattern.compile("sys\\.") private val scCancelAllJobs = Pattern.compile("sc\\.cancelAllJobs(\\s*)") private val runtime = Pattern.compile("Runtime\\.getRuntime") + private val LINE_BREAK = "\n" private val LOG:Logger = LoggerFactory.getLogger(getClass) override def authPass(code: String, error: StringBuilder): Boolean = { - + if (EntranceConfiguration.IS_QML.getValue) { + return true + } if (scStop.matcher(code).find()) { error.append("Authentication error: sc.stop() is not allowed in IDE.") false } else if (systemExit.matcher(code).find()) { error.append("Authentication error: System.exit(exitCode) is not allowed in IDE.") false - } else if (sy.matcher(code).find()) { - error.append("Authentication error: the package `sys` cannot be used in IDE.") - false } else if (scCancelAllJobs.matcher(code).find()) { error.append("Authentication error: sc.cancelAllJobs() is not allowed in IDE.") false @@ -82,6 +80,7 @@ object SQLExplain extends Explain { val SQL_APPEND_LIMIT:String = " limit " + SQL_DEFAULT_LIMIT.getValue val DROP_TABLE_SQL = "\\s*drop\\s+table\\s+\\w+\\s*" val CREATE_DATABASE_SQL = "\\s*create\\s+database\\s+\\w+\\s*" + private val IDE_ALLOW_NO_LIMIT_REGEX = "--set\\s*ide.engine.no.limit.allow\\s*=\\s*true".r.unanchored private val LINE_BREAK = "\n" private val COMMENT_FLAG = "--" val SET_OWN_USER = "set owner user" @@ -98,20 +97,31 @@ object SQLExplain extends Explain { /** * to deal with sql limit - * @param executionCode sql code + * + * @param executionCode sql code * @param requestPersistTask use to store inited logs */ - def dealSQLLimit(executionCode:String, requestPersistTask: RequestPersistTask, logAppender: java.lang.StringBuilder):Unit = { - val fixedCode:ArrayBuffer[String] = new ArrayBuffer[String]() - executionCode.split(";") foreach { singleCode => + def dealSQLLimit(executionCode: String, requestPersistTask: RequestPersistTask, logAppender: java.lang.StringBuilder): Unit = { + val fixedCode: ArrayBuffer[String] = new ArrayBuffer[String]() + val tempCode = SQLCommentHelper.dealComment(executionCode) + val isNoLimitAllowed = Utils.tryCatch { + IDE_ALLOW_NO_LIMIT_REGEX.findFirstIn(executionCode).isDefined + } { + case e: Exception => logger.warn("sql limit check error happens") + executionCode.contains(IDE_ALLOW_NO_LIMIT) + } + if (isNoLimitAllowed) logAppender.append(LogUtils.generateWarn("请注意,SQL全量导出模式打开\n")) + tempCode.split(";") foreach { singleCode => if (isSelectCmd(singleCode)){ val trimCode = singleCode.trim - if (isSelectCmdNoLimit(trimCode) && !executionCode.contains(IDE_ALLOW_NO_LIMIT)){ - logAppender.append(LogUtils.generateWarn(s"You submitted a sql $trimCode without limit, program will add limit 5000 to your sql") + "\n") - fixedCode += (trimCode + SQL_APPEND_LIMIT) - }else if (isSelectOverLimit(singleCode) && !executionCode.contains(IDE_ALLOW_NO_LIMIT)){ + if (isSelectCmdNoLimit(trimCode) && !isNoLimitAllowed){ + logAppender.append(LogUtils.generateWarn(s"You submitted a sql without limit, DSS will add limit 5000 to your sql") + "\n") + //将注释先干掉,然后再进行添加limit + val realCode = cleanComment(trimCode) + fixedCode += (realCode + SQL_APPEND_LIMIT) + }else if (isSelectOverLimit(singleCode) && !isNoLimitAllowed){ val trimCode = singleCode.trim - logAppender.append(LogUtils.generateWarn(s"You submitted a sql $trimCode with limit exceeding 5000, it is not allowed. Program will change your limit to 5000") + "\n") + logAppender.append(LogUtils.generateWarn(s"You submitted a sql with limit exceeding 5000, it is not allowed. DSS will change your limit to 5000") + "\n") fixedCode += repairSelectOverLimit(trimCode) }else{ fixedCode += singleCode.trim @@ -236,6 +246,9 @@ object PythonExplain extends Explain{ */ private val SC_STOP = """sc\.stop""".r.unanchored override def authPass(code: String, error: StringBuilder): Boolean = { + if (EntranceConfiguration.IS_QML.getValue) { + return true + } code.split(System.lineSeparator()) foreach {code => if (IMPORT_SYS_MOUDLE.findAllIn(code).nonEmpty || FROM_SYS_IMPORT.findAllIn(code).nonEmpty) throw PythonCodeCheckException(20070, "can not use sys module") @@ -257,6 +270,9 @@ object ScalaExplain extends Explain{ private val runtime = """Runtime.getRunTime""".r.unanchored private val LOG:Logger = LoggerFactory.getLogger(getClass) override def authPass(code: String, error: StringBuilder): Boolean = { + if (EntranceConfiguration.IS_QML.getValue) { + return true + } code match { case systemExit() => LOG.error("scala code can not use System.exit") throw ScalaCodeCheckException(20074, "scala code can not use System.exit") diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala new file mode 100644 index 0000000000..826940ecd1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import java.lang + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.LabelCheckException +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.protocol.task.Task +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +class LabelCheckInterceptor extends EntranceInterceptor { + + /** + * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 + * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * + * @param task + * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) + * @return + */ + override def apply(task: Task, logAppender: lang.StringBuilder): Task = { + task match { + case requestPersistTask: RequestPersistTask => + val labels = requestPersistTask.getLabels + checkEngineTypeLabel(labels) + checkUserCreatorLabel(labels) + task + case _ => task + } + } + + private def checkEngineTypeLabel(labels: java.util.List[Label[_]]): Unit = { + val engineTypeLabelOption = labels.find(_.isInstanceOf[EngineTypeLabel]) + if (engineTypeLabelOption.isDefined) { + val engineLabel = engineTypeLabelOption.get.asInstanceOf[EngineTypeLabel] + if (StringUtils.isNotBlank(engineLabel.getEngineType)) { + return + } + } + throw LabelCheckException(50079, "engineTypeLabel must be need") + } + + + private def checkUserCreatorLabel(labels: java.util.List[Label[_]]): Unit = { + val userCreatorLabelOption = labels.find(_.isInstanceOf[UserCreatorLabel]) + if (userCreatorLabelOption.isDefined) { + val userCreator = userCreatorLabelOption.get.asInstanceOf[UserCreatorLabel] + if (StringUtils.isNotBlank(userCreator.getUser)) { + return + } + } + throw LabelCheckException(50079, "UserCreatorLabel must be need") + } + + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala new file mode 100644 index 0000000000..9b806e6a1b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import com.webank.wedatasphere.linkis.common.exception.ErrorException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.cache.GlobalConfigurationKeyValueCache +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.LogPathCreateException +import com.webank.wedatasphere.linkis.entrance.parser.ParserUtils +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task + +/** + * Description:Log path generation interceptor, used to set the path log of the task(日志路径生成拦截器, 用于设置task的路径日志) + */ +class LogPathCreateInterceptor extends EntranceInterceptor with Logging { + + @throws[ErrorException] + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { + task match { + case requestPersistTask: RequestPersistTask => Utils.tryThrow { + ParserUtils.generateLogPath(requestPersistTask, Utils.tryAndWarn(GlobalConfigurationKeyValueCache.getCacheMap(requestPersistTask))) + requestPersistTask + } { + case e: ErrorException => + val exception: LogPathCreateException = LogPathCreateException(20075, "Failed to get logPath(获取logPath失败),reason: " + e.getMessage) + exception.initCause(e) + exception + case t: Throwable => + val exception: LogPathCreateException = LogPathCreateException(20075, "Failed to get logPath(获取logPath失败), reason: " + t.getCause) + exception.initCause(t) + exception + } + case _ => task + } + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala similarity index 83% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala index 5c4c95b76d..ceabc45885 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala @@ -19,22 +19,21 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.PythonCodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.exception.ExceptionUtils /** - * created by enjoyyin on 2018/10/22 * Description: Check for python code, prohibiting the use of sys, os, and creating processes(用于python代码的检查,禁止使用sys、os以及创建进程等行为) */ -class PythonCodeCheckInterceptor extends EntranceInterceptor{ - override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => +class PythonCodeCheckInterceptor extends EntranceInterceptor { + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => val error = new StringBuilder requestPersistTask.getRunType match { - case "python" | "pyspark" => - Utils.tryThrow(PythonExplain.authPass(requestPersistTask.getExecutionCode, error)){ - case PythonCodeCheckException(errCode,errDesc) => + case "python" | "pyspark" | "py" => + Utils.tryThrow(PythonExplain.authPass(requestPersistTask.getExecutionCode, error)) { + case PythonCodeCheckException(errCode, errDesc) => requestPersistTask.setErrCode(errCode) requestPersistTask.setErrDesc(errDesc) PythonCodeCheckException(errCode, errDesc) diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala new file mode 100644 index 0000000000..5bad733844 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.CodeCheckException +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task + +/** + * Description: + */ +class SQLCodeCheckInterceptor extends EntranceInterceptor { + + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => + requestPersistTask.getEngineType.toLowerCase() match { + case "hql" | "sql" | "jdbc" | "hive" => + val sb: StringBuilder = new StringBuilder + val isAuth: Boolean = SQLExplain.authPass(requestPersistTask.getExecutionCode, sb) + if (!isAuth) { + throw CodeCheckException(20051, "sql code check failed, reason is " + sb.toString()) + } + case _ => + } + requestPersistTask + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala similarity index 77% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala index 05081e3d08..83943defb1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala @@ -17,22 +17,21 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/10/19 * Description: LimitEntranceInterceptor Interceptors are used to set certain restrictions(拦截器用于对某些限制的设定) */ class SQLLimitEntranceInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { - case requestPersistTask:RequestPersistTask => requestPersistTask.getEngineType.toLowerCase() match { - case "hql" | "sql" | "jdbc"|"hive" | "psql" | "essql" => val executionCode = requestPersistTask.getExecutionCode + case requestPersistTask: RequestPersistTask => requestPersistTask.getEngineType.toLowerCase() match { + case "hql" | "sql" | "jdbc" | "hive" => val executionCode = requestPersistTask.getExecutionCode SQLExplain.dealSQLLimit(executionCode, requestPersistTask, logAppender) case _ => } - requestPersistTask + requestPersistTask case _ => task } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala similarity index 79% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala index 557504f46e..cafa99aa63 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala @@ -21,25 +21,22 @@ import java.lang import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.ScalaCodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * created by enjoyyin on 2019/2/25 - * Description: - */ + class ScalaCodeInterceptor extends EntranceInterceptor { private val SCALA_TYPE = "scala" - override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => val error = new StringBuilder + override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => val error = new StringBuilder requestPersistTask.getRunType match { - case SCALA_TYPE => Utils.tryThrow(ScalaExplain.authPass(requestPersistTask.getExecutionCode, error)){ + case SCALA_TYPE => Utils.tryThrow(ScalaExplain.authPass(requestPersistTask.getExecutionCode, error)) { case ScalaCodeCheckException(errorCode, errDesc) => requestPersistTask.setErrCode(errorCode) requestPersistTask.setErrDesc(errDesc) ScalaCodeCheckException(errorCode, errDesc) - case t:Throwable => val exception = ScalaCodeCheckException(20074, "Scala code check failed(scala代码检查失败)") + case t: Throwable => val exception = ScalaCodeCheckException(20074, "Scala code check failed(scala代码检查失败)") exception.initCause(t) exception } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala index 3a6beb5391..1b3d13edb4 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala @@ -18,25 +18,24 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.CodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/10/22 * Description: * Yòng yú jiǎnchá spark dàimǎ * 11/5000 * Used to check the spark code(用于检查spark代码) */ -class SparkCodeCheckInterceptor extends EntranceInterceptor{ +class SparkCodeCheckInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType.toLowerCase() match { - case "scala" => val stringBuilder:StringBuilder = new StringBuilder() + case "scala" => val stringBuilder: StringBuilder = new StringBuilder() val isAuth = SparkExplain.authPass(requestPersistTask.getExecutionCode, stringBuilder) - if (!isAuth){ + if (!isAuth) { throw CodeCheckException(20050, "spark code check failed") } case _ => diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala index 1216592ac1..11d8ee3ace 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala @@ -16,20 +16,19 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.cache.GlobalConfigurationKeyValueCache import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.time.DateFormatUtils -/** - * Created by enjoyyin on 2018/11/3. - */ -class StorePathEntranceInterceptor extends EntranceInterceptor { + +class StorePathEntranceInterceptor extends EntranceInterceptor with Logging { /** * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. - * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 * @@ -38,9 +37,9 @@ class StorePathEntranceInterceptor extends EntranceInterceptor { */ override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { case persistTask: RequestPersistTask => - val globalConfig = GlobalConfigurationKeyValueCache.getCacheMap(persistTask) + val globalConfig = Utils.tryAndWarn(GlobalConfigurationKeyValueCache.getCacheMap(persistTask)) var parentPath: String = null - if (globalConfig.containsKey(EntranceConfiguration.RESULT_SET_STORE_PATH.key)) + if (null != globalConfig && globalConfig.containsKey(EntranceConfiguration.RESULT_SET_STORE_PATH.key)) parentPath = EntranceConfiguration.RESULT_SET_STORE_PATH.getValue(globalConfig) else { parentPath = EntranceConfiguration.RESULT_SET_STORE_PATH.getValue diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala index bc1646dac9..5cadab5c92 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala @@ -21,28 +21,27 @@ import com.webank.wedatasphere.linkis.common.log.LogUtils import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.VarSubstitutionException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.exception.ExceptionUtils /** - * created by enjoyyin on 2018/10/19 * Description: For variable substitution(用于变量替换) */ -class VarSubstitutionInterceptor extends EntranceInterceptor{ +class VarSubstitutionInterceptor extends EntranceInterceptor { @throws[ErrorException] override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { - case requestPersistTask:RequestPersistTask => + case requestPersistTask: RequestPersistTask => Utils.tryThrow { logAppender.append(LogUtils.generateInfo("Program is substituting variables for you") + "\n") val (result, code) = CustomVariableUtils.replaceCustomVar(requestPersistTask, requestPersistTask.getEngineType) if (result) requestPersistTask.setExecutionCode(code) - logAppender.append(LogUtils.generateInfo( "Variables substitution ended successfully") + "\n") + logAppender.append(LogUtils.generateInfo("Variables substitution ended successfully") + "\n") requestPersistTask - }{ - case e:VarSubstitutionException => + } { + case e: VarSubstitutionException => val exception = VarSubstitutionException(20050, "Variable replacement failed!(变量替换失败!)" + ExceptionUtils.getRootCauseMessage(e)) exception.initCause(e) exception diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala new file mode 100644 index 0000000000..6dca503a3b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.{CacheNotReadyException, EntranceErrorCode} +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.scheduler.queue.Job +/** + * LogManager implementation, using a singleton class + * LogManager 的实现, 采用单例类进行 + */ +class CacheLogManager extends LogManager { + + override def getLogReader(execId: String): LogReader = { + var retLogReader:LogReader = null + this.entranceContext.getOrCreateScheduler().get(execId).foreach { + case entranceExecutionJob: EntranceExecutionJob => + retLogReader = entranceExecutionJob.getLogReader.getOrElse({ + this.synchronized { + val logWriter: CacheLogWriter = + entranceExecutionJob.getLogWriter.getOrElse(createLogWriter(entranceExecutionJob)).asInstanceOf[CacheLogWriter] + val sharedCache: Cache = logWriter.getCache. + getOrElse(throw CacheNotReadyException(EntranceErrorCode.CACHE_NOT_READY.getErrCode, EntranceErrorCode.CACHE_NOT_READY.getDesc)) + val logPath: String = entranceExecutionJob.getTask match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getLogPath + case _ => null + } + new CacheLogReader(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, sharedCache, entranceExecutionJob.getUser) + } + }) + entranceExecutionJob.setLogReader(retLogReader) + case _ => null + } + retLogReader + } + + + override def createLogWriter(job: Job): LogWriter = { + + job match { + case entranceExecutionJob: EntranceExecutionJob => { + val cache: Cache = Cache(EntranceConfiguration.DEFAULT_CACHE_MAX.getValue) + val logPath: String = entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getLogPath + val cacheLogWriter: CacheLogWriter = + new CacheLogWriter(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, cache, entranceExecutionJob.getUser) + entranceExecutionJob.setLogWriter(cacheLogWriter) + val webSocketCacheLogReader: WebSocketCacheLogReader = + new WebSocketCacheLogReader(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, cache, entranceExecutionJob.getUser) + entranceExecutionJob.setWebSocketLogReader(webSocketCacheLogReader) + val webSocketLogWriter: WebSocketLogWriter = new WebSocketLogWriter(entranceExecutionJob, entranceContext.getOrCreateEventListenerBus) + entranceExecutionJob.setWebSocketLogWriter(webSocketLogWriter) + cacheLogWriter + } + case _ => null + } + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala similarity index 95% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala index 832520c7e6..9412f643bd 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala @@ -14,12 +14,7 @@ * limitations under the License. */ -/** - * author: enjoyyin - * date: 2018/9/5 - * time: 11:14 - * Description: - */ + package com.webank.wedatasphere.linkis.entrance.log import java.io.{IOException, InputStream} @@ -46,7 +41,7 @@ class CacheLogReader(logPath:String , private def createInputStream: InputStream = { if (fileSystem == null) this synchronized { if (fileSystem == null){ - fileSystem = FSFactory.getFs(new FsPath(logPath)) + fileSystem = FSFactory.getFsByProxyUser(new FsPath(logPath), user) fileSystem.init(new util.HashMap[String, String]()) } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala new file mode 100644 index 0000000000..2e67ae94b6 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala @@ -0,0 +1,66 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.entrance.EntranceParser +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import org.apache.commons.lang.StringUtils +import org.slf4j.{Logger, LoggerFactory} + + +trait ErrorCodeListener { + + def onErrorCodeCreated(job: Job, errorCode: String, detailErrorMsg: String) +} + +class PersistenceErrorCodeListener extends ErrorCodeListener{ + + private var persistenceManager: PersistenceManager = _ + private var entranceParser: EntranceParser = _ + + private val logger:Logger = LoggerFactory.getLogger(classOf[PersistenceErrorCodeListener]) + + def setPersistenceManager(persistenceManager: PersistenceManager): Unit = this.persistenceManager = persistenceManager + def getPersistenceManager = persistenceManager + def setEntranceParser(entranceParser: EntranceParser): Unit = this.entranceParser = entranceParser + def getEntranceParser = entranceParser + + /** + * onErrorCodeCreated: When a job is running, it terminates unexpectedly or generates an error, and the error code and error information need to be persisted to the database. + * The subsequent front end will get this error code when querying a specific task as a key error message. + * onErrorCodeCreated: 当一个job在运行的时候,意外终止或者产生错误,需要将错误码和错误信息持久化到数据库中 + * 后续前端在查询一个具体任务的时候,会得到这个错误码,作为关键错误信息 + * @param job Wrong job(出错的job) + * @param errorCode error code(错误码) + * @param detailErrorMsg wrong description(错误描述) + */ + override def onErrorCodeCreated(job: Job, errorCode: String, detailErrorMsg: String): Unit = { + val task:Task = this.entranceParser.parseToTask(job) + task match{ + case requestPersistTask:RequestPersistTask => if (StringUtils.isEmpty(requestPersistTask.getErrDesc) || "50032".equals(errorCode)){ + requestPersistTask.setErrCode(Integer.parseInt(errorCode)) + val realErrorMsg = if (detailErrorMsg.length <= 255) detailErrorMsg else detailErrorMsg.substring(0, 255) + requestPersistTask.setErrDesc(realErrorMsg) + persistenceManager.createPersistenceEngine().updateIfNeeded(task) + } + case _ => logger.warn("task {} is not a instance of RequestPersistTask", task.getExecId) + } + } +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala new file mode 100644 index 0000000000..7900d0f048 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala @@ -0,0 +1,234 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import java.io.{BufferedReader, InputStreamReader} +import java.util +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.storage.FSFactory +import javax.annotation.PostConstruct + +import scala.collection.mutable.ArrayBuffer + + +abstract class ErrorCodeManager { + + def getErrorCodes: Array[ErrorCode] + + def errorMatch(log: String): Option[(String, String)] = { + getErrorCodes.foreach(e => if(e.regex.findFirstIn(log).isDefined) { + val matched = e.regex.unapplySeq(log) + if(matched.nonEmpty) + return Some(e.code -> e.message.format(matched.get:_*)) + else Some(e.code -> e.message) + }) + None + } +} + +abstract class FileErrorCodeManager extends ErrorCodeManager with Logging { + override def getErrorCodes: Array[ErrorCode] = (new ArrayBuffer[ErrorCode]() ++= getCommonErrorCodes ++= getErrorCodesDynamic).toArray + + val errorCodeFileDir: String = { + val specifiedDir = EntranceConfiguration.ERROR_CODE_FILE_DIR.getValue + if (specifiedDir.endsWith("/")) specifiedDir else specifiedDir + "/" + } + + val errorCodeFile: String + private val user = EntranceConfiguration.ENTRANCE_USER.getValue + private val fileSystem = FSFactory.getFs(new FsPath(errorCodeFileDir)) + + @PostConstruct + def init(): Unit = { + Utils.tryAndWarn(fileSystem.init(new util.HashMap[String, String]())) + } + + val dynamicErrorCodes: ArrayBuffer[ErrorCode] = new ArrayBuffer[ErrorCode]() + + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = { + logger.info("start to get error code properties from {}", errorCodeFile) + dynamicErrorCodes.clear() + val bufferedReader = new BufferedReader(new InputStreamReader(fileSystem.read(new FsPath(errorCodeFile)), "utf-8")) + var line: String = null + while ( { + line = bufferedReader.readLine(); line != null + }) { + val arr = line.split(",") + if (arr.length < 3){ + logger.warn("errorcode line {} format is not correct", line) + }else{ + dynamicErrorCodes += ErrorCode(arr(0).r.unanchored, arr(1), arr(2)) + } + } + } + }, 0, 1,TimeUnit.HOURS) + + + def getErrorCodesDynamic:Array[ErrorCode] = dynamicErrorCodes.toArray + + def getCommonErrorCodes:Array[ErrorCode] = { + Array(ErrorCode("queue (\\S+) is not exists in YARN".r.unanchored, "10001", "会话创建失败,%s队列不存在,请检查队列设置是否正确"), + ErrorCode("User (\\S+) cannot submit applications to queue (\\S+)".r.unanchored, "10001", "会话创建失败,用户%s不能提交应用到队列:%s,请检查队列设置是否正确"), + ErrorCode("您本次向任务队列([a-zA-Z_0-9\\.]+)请求资源((.+)),任务队列最大可用资源(.+),任务队列剩余可用资源((.+))您已占用任务队列资源(.+)".r.unanchored, "20001", "Session创建失败,当前申请资源%s,队列可用资源%s,请检查资源配置是否合理"), + ErrorCode("远程服务器没有足够资源实例化[a-zA-Z]+ Session,通常是由于您设置【驱动内存】或【客户端内存】过高导致的,建议kill脚本,调低参数后重新提交!等待下次调度...".r.unanchored, "20002", "Session创建失败,服务器资源不足,请稍后再试"), + ErrorCode("request resources from ResourceManager has reached 560++ tries, give up and mark it as FAILED.".r.unanchored, "20003", "Session创建失败,队列资源不足,请稍后再试"), + ErrorCode("Caused by:\\s*java.io.FileNotFoundException".r.unanchored, "20003", "文件%s不存在"), + ErrorCode("OutOfMemoryError".r.unanchored, "20083", "Java进程内存溢出"), + ErrorCode("Permission denied:\\s*user=[a-zA-Z0-9_]+,\\s*access=[A-Z]+\\s*,\\s*inode=\"([a-zA-Z0-9/_\\.]+)\"".r.unanchored, "30001", "%s无权限访问,请申请开通数据表权限"), + ErrorCode("Database '([a-zA-Z_0-9]+)' not found".r.unanchored, "40001", "数据库%s不存在,请检查引用的数据库是否有误"), + ErrorCode("Database does not exist: ([a-zA-Z_0-9]+)".r.unanchored, "40001", "数据库%s不存在,请检查引用的数据库是否有误"), + ErrorCode("Table or view not found: ([`\\.a-zA-Z_0-9]+)".r.unanchored, "40002", "表%s不存在,请检查引用的表是否有误"), + ErrorCode("Table not found '([a-zA-Z_0-9]+)'".r.unanchored, "40002", "表%s不存在,请检查引用的表是否有误"), + ErrorCode("cannot resolve '`(.+)`' given input columns".r.unanchored, "40003", "字段%s不存在,请检查引用的字段是否有误"), + ErrorCode(" Invalid table alias or column reference '(.+)':".r.unanchored, "40003", "字段%s不存在,请检查引用的字段是否有误"), + ErrorCode("([a-zA-Z_0-9]+) is not a valid partition column in table ([`\\.a-zA-Z_0-9]+)".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表%s是否为分区表或分区字段有误"), + ErrorCode("Partition spec \\{(\\S+)\\} contains non-partition columns".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表是否为分区表或分区字段有误"), + ErrorCode("table is not partitioned but partition spec exists:\\{(.+)\\}".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表是否为分区表或分区字段有误"), + ErrorCode("extraneous input '\\)'".r.unanchored, "50001", "括号不匹配,请检查代码中括号是否前后匹配"), + ErrorCode("missing EOF at '\\)'".r.unanchored, "50001", "括号不匹配,请检查代码中括号是否前后匹配"), + ErrorCode("expression '(\\S+)' is neither present in the group by".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("grouping expressions sequence is empty,\\s?and '(\\S+)' is not an aggregate function".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("Expression not in GROUP BY key '(\\S+)'".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("Undefined function: '(\\S+)'".r.unanchored, "50003", "未知函数%s,请检查代码中引用的函数是否有误"), + ErrorCode("Invalid function '(\\S+)'".r.unanchored, "50003", "未知函数%s,请检查代码中引用的函数是否有误"), + ErrorCode("Reference '(\\S+)' is ambiguous".r.unanchored, "50004", "字段%s存在名字冲突,请检查子查询内是否有同名字段"), + ErrorCode("Ambiguous column Reference '(\\S+)' in subquery".r.unanchored, "50004", "字段%s存在名字冲突,请检查子查询内是否有同名字段"), + ErrorCode("Column '(\\S+)' Found in more than One Tables/Subqueries".r.unanchored, "50005", "字段%s必须指定表或者子查询别名,请检查该字段来源"), + ErrorCode("Table or view '(\\S+)' already exists in database '(\\S+)'".r.unanchored, "50006", "表%s在数据库%s中已经存在,请删除相应表后重试"), + ErrorCode("Table (\\S+) already exists".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("Table already exists".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("""AnalysisException: (\S+) already exists""".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("java.io.FileNotFoundException: (\\S+) \\(No such file or directory\\)".r.unanchored,"64001","找不到导入文件地址:%s"), + ErrorCode("java.io.IOException: Permission denied(.+)at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet".r.unanchored,"64002","导出为excel时临时文件目录权限异常"), + ErrorCode("java.io.IOException: Mkdirs failed to create (\\S+) (.+)".r.unanchored,"64003","导出文件时无法创建目录:%s"), + ErrorCode("""ImportError: No module named (\S+)""".r.unanchored, "50008", "导入模块错误,系统没有%s模块,请联系运维人员安装"), + ErrorCode("""requires that the data to be inserted have the same number of columns as the target table""".r.unanchored, "50009", + "插入目标表字段数量不匹配,请检查代码!"), + ErrorCode("""missing \) at '(\S+)' near ''""".r.unanchored, "50010", "%s处括号不匹配,请检查代码!"), + ErrorCode("""due to data type mismatch: differing types in""".r.unanchored, + "50011", "数据类型不匹配,请检查代码!"), + ErrorCode("""Invalid column reference (\S+)""".r.unanchored, "50012", "字段%s引用有误,请检查字段是否存在!"), + ErrorCode("""Can't extract value from (\S+): need struct type but got string""".r.unanchored, "50013", "字段%s提取数据失败"), + ErrorCode("""mismatched input '(\S+)' expecting""".r.unanchored, "50014", "括号或者关键字不匹配,请检查代码!"), + ErrorCode("""GROUP BY position (\S+) is not in select list""".r.unanchored, "50015", "group by 位置2不在select列表中,请检查代码!"), + ErrorCode("""'NoneType' object""".r.unanchored, "50016", "代码中存在NoneType空类型变量,请检查代码"), + ErrorCode("""IndexError:List index out of range""".r.unanchored, "50017", "数组越界"), + ErrorCode("""Can't extract value from (\S+): need struct type but got string""".r.unanchored, "50013", "字段提取数据失败请检查字段类型"), + ErrorCode("""Cannot insert into target table because column number/types are different '(\S+)'""".r.unanchored, "50018", "插入数据未指定目标表字段%s,请检查代码!"), + ErrorCode("""Invalid table alias '(\S+)'""".r.unanchored, "50019", "表别名%s错误,请检查代码!"), + ErrorCode("""UDFArgumentException Argument expected""".r.unanchored, "50020", "UDF函数未指定参数,请检查代码!"), + ErrorCode("""aggregate functions are not allowed in GROUP BY""".r.unanchored, "50021", "聚合函数%s不能写在group by 中,请检查代码!"), + ErrorCode("SyntaxError".r.unanchored, "50007", "您的代码有语法错误,请您修改代码之后执行"), + ErrorCode("""Table not found""".r.unanchored, "40002", "表不存在,请检查引用的表是否有误"), + ErrorCode("""No matching method""".r.unanchored, "40003", "函数使用错误,请检查您使用的函数方式"), + ErrorCode("""is killed by user""".r.unanchored, "50032", "用户主动kill任务"), + ErrorCode("""name '(\S+)' is not defined""".r.unanchored, "60001", "python代码变量%s未定义"), + ErrorCode("""Undefined function:\s+'(\S+)'""".r.unanchored, "60002", "python udf %s 未定义"), + ErrorCode("FAILED: ParseException".r.unanchored, "50007", "您的sql代码可能有语法错误,请检查sql代码"), + ErrorCode("org.apache.spark.sql.catalyst.parser.ParseException".r.unanchored,"50007", "您的sql代码可能有语法错误,请检查sql代码"), + ErrorCode("""ParseException:""".r.unanchored, "60003", "脚本语法有误"), + ErrorCode("""Permission denied""".r.unanchored, "60010", "您可能没有相关权限"), + ErrorCode("""cannot concatenate '(\S+)' and '(\S+)'""".r.unanchored, "61027", "python执行不能将%s和%s两种类型进行连接"), + ErrorCode("""Py4JJavaError: An error occurred""".r.unanchored, "60020", "pyspark执行失败,可能是语法错误或stage失败"), + ErrorCode("""unexpected indent""".r.unanchored, "61028", "python代码缩进对齐有误"), + ErrorCode("""is exceeded""".r.unanchored, "60078", "个人库超过限制"), + ErrorCode("""unexpected indent""".r.unanchored, "69582", "python代码缩进有误"), + ErrorCode("""unexpected character after line""".r.unanchored, "69583", "python代码反斜杠后面必须换行"), + ErrorCode("""Invalid row number""".r.unanchored, "60091", "导出Excel表超过最大限制1048575"), + ErrorCode("""parquet.io.ParquetDecodingException""".r.unanchored, "60092", "python save as table未指定格式,默认用parquet保存,hive查询报错"), + ErrorCode("""errCode: 11011""".r.unanchored, "11011", "远程服务器内存资源不足"), + ErrorCode("""errCode: 11012""".r.unanchored, "11012", "远程服务器CPU资源不足"), + ErrorCode("""errCode: 11013""".r.unanchored, "11013", "远程服务器实例资源不足"), + ErrorCode("""errCode: 11014""".r.unanchored, "11014", "队列CPU资源不足"), + ErrorCode("""errCode: 11015""".r.unanchored, "11015", "队列内存资源不足"), + ErrorCode("""errCode: 11016""".r.unanchored, "11016", "队列实例数超过限制"), + ErrorCode("""errCode: 11017""".r.unanchored, "11017", "超出全局计算引擎实例限制"), + ErrorCode("""资源不足""".r.unanchored, "60035", "资源不足,启动引擎失败"), + ErrorCode("""获取Yarn队列信息异常""".r.unanchored, "60075", "获取Yarn队列信息异常,可能是您设置的yarn队列不存在") + ) + } +} + +/** + * errorCodeManager的单例对象,主要是用来生成固定的错误码 + */ +object FixedErrorCodeManager extends FileErrorCodeManager { + + override val errorCodeFile: String = "" + + override def getErrorCodes: Array[ErrorCode] = getCommonErrorCodes +} + + +object Main{ + def main(args: Array[String]): Unit = { + } +} + + +/** + * RefreshableErrorCodeManager corresponds to FixedErrorCodeManager, and refresheyeErrorCodeManager can update its own errorCodes through the query module. + * The purpose is to enable users to update the error code at any time by modifying the database. + * RefreshableErrorCodeManager 与 FixedErrorCodeManager 是对应的,refreshaleErrorCodeManager可以通过query模块进行更新自身的errorCodes + * 目的是为了能够让用户通过修改数据库随时更新错误码 + */ +// +//object RefreshableErrorCodeManager extends ErrorCodeManager{ +// private val sender:Sender = +// Sender.getSender(EntranceConfiguration.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME.getValue, 1000 * 60 * 60, 100) +// +// private val logger:Logger = LoggerFactory.getLogger(getClass) +// private var errorCodes:Array[ErrorCode] = _ +// +// class FetchErrorCodeThread extends Runnable{ +// override def run(): Unit = { +// val requestErrorCode = new RequestErrorCode +// val responseErrorCode = sender.send(requestErrorCode).asInstanceOf[ResponseErrorCode] +// Utils.tryAndWarnMsg{ +// val responseErrorCode = sender.send(requestErrorCode).asInstanceOf[ResponseErrorCode] +// val status = responseErrorCode.getStatus +// val message = responseErrorCode.getMessage +// if (status != 0){ +// logger.warn(s"Error encounters when retrieve errorCodes from query module, reason: $message") +// }else{ +// val errorCodeList = responseErrorCode.getResult +// val arrayBuffer = new ArrayBuffer[ErrorCode]() +// import scala.collection.JavaConversions._ +// errorCodeList foreach { errorCode => +// val regex = errorCode.getErrorRegex.r.unanchored +// val errorCode_ = errorCode.getErrorCode +// val errorDesc = errorCode.getErrorDesc +// arrayBuffer += ErrorCode(regex, errorCode_, errorDesc) +// } +// errorCodes = arrayBuffer.toArray +// } +// }("Query ErrorCodes failed. You may check the cause or just ignore it ") +// } +// } +// +// override def getErrorCodes: Array[ErrorCode] = errorCodes +//} + + + + + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala new file mode 100644 index 0000000000..9db056eba1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.scheduler.listener.LogListener +import com.webank.wedatasphere.linkis.scheduler.queue.Job + + +abstract class LogManager extends LogListener with Logging{ + + protected var errorCodeListener: Option[ErrorCodeListener] = None + protected var errorCodeManager: Option[ErrorCodeManager] = None + protected var entranceContext: EntranceContext = _ + + def setEntranceContext(entranceContext: EntranceContext): Unit = this.entranceContext = entranceContext + def setErrorCodeListener(errorCodeListener: ErrorCodeListener): Unit = this.errorCodeListener = Option(errorCodeListener) + def setErrorCodeManager(errorCodeManager: ErrorCodeManager): Unit = this.errorCodeManager = Option(errorCodeManager) + + def getLogReader(execId: String): LogReader + + def createLogWriter(job: Job): LogWriter + + override def onLogUpdate(job: Job, log: String): Unit = { + Utils.tryCatch{ + job match{ + case entranceExecutionJob: EntranceExecutionJob => + if (entranceExecutionJob.getLogWriter.isEmpty) entranceExecutionJob synchronized { + if (entranceExecutionJob.getLogWriter.isEmpty) createLogWriter(entranceExecutionJob) + } + entranceExecutionJob.getLogWriter.foreach(logWriter => logWriter.write(log)) + entranceExecutionJob.getWebSocketLogWriter.foreach(writer => writer.write(log)) + errorCodeManager.foreach(_.errorMatch(log).foreach { case (code, errorMsg) => + errorCodeListener.foreach(_.onErrorCodeCreated(job, code, errorMsg)) + }) + case _ => + } + }{ + case e: Exception => logger.warn(s"write log for job ${job.getId} failed", e) + case t: Throwable => logger.warn(s"write log for job ${job.getId} failed", t) + } + } +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala similarity index 82% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala index 6a85906d1c..2afa4733d7 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala @@ -26,9 +26,7 @@ import org.apache.commons.lang.StringUtils import scala.util.matching.Regex -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class LogReader(charset: String) extends Closeable with Logging{ import LogReader._ @@ -70,6 +68,18 @@ abstract class LogReader(charset: String) extends Closeable with Logging{ if (!flag) concatLog(length, singleLog, warning, all) case INFO_HEADER1() | INFO_HEADER2() => val hiveLogSpecial:String = EntranceConfiguration.HIVE_SPECIAL_LOG_INCLUDE.getValue + val sparkLogSpecial:String = EntranceConfiguration.SPARK_SPECIAL_LOG_INCLUDE.getValue + val hiveCreateTableLog:String = EntranceConfiguration.HIVE_CREATE_TABLE_LOG.getValue + if (singleLog.contains(hiveLogSpecial) && singleLog.contains(hiveCreateTableLog)){ + val threadName = EntranceConfiguration.HIVE_THREAD_NAME.getValue + val printInfo = EntranceConfiguration.HIVE_PRINT_INFO_LOG.getValue + val start = singleLog.indexOf(threadName) + val end = singleLog.indexOf(printInfo) + printInfo.length + if(start > 0 && end > 0) { + val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) + concatLog(length, realLog, info, all) + } + } if (singleLog.contains(hiveLogSpecial) && singleLog.contains("map") && singleLog.contains("reduce")){ val start = singleLog.indexOf(EntranceConfiguration.HIVE_THREAD_NAME.getValue) val end = singleLog.indexOf(EntranceConfiguration.HIVE_STAGE_NAME.getValue) @@ -77,6 +87,15 @@ abstract class LogReader(charset: String) extends Closeable with Logging{ val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) concatLog(length, realLog, info, all) } + }else if (singleLog.contains(sparkLogSpecial)){ + val className = EntranceConfiguration.SPARK_PROGRESS_NAME.getValue + val endFlag = EntranceConfiguration.END_FLAG.getValue + val start = singleLog.indexOf(className) + val end = singleLog.indexOf(endFlag) + endFlag.length + if(start > 0 && end > 0) { + val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) + concatLog(length, realLog, info, all) + } }else{ val arr = EntranceConfiguration.LOG_EXCLUDE.getValue.split(",").map (word => word.trim) var flag = false diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala index 0d9e0cfece..6a56bdb858 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala @@ -24,12 +24,10 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException import com.webank.wedatasphere.linkis.storage.FSFactory import com.webank.wedatasphere.linkis.storage.utils.FileSystemUtils -import org.apache.commons.io.IOUtils import org.apache.commons.lang.StringUtils +import org.apache.hadoop.hdfs.client.HdfsDataOutputStream + -/** - * Created by enjoyyin on 2018/9/4. - */ abstract class LogWriter(charset: String) extends Closeable with Flushable with Logging { private var firstWrite = true @@ -52,15 +50,25 @@ abstract class LogWriter(charset: String) extends Closeable with Flushable with - def flush(): Unit = Utils.tryQuietly(outputStream.flush(), t => { - warn("Error encounters when flush log,", t) - }) - + def flush(): Unit = Utils.tryAndWarnMsg[Unit] { + outputStream match { + case hdfs: HdfsDataOutputStream => + // todo check + hdfs.hsync() + case _ => + outputStream.flush() + } + }("Error encounters when flush log, ") def close(): Unit = { flush() - if (outputStream != null) IOUtils.closeQuietly(outputStream) - + if (outputStream != null) { + Utils.tryCatch{ + outputStream.close() + }{ + case t:Throwable => //ignore + } + } } } @@ -68,11 +76,11 @@ abstract class AbstractLogWriter(logPath: String, user: String, charset: String) extends LogWriter(charset) { if(StringUtils.isBlank(logPath)) throw new EntranceErrorException(20301, "logPath cannot be empty.") - protected val fileSystem = FSFactory.getFs(new FsPath(logPath)) + protected val fileSystem = FSFactory.getFsByProxyUser(new FsPath(logPath), user) fileSystem.init(new util.HashMap[String, String]()) protected val outputStream: OutputStream = { - FileSystemUtils.createNewFile(new FsPath(logPath), true) + FileSystemUtils.createNewFile(new FsPath(logPath), user, true) fileSystem.write(new FsPath(logPath), true) } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala new file mode 100644 index 0000000000..025da36543 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala @@ -0,0 +1,219 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.parser + +import java.util +import java.util.Date + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.{EntranceErrorCode, EntranceIllegalParamException} +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.builder.factory.{LabelBuilderFactory, LabelBuilderFactoryContext, StdLabelBuilderFactory} +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineRunTypeLabel, EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.manager.label.utils.{EngineTypeLabelCreator, LabelUtils} +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions.mapAsScalaMap +import scala.collection.JavaConverters._ + + +class CommonEntranceParser extends AbstractEntranceParser with Logging { + + private val labelBuilderFactory: LabelBuilderFactory = new StdLabelBuilderFactory + + /** + * parse params to be a task + * params json data from frontend + * + */ + override def parseToTask(params: util.Map[String, Any]): Task = { + if (!params.containsKey(TaskConstant.EXECUTION_CONTENT)) { + return parseToOldTask(params) + } + + val task = new RequestPersistTask + task.setCreatedTime(new Date(System.currentTimeMillis)) + task.setInstance(Sender.getThisInstance) + val umUser = params.get(TaskConstant.EXECUTE_USER).asInstanceOf[String] + val submitUser = params.get(TaskConstant.SUBMIT_USER).asInstanceOf[String] + task.setSubmitUser(submitUser) + if (StringUtils.isBlank(umUser)) task.setUmUser(submitUser) + task.setUmUser(umUser) + val executionContent = params.getOrDefault(TaskConstant.EXECUTION_CONTENT, null).asInstanceOf[util.Map[String, Object]] + val configMap = params.getOrDefault(TaskConstant.PARAMS, null).asInstanceOf[util.Map[String, Object]] + val labelMap = params.getOrDefault(TaskConstant.LABELS, null).asInstanceOf[util.Map[String, Object]] + val source = params.getOrDefault(TaskConstant.SOURCE, new util.HashMap[String, String]()).asInstanceOf[util.Map[String, String]] + val sourcePath = source.getOrDefault(TaskConstant.SCRIPTPATH, null) + if (null == sourcePath || null == labelMap) { + throw new EntranceIllegalParamException(EntranceErrorCode.PARAM_CANNOT_EMPTY.getErrCode, EntranceErrorCode.PARAM_CANNOT_EMPTY.getDesc + s", source : ${sourcePath}, labels : ${BDPJettyServerHelper.gson.toJson(labelMap)}") + } + + var code: String = null + var runType: String = null + if (executionContent.containsKey(TaskConstant.CODE)) { + code = executionContent.get(TaskConstant.CODE).asInstanceOf[String] + runType = executionContent.get(TaskConstant.RUNTYPE).asInstanceOf[String] + if (StringUtils.isEmpty(code)) + throw new EntranceIllegalParamException(20007, "param executionCode and scriptPath can not be empty at the same time") + } else { + // todo check + throw new EntranceIllegalParamException(20010, "Only code with runtype supported !") + } + val formatCode = params.get(TaskConstant.FORMATCODE).asInstanceOf[Boolean] + if (formatCode) code = format(code) + task.setExecutionCode(code) + var labels: util.Map[String, Label[_]] = buildLabel(labelMap) + val engineTypeLabel = labels.getOrElse(LabelKeyConstant.ENGINE_TYPE_KEY, null).asInstanceOf[EngineTypeLabel] + if (null == engineTypeLabel) { + val msg = s"Cannot create engineTypeLabel, labelMap : ${BDPJettyServerHelper.gson.toJson(labelMap)}" + error(msg) + throw new EntranceIllegalParamException(EntranceErrorCode.LABEL_PARAMS_INVALID.getErrCode, + EntranceErrorCode.LABEL_PARAMS_INVALID.getDesc + msg) + } else { + task.setEngineType(engineTypeLabel.getEngineType) + } + val engineRunTypeLabel = labels.getOrElse(LabelKeyConstant.ENGINE_RUN_TYPE_KEY, null).asInstanceOf[EngineRunTypeLabel] + if (null != engineRunTypeLabel) { + task.setRunType(engineRunTypeLabel.getRunType) + } else { + warn(s"RunType not set. EngineType : ${engineTypeLabel.getEngineType}") + } + var userCreatorLabel = labels.getOrElse(LabelKeyConstant.USER_CREATOR_TYPE_KEY, null).asInstanceOf[UserCreatorLabel] + + if (null == userCreatorLabel) { + userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + val creator = EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + userCreatorLabel.setUser(umUser) + userCreatorLabel.setCreator(creator) + labels.put(userCreatorLabel.getLabelKey, userCreatorLabel) + } + labels += (LabelKeyConstant.ENGINE_TYPE_KEY -> engineTypeLabel) + labels += (LabelKeyConstant.ENGINE_RUN_TYPE_KEY -> engineRunTypeLabel) + labels += (LabelKeyConstant.USER_CREATOR_TYPE_KEY -> userCreatorLabel) + task.setLabels(new util.ArrayList[Label[_]](labels.values())) + task.setSource(source) + task.setExecuteApplicationName(engineTypeLabel.getEngineType) + task.setRequestApplicationName(userCreatorLabel.getCreator) + task.setStatus(SchedulerEventState.Inited.toString) + task.setCreateService(EntranceConfiguration.DEFAULT_CREATE_SERVICE.getValue) + task.setParams(configMap) + task + } + + private def parseToOldTask(params: util.Map[String, Any]): Task = { + + val task = new RequestPersistTask + task.setCreatedTime(new Date(System.currentTimeMillis)) + task.setInstance(Sender.getThisInstance) + val umUser = params.get(TaskConstant.UMUSER).asInstanceOf[String] + val submitUser = params.get(TaskConstant.SUBMIT_USER).asInstanceOf[String] + task.setSubmitUser(submitUser) + if (umUser == null) throw new EntranceIllegalParamException(20005, "umUser can not be null") + task.setUmUser(umUser) + var executionCode = params.get(TaskConstant.EXECUTIONCODE).asInstanceOf[String] + val _params = params.get(TaskConstant.PARAMS) + _params match { + case mapParams: java.util.Map[String, Object] => task.setParams(mapParams) + case _ => + } + val formatCode = params.get(TaskConstant.FORMATCODE).asInstanceOf[Boolean] + var creator = params.get(TaskConstant.REQUESTAPPLICATIONNAME).asInstanceOf[String] + val source = params.getOrDefault(TaskConstant.SOURCE, new util.HashMap[String, String]()).asInstanceOf[util.Map[String, String]] + val executeApplicationName = params.get(TaskConstant.EXECUTEAPPLICATIONNAME).asInstanceOf[String] + if (StringUtils.isEmpty(creator)) creator = EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + //if (StringUtils.isEmpty(executeApplicationName)) throw new EntranceIllegalParamException(20006, "param executeApplicationName can not be empty or null") + /* When the execution type is IDE, executionCode and scriptPath cannot be empty at the same time*/ + /*当执行类型为IDE的时候,executionCode和scriptPath不能同时为空*/ + if (EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue.equals(creator) && StringUtils.isEmpty(source.get(TaskConstant.SCRIPTPATH)) && + StringUtils.isEmpty(executionCode)) + throw new EntranceIllegalParamException(20007, "param executionCode and scriptPath can not be empty at the same time") + var runType: String = null + if (StringUtils.isNotEmpty(executionCode)) { + runType = params.get(TaskConstant.RUNTYPE).asInstanceOf[String] + if (StringUtils.isEmpty(runType)) runType = EntranceConfiguration.DEFAULT_RUN_TYPE.getValue + //If formatCode is not empty, we need to format it(如果formatCode 不为空的话,我们需要将其进行格式化) + if (formatCode) executionCode = format(executionCode) + task.setExecutionCode(executionCode) + } + task.setSource(source) + task.setEngineType(runType) + //为了兼容代码,让engineType和runType都有同一个属性 + task.setRunType(runType) + task.setExecuteApplicationName(executeApplicationName) + task.setRequestApplicationName(creator) + task.setStatus(SchedulerEventState.Inited.toString) + task.setCreateService(EntranceConfiguration.DEFAULT_CREATE_SERVICE.getValue) + //封装Labels + task.setLabels(buildLabel(task)) + task + } + + private def buildLabel(task: RequestPersistTask): util.List[Label[_]] = { + val labelsList = new util.ArrayList[Label[_]]() + val labelBuilderFactory = LabelBuilderFactoryContext.getLabelBuilderFactory + if (StringUtils.isNotBlank(task.getUmUser) && StringUtils.isNotBlank(task.getRequestApplicationName)) { + val userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + userCreatorLabel.setCreator(task.getRequestApplicationName) + userCreatorLabel.setUser(task.getUmUser) + labelsList.add(userCreatorLabel) + } + + if (StringUtils.isNotBlank(task.getExecuteApplicationName)) { + val engineTypeLabel = EngineTypeLabelCreator.createEngineTypeLabel(task.getExecuteApplicationName) + labelsList.add(engineTypeLabel) + } + + if (StringUtils.isNotBlank(task.getRunType)) { + val runTypeLabel = labelBuilderFactory.createLabel(classOf[EngineRunTypeLabel]) + runTypeLabel.setRunType(task.getRunType) + labelsList.add(runTypeLabel) + } + + val labels = TaskUtils.getLabelsMap(task.getParams.asInstanceOf[util.Map[String, Any]]) + if (null != labels) { + LabelUtils.distinctLabel(labelBuilderFactory.getLabels(labels.asInstanceOf[util.Map[String, AnyRef]]), labelsList) + } else { + labelsList + } + } + + private def buildLabel(labelMap: util.Map[String, Object]): util.Map[String, Label[_]] = { + val labelKeyValueMap = new util.HashMap[String, Label[_]]() + if (null != labelMap && !labelMap.isEmpty) { + val list: util.List[Label[_]] = labelBuilderFactory.getLabels(labelMap.asInstanceOf[util.Map[String, AnyRef]]) + if (null != list) { + list.asScala.foreach { + label => labelKeyValueMap.put(label.getLabelKey, label) + } + } + } + labelKeyValueMap + } + + //todo to format code using proper way + private def format(code: String): String = code + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala new file mode 100644 index 0000000000..d64747bda6 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala @@ -0,0 +1,97 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.persistence + +import com.webank.wedatasphere.linkis.common.io.resultset.ResultSet +import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.execute.StorePathExecuteRequest +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.entrance.scheduler.cache.CacheOutputExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.executer.{AliasOutputExecuteResponse, OutputExecuteResponse} +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetWriter} +import com.webank.wedatasphere.linkis.storage.utils.FileSystemUtils +import org.apache.commons.io.IOUtils + + +class EntranceResultSetEngine extends ResultSetEngine with Logging { + override def persistResultSet(job: Job, executeCompleted: OutputExecuteResponse): String = { + + + executeCompleted match { + case AliasOutputExecuteResponse(alias, output) => + if (ResultSetFactory.getInstance.isResultSetPath(output)) output + else { + val resultSet = ResultSetFactory.getInstance.getResultSetByContent(output) + writeResult(alias, output, job, resultSet) + } + case CacheOutputExecuteResponse(alias, output) => + if(ResultSetFactory.getInstance.isResultSet(output)){ + val resultSet = ResultSetFactory.getInstance.getResultSetByContent(output) + writeResult(alias, output, job, resultSet) + } else { + val resultSet = ResultSetFactory.getInstance.getResultSetByPath(FsPath.getFsPath(output)) + copyResult(alias, output, job, resultSet) + } + } + } + + private def copyResult(alias: String, output: String, job: Job, resultSet:ResultSet[_ <: MetaData, _ <: Record]) : String = { + var user:String="hadoop" + val storePath = job match { + case j: EntranceExecutionJob => j.jobToExecuteRequest() match { + case s: StorePathExecuteRequest => { + user = j.getUser + s.storePath + } + case _ => null + } + case _ => null + } + if(storePath != null) { + val path = if(alias.contains("_")) resultSet.getResultSetPath(new FsPath(storePath), alias) else resultSet.getResultSetPath(new FsPath(storePath), "_" + alias) + FileSystemUtils.copyFile(path, FsPath.getFsPath(output), user) + path.getSchemaPath + } else null + } + + private def writeResult(alias: String, output: String, job: Job, resultSet:ResultSet[_ <: MetaData, _ <: Record]) = { + var user:String="hadoop" + val storePath = job match { + case j: EntranceExecutionJob => j.jobToExecuteRequest() match { + case s: StorePathExecuteRequest => { + user = j.getUser + s.storePath + } + case _ => null + } + case _ => null + } + if(storePath != null) { + //TODO Remove _ stitching(去掉_拼接) + val path = if(alias.contains("_")) resultSet.getResultSetPath(new FsPath(storePath), alias) else resultSet.getResultSetPath(new FsPath(storePath), "_" + alias) + + FileSystemUtils.createNewFile(path, user,true) + val writer = ResultSetWriter.getResultSetWriter(resultSet, 0, path, user) + Utils.tryFinally { + writer.addMetaDataAndRecordString(output) + writer.flush() + }{ + IOUtils.closeQuietly(writer) + } + path.getSchemaPath + } else null + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala similarity index 90% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala index 620af1c46a..6c1aa10e72 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala @@ -23,15 +23,16 @@ import javax.ws.rs.QueryParam import javax.ws.rs.core.{Context, Response} import org.springframework.web.bind.annotation.{PathVariable, RequestBody, RequestMapping, RequestMethod} -/** - * Created by enjoyyin on 2018/9/3. - */ + trait EntranceRestfulRemote { @RequestMapping(value = Array("/entrance/execute"), method = Array(RequestMethod.POST)) def execute(@Context req: HttpServletRequest, @RequestBody json: util.Map[String, Any]): Response -// @RequestMapping(value = Array("/api/entrance/{id}"), method = Array(RequestMethod.GET)) + @RequestMapping(value = Array("/entrance/submit"), method = Array(RequestMethod.POST)) + def submit(@Context req: HttpServletRequest, @RequestBody json: util.Map[String, Any]): Response + + // @RequestMapping(value = Array("/api/entrance/{id}"), method = Array(RequestMethod.GET)) // def get(@PathVariable("id") id: String): Response @RequestMapping(value = Array("/entrance/{id}/status"), method = Array(RequestMethod.GET)) diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala new file mode 100644 index 0000000000..1300086e1b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala @@ -0,0 +1,152 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.protocol.conf.{RequestQueryEngineConfig, ResponseQueryConfig} +import com.webank.wedatasphere.linkis.manager.label.builder.factory.LabelBuilderFactoryContext +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{ConcurrentEngineConnLabel, EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.manager.label.utils.EngineTypeLabelCreator +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelGroup +import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, SchedulerEvent} +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +class EntranceGroupFactory extends GroupFactory with Logging { + + private val groupNameToGroups = new JMap[String, Group] + private val labelBuilderFactory = LabelBuilderFactoryContext.getLabelBuilderFactory + + override def getOrCreateGroup(groupName: String): Group = { + if (!groupNameToGroups.containsKey(groupName)) synchronized { + val initCapacity = 100 + val maxCapacity = 100 + var maxRunningJobs = EntranceConfiguration.WDS_LINKIS_INSTANCE.getValue + val maxAskExecutorTimes = EntranceConfiguration.MAX_ASK_EXECUTOR_TIME.getValue.toLong + if (groupName.startsWith(EntranceGroupFactory.CONCURRENT)) { + if (null == groupNameToGroups.get(groupName)) synchronized { + if (null == groupNameToGroups.get(groupName)) { + val group = new ParallelGroup(groupName, 100, EntranceConfiguration.CONCURRENT_FACTORY_MAX_CAPACITY.getValue) + group.setMaxRunningJobs(EntranceConfiguration.CONCURRENT_MAX_RUNNING_JOBS.getValue) + group.setMaxAskExecutorTimes(EntranceConfiguration.CONCURRENT_EXECUTOR_TIME.getValue) + groupNameToGroups.put(groupName, group) + return group + } + } + } + val groupNameSplits = groupName.split("_") + if (groupNameSplits.length < 3) { + logger.warn(s"name style of group: $groupName is not correct, we will set default value for the group") + } else { + val sender: Sender = Sender.getSender(EntranceConfiguration.CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME.getValue) + val creator = groupNameSplits(0) + val username = groupNameSplits(1) + val engineType = groupNameSplits(2) + + logger.info(s"Getting parameters for $groupName(正在为 $groupName 获取参数) username: $username, creator:$creator, engineType: $engineType") + val userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + userCreatorLabel.setUser(username) + userCreatorLabel.setCreator(creator) + val engineTypeLabel = EngineTypeLabelCreator.createEngineTypeLabel(engineType) + try { + val keyAndValue = sender.ask(RequestQueryEngineConfig(userCreatorLabel, engineTypeLabel)).asInstanceOf[ResponseQueryConfig].getKeyAndValue + + maxRunningJobs = Integer.parseInt(keyAndValue.get(EntranceConfiguration.WDS_LINKIS_INSTANCE.key)) + } catch { + case t: Throwable => logger.warn("Get maxRunningJobs from configuration server failed! Next use the default value to continue.") + } + } + logger.info("groupName: {} => maxRunningJobs is {}", groupName, maxRunningJobs) + val group = new ParallelGroup(groupName, initCapacity, maxCapacity) + group.setMaxRunningJobs(maxRunningJobs) + group.setMaxAskExecutorTimes(maxAskExecutorTimes) + if (!groupNameToGroups.containsKey(groupName)) groupNameToGroups.put(groupName, group) + } + groupNameToGroups.get(groupName) + } + + + override def getGroupNameByEvent(event: SchedulerEvent): String = event match { + case job: EntranceJob => + job.getTask match { + case HaPersistenceTask(task) => + "HA" + case requestPersistTask: RequestPersistTask => { + val labels = requestPersistTask.getLabels + EntranceGroupFactory.getGroupNameByLabels(labels, job.getParams) + } + case _ => EntranceGroupFactory.getGroupName(job.getCreator, job.getUser, job.getParams) + } + } +} + +object EntranceGroupFactory { + + val CACHE = "_Cache" + + val CONCURRENT = "Concurrent_" + + def getGroupName(creator: String, user: String, params: util.Map[String, Any] = new util.HashMap[String, Any]): String = { + val runtime = TaskUtils.getRuntimeMap(params) + val cache = if (runtime.get(TaskConstant.READ_FROM_CACHE) != null && runtime.get(TaskConstant.READ_FROM_CACHE).asInstanceOf[Boolean]) CACHE else "" + if (StringUtils.isNotEmpty(creator)) creator + "_" + user + cache + else EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + "_" + user + cache + } + + def getGroupNameByLabels(labels: java.util.List[Label[_]], params: util.Map[String, Any] = new util.HashMap[String, Any]): String = { + + val userCreator = labels.find(_.isInstanceOf[UserCreatorLabel]) + val engineType = labels.find(_.isInstanceOf[EngineTypeLabel]) + val concurrent = labels.find(_.isInstanceOf[ConcurrentEngineConnLabel]) + if (userCreator.isEmpty || engineType.isEmpty) { + throw new EntranceErrorException(20001, "userCreator label or engineType label cannot null") + } + + if (concurrent.isDefined) { + + val engineTypeLabel = engineType.get.asInstanceOf[EngineTypeLabel] + val groupName = CONCURRENT + engineTypeLabel.getEngineType + groupName + + } else { + val userCreatorLabel = userCreator.get.asInstanceOf[UserCreatorLabel] + + val engineTypeLabel = engineType.get.asInstanceOf[EngineTypeLabel] + + val runtime = TaskUtils.getRuntimeMap(params) + val cache = if (runtime.get(TaskConstant.READ_FROM_CACHE) != null && runtime.get(TaskConstant.READ_FROM_CACHE).asInstanceOf[Boolean]) CACHE else "" + val groupName = userCreatorLabel.getCreator + "_" + userCreatorLabel.getUser + "_" + engineTypeLabel.getEngineType + cache + groupName + } + } + + +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala new file mode 100644 index 0000000000..6b53a773b1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse + +case class CacheOutputExecuteResponse(alias: String, output: String) extends OutputExecuteResponse{ + override def getOutput: String = output +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala new file mode 100644 index 0000000000..8a8091161d --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import java.util.concurrent.ExecutorService + +import com.google.common.collect.Lists +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.entrance.utils.JobHistoryHelper +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.scheduler.SchedulerContext +import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException +import com.webank.wedatasphere.linkis.scheduler.executer.SuccessExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.queue.Group +import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer +import com.webank.wedatasphere.linkis.storage.FSFactory +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + +class ReadCacheConsumer(schedulerContext: SchedulerContext, + executeService: ExecutorService, private var group: Group, persistenceManager: PersistenceManager) extends FIFOUserConsumer(schedulerContext, executeService, group) { + + override protected def loop(): Unit = { + val event = Option(getConsumeQueue.take()) + event.foreach{ + case job: EntranceJob => + job.getTask match { + case task: RequestPersistTask => + Utils.tryCatch { + val readCacheBefore = TaskUtils.getRuntimeMap(job.getParams).getOrDefault(TaskConstant.READ_CACHE_BEFORE, 300L).asInstanceOf[Long] + val cacheResult = JobHistoryHelper.getCache(task.getExecutionCode, task.getExecuteApplicationName, task.getUmUser, readCacheBefore) + if (cacheResult != null && StringUtils.isNotBlank(cacheResult.getResultLocation)) { + val resultSets = listResults(cacheResult.getResultLocation, job.getUser) + if (resultSets.size() > 0) { + for (resultSet: FsPath <- resultSets) { + val alias = FilenameUtils.getBaseName(resultSet.getPath) + val output = FsPath.getFsPath(cacheResult.getResultLocation, FilenameUtils.getName(resultSet.getPath)).getSchemaPath + persistenceManager.onResultSetCreated(job, new CacheOutputExecuteResponse(alias, output)) + } + persistenceManager.onResultSizeCreated(job, resultSets.size()) + } + val runtime = TaskUtils.getRuntimeMap(job.getParams) + runtime.put(TaskConstant.CACHE, false) + TaskUtils.addRuntimeMap(job.getParams, runtime) + job.transitionCompleted(new SuccessExecuteResponse(), "Result found in cache") + } else { + info("Cache not found, submit to normal consumer.") + submitToExecute(job) + } + }{ + case t: Throwable => + warn("Read cache failed, submit to normal consumer: ", t) + submitToExecute(job) + } + case _ => + } + case _ => + } + } + + private def listResults(resultLocation: String, user: String) = { + val dirPath = FsPath.getFsPath(resultLocation) + val fileSystem = FSFactory.getFsByProxyUser(dirPath, user).asInstanceOf[FileSystem] + Utils.tryFinally { + fileSystem.init(null) + if (fileSystem.exists(dirPath)) { + fileSystem.listPathWithError(dirPath).getFsPaths + } else { + Lists.newArrayList[FsPath](); + } + }(Utils.tryQuietly(fileSystem.close())) + } + + private def submitToExecute(job: EntranceJob) = { + val runtime = TaskUtils.getRuntimeMap(job.getParams) + runtime.put(TaskConstant.READ_FROM_CACHE, false) + TaskUtils.addRuntimeMap(job.getParams, runtime) + val groupName = schedulerContext.getOrCreateGroupFactory.getGroupNameByEvent(job) + val consumer = schedulerContext.getOrCreateConsumerManager.getOrCreateConsumer(groupName) + val index = consumer.getConsumeQueue.offer(job) + //index.map(getEventId(_, groupName)).foreach(job.setId) + if (index.isEmpty) throw new SchedulerErrorException(12001, "The submission job failed and the queue is full!(提交作业失败,队列已满!)") + } + + private def getEventId(index: Int, groupName: String): String = groupName + "_" + index +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala new file mode 100644 index 0000000000..b4c39f1042 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceGroupFactory +import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelConsumerManager + +class ReadCacheConsumerManager(maxParallelismUsers: Int, persistenceManager: PersistenceManager) extends ParallelConsumerManager(maxParallelismUsers){ + + override protected def createConsumer(groupName: String): FIFOUserConsumer = { + val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) + if(groupName.endsWith(EntranceGroupFactory.CACHE)){ + info("Create cache consumer with group: " + groupName) + new ReadCacheConsumer(getSchedulerContext, getOrCreateExecutorService, group, persistenceManager) + } else { + info("Create normal consumer with group: " + groupName) + new FIFOUserConsumer(getSchedulerContext, getOrCreateExecutorService, group) + } + } + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala index f330fcd4bf..17dcb8d145 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala @@ -1,21 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.entrance.utils import java.util -import com.google.gson.Gson import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.exception.JobHistoryFailedException +import com.webank.wedatasphere.linkis.governance.common.entity.task.{RequestPersistTask, RequestQueryTask, RequestUpdateTask, ResponsePersist} import com.webank.wedatasphere.linkis.protocol.query.cache.{CacheTaskResult, RequestReadCache} -import com.webank.wedatasphere.linkis.protocol.query.{RequestPersistTask, RequestQueryTask, RequestUpdateTask, ResponsePersist} import com.webank.wedatasphere.linkis.rpc.Sender import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState -/** - * created by cooperyang on 2020/1/2 - * Description: - */ + object JobHistoryHelper extends Logging{ private val sender = Sender.getSender(EntranceConfiguration.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME.getValue) @@ -61,13 +73,7 @@ object JobHistoryHelper extends Logging{ }else{ val data = responsePersist.getData data.get(TASK_MAP_KEY) match { - case tasks:util.List[util.Map[String, Object]] => tasks.get(0) match { - case map:util.Map[String, Object] => val gson = new Gson() - val json = gson.toJson(map) - val requestPersistTask = gson.fromJson(json, classOf[RequestPersistTask]) - requestPersistTask - case _ => throw JobHistoryFailedException(s"query from jobhistory not a correct RequestPersistTask type taskId is $taskID") - } + case tasks: util.List[RequestPersistTask] => tasks.get(0) case _ => throw JobHistoryFailedException(s"query from jobhistory not a correct List type taskId is $taskID") } } diff --git a/linkis-computation-governance/linkis-jdbc-driver/pom.xml b/linkis-computation-governance/linkis-jdbc-driver/pom.xml new file mode 100644 index 0000000000..d9ce050d0e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/pom.xml @@ -0,0 +1,80 @@ + + + + + + 4.0.0 + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + linkis-jdbc-driver + + + + com.webank.wedatasphere.linkis + linkis-computation-client + ${linkis.version} + + + junit + junit + RELEASE + test + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + maven-assembly-plugin + + + jar-with-dependencies + + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + **/*.yml + **/*.properties + **/*.sh + **/log4j2.xml + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java new file mode 100644 index 0000000000..dcedfa50a1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java @@ -0,0 +1,1088 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.math.MathContext; +import java.net.URL; +import java.sql.*; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +/** + * Data independed base class which implements the common part of + * all hive resultsets. + */ +public abstract class LinkisBaseResultSet implements ResultSet{ + protected SQLWarning warningChain = null; + protected boolean wasNull = false; + protected List row; + protected List columnNames; + protected List columnTypes; + + @Override + public boolean absolute(int row) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void afterLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void beforeFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void cancelRowUpdates() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void deleteRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int findColumn(String columnName) throws SQLException { + int columnIndex = columnNames.indexOf(columnName); + if (columnIndex==-1) { + throw new SQLException(); + } else { + return ++columnIndex; + } + } + + @Override + public boolean first() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Array getArray(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Array getArray(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getAsciiStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getAsciiStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + if (obj instanceof BigDecimal) { + return ((BigDecimal) obj); + } + throw new SQLException("Cannot convert column " + columnIndex + + " to BigDecimal. Found data of type: " + + obj.getClass()+", value: " + obj.toString()); + } + + @Override + public BigDecimal getBigDecimal(String columnName) throws SQLException { + return getBigDecimal(findColumn(columnName)); + } + + @Override + public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { + MathContext mc = new MathContext(scale); + return getBigDecimal(columnIndex).round(mc); + } + + @Override + public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { + return getBigDecimal(findColumn(columnName), scale); + } + + @Override + public InputStream getBinaryStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getBinaryStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Blob getBlob(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Blob getBlob(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean getBoolean(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (Boolean.class.isInstance(obj)) { + return (Boolean) obj; + } else if (obj == null) { + return false; + } else if (Number.class.isInstance(obj)) { + return ((Number) obj).intValue() != 0; + } else if (String.class.isInstance(obj)) { + return !((String) obj).equals("0"); + } + throw new SQLException("Cannot convert column " + columnIndex + " to boolean"); + } + + @Override + public boolean getBoolean(String columnName) throws SQLException { + return getBoolean(findColumn(columnName)); + } + + @Override + public byte getByte(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).byteValue(); + } else if (obj == null) { + return 0; + } + throw new SQLException("Cannot convert column " + columnIndex + " to byte"); + } + + @Override + public byte getByte(String columnName) throws SQLException { + return getByte(findColumn(columnName)); + } + + @Override + public byte[] getBytes(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public byte[] getBytes(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getCharacterStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getCharacterStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Clob getClob(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Clob getClob(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getConcurrency() throws SQLException { + return ResultSet.CONCUR_READ_ONLY; + } + + @Override + public String getCursorName() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Date getDate(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + + if (obj instanceof Date) { + return (Date) obj; + } + + try { + if (obj instanceof String) { + return Date.valueOf((String)obj); + } + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to date: " + e.toString()); + } + + throw new SQLException("Illegal conversion"); + } + + @Override + public Date getDate(String columnName) throws SQLException { + return getDate(findColumn(columnName)); + } + + @Override + public Date getDate(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Date getDate(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public double getDouble(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).doubleValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Double.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to double: " + e.toString()); + } + } + + @Override + public double getDouble(String columnName) throws SQLException { + return getDouble(findColumn(columnName)); + } + + @Override + public int getFetchDirection() throws SQLException { + return ResultSet.FETCH_FORWARD; + } + + @Override + public int getFetchSize() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public float getFloat(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).floatValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Float.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to float: " + e.toString()); + } + } + + @Override + public float getFloat(String columnName) throws SQLException { + return getFloat(findColumn(columnName)); + } + + @Override + public int getHoldability() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getInt(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).intValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Integer.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + " to integer" + e.toString()); + } + } + + @Override + public int getInt(String columnName) throws SQLException { + return getInt(findColumn(columnName)); + } + + @Override + public long getLong(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).longValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Long.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + " to long: " + e.toString()); + } + } + + @Override + public long getLong(String columnName) throws SQLException { + return getLong(findColumn(columnName)); + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException { + UJESSQLResultSetMetaData resultSetMetaData = new UJESSQLResultSetMetaData(); + if (null != columnNames) { + for (int i=0; i< columnNames.size(); i++ ) { + resultSetMetaData.setColumnNameProperties(i +1 , columnNames.get(i)); + resultSetMetaData.setDataTypeProperties(i + 1 , columnTypes.get(i)); + } + } + return resultSetMetaData; + } + + @Override + public Reader getNCharacterStream(int arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getNCharacterStream(String arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public NClob getNClob(int arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public NClob getNClob(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public String getNString(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public String getNString(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(int columnIndex) throws SQLException { + if (row == null) { + throw new SQLException("No row found."); + } + + if (columnIndex > row.size()) { + throw new SQLException("Invalid columnIndex: " + columnIndex); + } + + try { + wasNull = false; + if (row.get(columnIndex - 1) == null) { + wasNull = true; + } + + return row.get(columnIndex - 1); + } catch (Exception e) { + throw new SQLException(e.toString()); + } + } + + + @Override + public Object getObject(String columnName) throws SQLException { + return getObject(findColumn(columnName)); + } + + @Override + public T getObject(int columnIndex, Class type) throws SQLException { + // TODO method required by JDK 1.7 + throw new SQLException("Method not supported"); + } + + @Override + public T getObject(String columnLabel, Class type) throws SQLException { + // TODO method required by JDK 1.7 + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(int i, Map> map) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(String colName, Map> map) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Ref getRef(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Ref getRef(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public RowId getRowId(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public RowId getRowId(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public SQLXML getSQLXML(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public SQLXML getSQLXML(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public short getShort(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).shortValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Short.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to short: " + e.toString()); + } + } + + @Override + public short getShort(String columnName) throws SQLException { + return getShort(findColumn(columnName)); + } + + @Override + public Statement getStatement() throws SQLException { + throw new SQLException("Method not supported"); + } + + /** + * @param columnIndex - the first column is 1, the second is 2, ... + * @see ResultSet#getString(int) + */ + @Override + public String getString(int columnIndex) throws SQLException { + // Column index starts from 1, not 0. + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + + return obj.toString(); + } + + @Override + public String getString(String columnName) throws SQLException { + return getString(findColumn(columnName)); + } + + @Override + public Time getTime(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Timestamp getTimestamp(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + if (obj instanceof Timestamp) { + return (Timestamp) obj; + } + if (obj instanceof String) { + return Timestamp.valueOf((String)obj); + } + throw new SQLException("Illegal conversion"); + } + + @Override + public Timestamp getTimestamp(String columnName) throws SQLException { + return getTimestamp(findColumn(columnName)); + } + + @Override + public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getType() throws SQLException { + return ResultSet.TYPE_FORWARD_ONLY; + } + + @Override + public URL getURL(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public URL getURL(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getUnicodeStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getUnicodeStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void insertRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isAfterLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isBeforeFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isClosed() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean last() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void moveToCurrentRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void moveToInsertRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean previous() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void refreshRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean relative(int rows) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowDeleted() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowInserted() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowUpdated() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void setFetchDirection(int direction) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void setFetchSize(int rows) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateArray(int columnIndex, Array x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateArray(String columnName, Array x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnName, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnName, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, Blob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnName, Blob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, InputStream inputStream, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnLabel, InputStream inputStream, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBoolean(int columnIndex, boolean x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBoolean(String columnName, boolean x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateByte(int columnIndex, byte x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateByte(String columnName, byte x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBytes(int columnIndex, byte[] x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBytes(String columnName, byte[] x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnName, Reader reader, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Clob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnName, Clob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDate(int columnIndex, Date x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDate(String columnName, Date x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDouble(int columnIndex, double x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDouble(String columnName, double x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateFloat(int columnIndex, float x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateFloat(String columnName, float x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateInt(int columnIndex, int x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateInt(String columnName, int x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateLong(int columnIndex, long x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateLong(String columnName, long x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, NClob clob) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, NClob clob) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNString(int columnIndex, String string) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNString(String columnLabel, String string) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNull(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNull(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(int columnIndex, Object x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(String columnName, Object x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(int columnIndex, Object x, int scale) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(String columnName, Object x, int scale) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRef(int columnIndex, Ref x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRef(String columnName, Ref x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRow() throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRowId(int columnIndex, RowId x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRowId(String columnLabel, RowId x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateShort(int columnIndex, short x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateShort(String columnName, short x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateString(int columnIndex, String x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateString(String columnName, String x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTime(int columnIndex, Time x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTime(String columnName, Time x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTimestamp(String columnName, Timestamp x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public SQLWarning getWarnings() throws SQLException { + return warningChain; + } + @Override + public void clearWarnings() throws SQLException { + warningChain = null; + } + @Override + public void close() throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public boolean wasNull() throws SQLException { + return wasNull; + } + @Override + public boolean isWrapperFor(Class> iface) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public T unwrap(Class iface) throws SQLException { + throw new SQLException("Method not supported"); + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java new file mode 100644 index 0000000000..77505cb830 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public abstract class LinkisMetaDataResultSet extends LinkisBaseResultSet { + + protected final List data; + + @SuppressWarnings("unchecked") + public LinkisMetaDataResultSet(final List columnNames + , final List columnTypes + , final List data) throws SQLException { + if (data!=null) { + this.data = new ArrayList(data); + } else { + this.data = new ArrayList(); + } + if (columnNames!=null) { + this.columnNames = new ArrayList(columnNames); + } else { + this.columnNames = new ArrayList(); + } + if (columnTypes!=null) { + this.columnTypes = new ArrayList(columnTypes); + } else { + this.columnTypes = new ArrayList(); + } + } + + @Override + public void close() throws SQLException { + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java new file mode 100644 index 0000000000..a8c0466538 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +public enum TableType { + TABLE, VIEW, TMP_TABLE +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java new file mode 100644 index 0000000000..02b4c9abfd --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java @@ -0,0 +1,59 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class UJESSQLDriver extends UJESSQLDriverMain implements Driver { + static { + try { + DriverManager.registerDriver(new UJESSQLDriver()); + } catch (SQLException e) { + Logger logger = LoggerFactory.getLogger(UJESSQLDriver.class); + logger.info("Load driver failed",e); + } + } + + static String URL_PREFIX = "jdbc:linkis://"; + static String URL_REGEX = "jdbc:linkis://([^:]+)(:\\d+)?(/[^\\?]+)?(\\?\\S*)?"; + + static String HOST = "HOST"; + static String PORT = "PORT"; + static String DB_NAME = "DBNAME"; + static String PARAMS = "PARAMS"; + + static String USER = "user"; + static String PASSWORD = "password"; + + static String VERSION = "version"; + static int DEFAULT_VERSION = 1; + static String MAX_CONNECTION_SIZE = "maxConnectionSize"; + static String READ_TIMEOUT = "readTimeout"; + static String ENABLE_DISCOVERY = "enableDiscovery"; + static String ENABLE_LOADBALANCER = "enableLoadBalancer"; + static String CREATOR = "creator"; + + static String VARIABLE_HEADER = "var:"; + static String PARAM_SPLIT = "&"; + static String KV_SPLIT = "="; + +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java new file mode 100644 index 0000000000..758c59fd20 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +public enum UJESSQLErrorCode { + BAD_URL(80000,"bad url"), + NOSUPPORT_DRIVER(80001,"this method not supported in driver"), + NOSUPPORT_CONNECTION(80002, "this method not supported in connection"), + NOSUPPORT_STATEMENT(80003,"this method not supported in statement"), + CONNECTION_CLOSED(80004,"Connection is closed!"), + STATEMENT_CLOSED(80005,"statement is closed!"), + SCHEMA_EMPTY(80006,"schema is empty!"), + SCHEMA_FAILED(80007,"Get schema failed!"), + QUERY_TIMEOUT(80008,"query has been timeout!"), + FILETYPE_ERROR(80009,"file type error"), + METADATATYPE_ERROR(80010,"metadata type error"), + NOSUPPORT_METADATA(80011, "this method not supported in DatabaseMetaData"), + NOPERMITION(80012,"This user has no permission to read this file!"), + PARAMS_NOT_FOUND(80013, "Parameter not found"), + ERRORINFO_FROM_JOBINFO(80014,"get errorinfo from jobInfo"), + RESULTSET_ROWERROR(80015,"row message error"), + NOSUPPORT_RESULTSET(80016,"this method not supported in resultSet"), + RESULTSET_NULL(80017,"resultset is null,try to run next() firstly to init ResultSet and MetaData"), + PREPARESTATEMENT_TYPEERROR(80018,"parameter type error"), + METADATA_EMPTY(80019,"data is empty") + ; + private String msg; + private int code; + + UJESSQLErrorCode(int code,String msg) { + this.code = code; + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public int getCode() { + return code; + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java new file mode 100644 index 0000000000..4fe9b9becb --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java @@ -0,0 +1,188 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.entity; + +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLTypeParser; + +import java.sql.SQLException; +import java.sql.Types; + +/** + * Column metadata. + */ +public class JdbcColumn { + + private final String columnName; + private final String tableName; + private final String tableCatalog; + private final String type; + private final String comment; + private final int ordinalPos; + + public JdbcColumn(String columnName, String tableName, String tableCatalog + , String type, String comment, int ordinalPos) { + this.columnName = columnName; + this.tableName = tableName; + this.tableCatalog = tableCatalog; + this.type = type; + this.comment = comment; + this.ordinalPos = ordinalPos; + } + + public String getColumnName() { + return columnName; + } + + public String getTableName() { + return tableName; + } + + public String getTableCatalog() { + return tableCatalog; + } + + public String getType() { + return type; + } + + public Integer getSqlType() throws SQLException { + return UJESSQLTypeParser.parserFromName(type); + } + + static int columnDisplaySize(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + return columnPrecision(columnType); + case Types.VARCHAR: + return Integer.MAX_VALUE; // hive has no max limit for strings + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + return columnPrecision(columnType) + 1; // allow +/- + case Types.DATE: + return 10; + case Types.TIMESTAMP: + return columnPrecision(columnType); + // see http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Float.MAX_EXPONENT + case Types.FLOAT: + return 24; // e.g. -(17#).e-### + // see http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Double.MAX_EXPONENT + case Types.DOUBLE: + return 25; // e.g. -(17#).e-#### + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + static int columnPrecision(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + return 1; + case Types.VARCHAR: + case Types.CHAR: + return Integer.MAX_VALUE; // hive has no max limit for strings + case Types.TINYINT: + return 3; + case Types.SMALLINT: + return 5; + case Types.INTEGER: + return 10; + case Types.BIGINT: + return 19; + case Types.FLOAT: + return 7; + case Types.DOUBLE: + return 15; + case Types.DATE: + return 10; + case Types.TIMESTAMP: + return 29; + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + static int columnScale(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + case Types.VARCHAR: + case Types.CHAR: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.DATE: + return 0; + case Types.FLOAT: + return 7; + case Types.DOUBLE: + return 15; + case Types.TIMESTAMP: + return 9; + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + public Integer getColumnSize() throws SQLException { + int precision = columnPrecision(UJESSQLTypeParser.parserFromName(type)); + + return precision == 0 ? null : precision; + } + + public Integer getDecimalDigits() throws SQLException { + return columnScale(UJESSQLTypeParser.parserFromName(type)); + } + + public Integer getNumPrecRadix() { + if (type.equalsIgnoreCase("tinyint")) { + return 10; + } else if (type.equalsIgnoreCase("smallint")) { + return 10; + } else if (type.equalsIgnoreCase("int")) { + return 10; + } else if (type.equalsIgnoreCase("bigint")) { + return 10; + } else if (type.equalsIgnoreCase("decimal")) { + return 10; + } else if (type.equalsIgnoreCase("float")) { + return 2; + } else if (type.equalsIgnoreCase("double")) { + return 2; + } else { // anything else including boolean and string is null + return null; + } + } + + public String getComment() { + return comment; + } + + public int getOrdinalPos() { + return ordinalPos; + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java new file mode 100644 index 0000000000..7ddfdce5cc --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.utils; + +public class JDBCUtils { + + + private static final char SEARCH_STRING_ESCAPE = '\\'; + + public static String convertPattern(final String pattern) { + if (pattern==null) { + return ".*"; + } else { + StringBuilder result = new StringBuilder(pattern.length()); + + boolean escaped = false; + for (int i = 0, len = pattern.length(); i < len; i++) { + char c = pattern.charAt(i); + if (escaped) { + if (c != SEARCH_STRING_ESCAPE) { + escaped = false; + } + result.append(c); + } else { + if (c == SEARCH_STRING_ESCAPE) { + escaped = true; + continue; + } else if (c == '%') { + result.append(".*"); + } else if (c == '_') { + result.append('.'); + } else { + result.append(Character.toLowerCase(c)); + } + } + } + + return result.toString(); + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver b/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver new file mode 100644 index 0000000000..f8934f31c2 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver @@ -0,0 +1,17 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala new file mode 100644 index 0000000000..58cb335d8f --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.ParameterMetaData + +class LinkisParameterMetaData(parameterCount: Int) extends ParameterMetaData{ + + override def getParameterCount: Int = parameterCount + + override def isNullable(param: Int): Int = 1 + + override def isSigned(param: Int): Boolean = true + + override def getPrecision(param: Int): Int = Int.MaxValue + + override def getScale(param: Int): Int = 10 + + override def getParameterType(param: Int): Int = 12 + + override def getParameterTypeName(param: Int): String = "VARCHAR" + + override def getParameterClassName(param: Int): String = "java.lang.String" + + override def getParameterMode(param: Int): Int = 1 + + override def unwrap[T](iface: Class[T]): T = iface.cast(this) + + override def isWrapperFor(iface: Class[_]): Boolean = iface.isInstance(this) +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala similarity index 79% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala index a29fcd9f18..10dd9268f5 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.util @@ -6,12 +22,9 @@ import java.util.Properties import com.webank.wedatasphere.linkis.httpclient.dws.authentication.StaticAuthenticationStrategy import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfigBuilder import com.webank.wedatasphere.linkis.ujes.client.UJESClient -import UJESSQLDriverMain._ +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriverMain._ import org.apache.commons.lang.StringUtils -/** - * Created by enjoyyin on 2019/5/27. - */ object UJESClientFactory { private val ujesClients = new util.HashMap[String, UJESClient] diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala similarity index 89% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala index 7360bfe35c..ae7703309c 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Blob, CallableStatement, Clob, Connection, DatabaseMetaData, NClob, PreparedStatement, ResultSet, SQLException, SQLWarning, SQLXML, Savepoint, Statement, Struct} @@ -12,9 +28,6 @@ import org.apache.commons.lang.StringUtils import scala.collection.{JavaConversions, mutable} -/** - * Created by enjoyyin on 2019/5/27. - */ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Properties) extends Connection with Logging { private[jdbc] var creator = "IDE" private[jdbc] val variableMap = { @@ -31,19 +44,32 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert } map.toMap } - private[jdbc] val dbName = props.getProperty(DB_NAME) + private[jdbc] val dbName = if (StringUtils.isNotBlank(props.getProperty(DB_NAME))) props.getProperty(DB_NAME) else "default" + private val runningSQLStatements = new util.LinkedList[Statement] + private var closed = false + + private var inited = false + private[jdbc] val user = props.getProperty(USER) + private[jdbc] val serverURL = props.getProperty("URL") + + private[jdbc] def throwWhenClosed[T](op: => T): T = if(isClosed) throw new UJESSQLException(UJESSQLErrorCode.CONNECTION_CLOSED) else op private def createStatementAndAdd[T<:Statement](op: => T): T = throwWhenClosed { + val statement = op runningSQLStatements.add(statement) + if (! inited) { + inited = true + Utils.tryAndWarn(statement.execute(s"USE $dbName")) + } statement } def getProps : Properties = props @@ -52,7 +78,11 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def createStatement(): Statement = createStatementAndAdd(new UJESSQLStatement(this)) - override def prepareStatement(sql: String): UJESSQLPreparedStatement = createStatementAndAdd(new UJESSQLPreparedStatement(this, sql)) + override def prepareStatement(sql: String): UJESSQLPreparedStatement = { + val statement = createStatementAndAdd(new UJESSQLPreparedStatement(this, sql)) + statement.clearQuery() + statement + } override def createStatement(resultSetType: Int, resultSetConcurrency: Int): Statement = { if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) @@ -92,11 +122,11 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def clearWarnings(): Unit = {} - override def setAutoCommit(autoCommit: Boolean): Unit = if(autoCommit) throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "setAutoCommit not supported") + override def setAutoCommit(autoCommit: Boolean): Unit = {} override def getAutoCommit: Boolean = true - override def commit(): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "commit not supported") + override def commit(): Unit = {} override def prepareCall(sql: String): CallableStatement = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "prepareCall not supported") @@ -152,7 +182,7 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def createSQLXML(): SQLXML = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "createSQLXML not supported") - override def isValid(timeout: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "isValid not supported") + override def isValid(timeout: Int): Boolean = true override def setClientInfo(name: String, value: String): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "setClientInfo not supported") diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala new file mode 100644 index 0000000000..40407fda2e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala @@ -0,0 +1,561 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.{Connection, DatabaseMetaData, ResultSet, RowIdLifetime} +import java.util + +import com.webank.wedatasphere.linkis.ujes.client.request.{GetColumnsAction, GetDBSAction, GetTablesAction} +import com.webank.wedatasphere.linkis.ujes.jdbc.entity.JdbcColumn +import com.webank.wedatasphere.linkis.ujes.jdbc.utils.JDBCUtils +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + +class UJESSQLDatabaseMetaData(ujesSQLConnection: UJESSQLConnection) extends DatabaseMetaData { + override def allProceduresAreCallable(): Boolean = false + + override def allTablesAreSelectable(): Boolean = false + + override def getURL: String = ujesSQLConnection.getProps.getProperty("URL") + + override def getUserName: String = + if (ujesSQLConnection.getProps.containsKey("user")) + ujesSQLConnection.getProps.getProperty("user") + else throw new UJESSQLException(UJESSQLErrorCode.PARAMS_NOT_FOUND, "Missing user information") + + override def isReadOnly: Boolean = false + + override def nullsAreSortedHigh(): Boolean = false + + override def nullsAreSortedLow(): Boolean = false + + override def nullsAreSortedAtStart(): Boolean = false + + override def nullsAreSortedAtEnd(): Boolean = false + + override def getDatabaseProductName: String = "linkis" + + override def getDatabaseProductVersion: String = "" + + override def getDriverName: String = "Linkis JDBC Driver" + + override def getDriverVersion: String = UJESSQLDriverMain.DEFAULT_VERSION.toString + + override def getDriverMajorVersion: Int = UJESSQLDriverMain.DEFAULT_VERSION + + override def getDriverMinorVersion: Int = UJESSQLDriverMain.DEFAULT_VERSION + + override def usesLocalFiles(): Boolean = false + + override def usesLocalFilePerTable(): Boolean = false + + override def supportsMixedCaseIdentifiers(): Boolean = false + + override def storesUpperCaseIdentifiers(): Boolean = false + + override def storesLowerCaseIdentifiers(): Boolean = false + + override def storesMixedCaseIdentifiers(): Boolean = false + + override def supportsMixedCaseQuotedIdentifiers(): Boolean = false + + override def storesUpperCaseQuotedIdentifiers(): Boolean = false + + override def storesLowerCaseQuotedIdentifiers(): Boolean = false + + override def storesMixedCaseQuotedIdentifiers(): Boolean = false + + override def getIdentifierQuoteString: String = " " + + override def getSQLKeywords: String = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSQLKeywords not supported") + + override def getNumericFunctions: String = "" + + override def getStringFunctions: String = "" + + override def getSystemFunctions: String = "" + + override def getTimeDateFunctions: String = "" + + override def getSearchStringEscape: String = "\\" + + override def getExtraNameCharacters: String = "" + + override def supportsAlterTableWithAddColumn(): Boolean = true + + override def supportsAlterTableWithDropColumn(): Boolean = false + + override def supportsColumnAliasing(): Boolean = true + + override def nullPlusNonNullIsNull(): Boolean = false + + override def supportsConvert(): Boolean = false + + override def supportsConvert(fromType: Int, toType: Int): Boolean = false + + override def supportsTableCorrelationNames(): Boolean = false + + override def supportsDifferentTableCorrelationNames(): Boolean = false + + override def supportsExpressionsInOrderBy(): Boolean = false + + override def supportsOrderByUnrelated(): Boolean = false + + override def supportsGroupBy(): Boolean = true + + override def supportsGroupByUnrelated(): Boolean = false + + override def supportsGroupByBeyondSelect(): Boolean = false + + override def supportsLikeEscapeClause(): Boolean = false + + override def supportsMultipleResultSets(): Boolean = false + + override def supportsMultipleTransactions(): Boolean = false + + override def supportsNonNullableColumns(): Boolean = false + + override def supportsMinimumSQLGrammar(): Boolean = false + + override def supportsCoreSQLGrammar(): Boolean = false + + override def supportsExtendedSQLGrammar(): Boolean = false + + override def supportsANSI92EntryLevelSQL(): Boolean = false + + override def supportsANSI92IntermediateSQL(): Boolean = false + + override def supportsANSI92FullSQL(): Boolean = false + + override def supportsIntegrityEnhancementFacility(): Boolean = false + + override def supportsOuterJoins(): Boolean = true + + override def supportsFullOuterJoins(): Boolean = true + + override def supportsLimitedOuterJoins(): Boolean = true + + override def getSchemaTerm: String = "database" + + override def getProcedureTerm: String = new String("UDF") + + override def getCatalogTerm: String = "instance" + + override def isCatalogAtStart: Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "isCatalogAtStart not supported") + + override def getCatalogSeparator: String = "." + + override def supportsSchemasInDataManipulation(): Boolean = true + + override def supportsSchemasInProcedureCalls(): Boolean = false + + override def supportsSchemasInTableDefinitions(): Boolean = true + + override def supportsSchemasInIndexDefinitions(): Boolean = false + + override def supportsSchemasInPrivilegeDefinitions(): Boolean = false + + override def supportsCatalogsInDataManipulation(): Boolean = false + + override def supportsCatalogsInProcedureCalls(): Boolean = false + + override def supportsCatalogsInTableDefinitions(): Boolean = false + + override def supportsCatalogsInIndexDefinitions(): Boolean = false + + override def supportsCatalogsInPrivilegeDefinitions(): Boolean = false + + override def supportsPositionedDelete(): Boolean = false + + override def supportsPositionedUpdate(): Boolean = false + + override def supportsSelectForUpdate(): Boolean = false + + override def supportsStoredProcedures(): Boolean = false + + override def supportsSubqueriesInComparisons(): Boolean = false + + override def supportsSubqueriesInExists(): Boolean = false + + override def supportsSubqueriesInIns(): Boolean = false + + override def supportsSubqueriesInQuantifieds(): Boolean = false + + override def supportsCorrelatedSubqueries(): Boolean = false + + override def supportsUnion(): Boolean = false + + override def supportsUnionAll(): Boolean = true + + override def supportsOpenCursorsAcrossCommit(): Boolean = false + + override def supportsOpenCursorsAcrossRollback(): Boolean = false + + override def supportsOpenStatementsAcrossCommit(): Boolean = false + + override def supportsOpenStatementsAcrossRollback(): Boolean = false + + override def getMaxBinaryLiteralLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxBinaryLiteralLength not supported") + + override def getMaxCharLiteralLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCharLiteralLength not supported") + + override def getMaxColumnNameLength: Int = 128 + + override def getMaxColumnsInGroupBy: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInGroupBy not supported") + + override def getMaxColumnsInIndex: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInIndex not supported") + + override def getMaxColumnsInOrderBy: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInOrderBy not supported") + + override def getMaxColumnsInSelect: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInSelect not supported") + + override def getMaxColumnsInTable: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInTable not supported") + + override def getMaxConnections: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxConnections not supported") + + override def getMaxCursorNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCursorNameLength not supported") + + override def getMaxIndexLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxIndexLength not supported") + + override def getMaxSchemaNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxSchemaNameLength not supported") + + override def getMaxProcedureNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxProcedureNameLength not supported") + + override def getMaxCatalogNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCatalogNameLength not supported") + + override def getMaxRowSize: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxRowSize not supported") + + override def doesMaxRowSizeIncludeBlobs(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "doesMaxRowSizeIncludeBlobs not supported") + + override def getMaxStatementLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxStatementLength not supported") + + override def getMaxStatements: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxStatements not supported") + + override def getMaxTableNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxTableNameLength not supported") + + override def getMaxTablesInSelect: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxTablesInSelect not supported") + + override def getMaxUserNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxUserNameLength not supported") + + override def getDefaultTransactionIsolation: Int = 0 + + override def supportsTransactions(): Boolean = false + + override def supportsTransactionIsolationLevel(level: Int): Boolean = false + + override def supportsDataDefinitionAndDataManipulationTransactions(): Boolean = false + + override def supportsDataManipulationTransactionsOnly(): Boolean = false + + override def dataDefinitionCausesTransactionCommit(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "dataDefinitionCausesTransactionCommit not supported") + + override def dataDefinitionIgnoredInTransactions(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "dataDefinitionIgnoredInTransactions not supported") + + override def getProcedures(catalog: String, schemaPattern: String, procedureNamePattern: String): ResultSet = null + + override def getProcedureColumns(catalog: String, schemaPattern: String, procedureNamePattern: String, columnNamePattern: String): ResultSet = null + + override def getTables(catalog: String, schemaPattern: String, tableNamePattern: String, types: Array[String]): ResultSet = { + val resultCatalog = if (StringUtils.isNotBlank(catalog)) { + catalog + } else { + s"${getUserName}_ind" + } + val getTableAction = GetTablesAction.builder().setUser(getUserName).setDatabase(resultCatalog).build() + val result = ujesSQLConnection.ujesClient.getTables(getTableAction) + val tables = result.getTables + val resultTables = new util.ArrayList[util.Map[String, String]]() + tables.foreach { table => + val tableType = if (table.get("isView").asInstanceOf[Boolean]) TableType.VIEW.name() else TableType.TABLE.name() + val resultTable = new util.HashMap[String, String]() + resultTable.put("catalog", resultCatalog) + resultTable.put("tableName", table.get("tableName").asInstanceOf[String]) + resultTable.put("tableType", tableType) + if (null == types || types.contains(tableType)) { + resultTables.add(resultTable) + } + } + new LinkisMetaDataResultSet[util.Map[String, String]](util.Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS"), util.Arrays.asList("string", "string", "string", "string", "string"), resultTables) { + + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val resultTable = new util.ArrayList[Object](5) + val table = data.get(cnt) + resultTable.add(table.get("catalog")) + resultTable.add(null) + resultTable.add(table.get("tableName")) + resultTable.add(table.get("tableType")) + resultTable.add(table.get("")) + row = resultTable + cnt = cnt + 1 + true + } else { + false + } + } + } + + } + + override def getSchemas: ResultSet = { + new LinkisMetaDataResultSet(util.Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"), util.Arrays.asList("string", "string"), null) { + override def next(): Boolean = false + } + } + + override def getCatalogs: ResultSet = { + val getDBSAction = GetDBSAction.builder().setUser(getUserName).build() + val dBSResult = ujesSQLConnection.ujesClient.getDBS(getDBSAction) + val dbsName = dBSResult.getDBSName() + new LinkisMetaDataResultSet[String](util.Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"), util.Arrays.asList("string", "string"), dbsName) { + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val db = new util.ArrayList[Object](2) + db.add(null) + db.add(data.get(cnt)) + row = db + cnt = cnt + 1 + true + } else { + false + } + } + } + } + + override def getTableTypes: ResultSet = { + val typesList = TableType.values() + new LinkisMetaDataResultSet[TableType](util.Arrays.asList("TABLE_TYPE"), util.Arrays.asList("string"), typesList.toList) { + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val types = new util.ArrayList[Object](1) + types.add(data.get(cnt).name()) + row = types + cnt = cnt + 1 + true + } else { + false + } + } + } + } + + + override def getColumns(catalog: String, schemaPattern: String, tableNamePattern: String, columnNamePattern: String): ResultSet = { + val resultCatalog = if (StringUtils.isNotBlank(catalog)) { + catalog + } else { + s"${getUserName}_ind" + } + + val getColumnsAction = GetColumnsAction.builder().setUser(getUserName).setDatabase(resultCatalog).setTable(JDBCUtils.convertPattern(tableNamePattern)).build() + val result = ujesSQLConnection.ujesClient.getColumns(getColumnsAction) + val columns = result.getColumns + val resultColumns = new util.ArrayList[JdbcColumn]() + var ordinalPos = 1 + columns.foreach { column => + val jdbcColumn = new JdbcColumn(column.get("columnName").asInstanceOf[String], + tableNamePattern, + resultCatalog, + column.get("columnType").asInstanceOf[String], + column.get("columnComment").asInstanceOf[String], + ordinalPos + ) + resultColumns.add(jdbcColumn) + ordinalPos = ordinalPos + 1 + } + new LinkisMetaDataResultSet[JdbcColumn](util.Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE" + , "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS" + , "NUM_PREC_RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE" + , "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION" + , "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE" + , "SOURCE_DATA_TYPE"), + util.Arrays.asList("string", "string", "string", "string", "int", "string" + , "int", "int", "int", "int", "int", "string" + , "string", "int", "int", "int", "int" + , "string", "string", "string", "string", "int"), resultColumns) { + + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val jdbcColumn = new util.ArrayList[Object](20) + val column = data.get(cnt) + jdbcColumn.add(column.getTableCatalog) // TABLE_CAT String => table catalog (may be null) + + jdbcColumn.add(null) // TABLE_SCHEM String => table schema (may be null) + + jdbcColumn.add(column.getTableName) // TABLE_NAME String => table name + + jdbcColumn.add(column.getColumnName) // COLUMN_NAME String => column name + + jdbcColumn.add(column.getSqlType) // DATA_TYPE short => SQL type from java.sql.Types + + jdbcColumn.add(column.getType) // TYPE_NAME String => Data source dependent type name. + + jdbcColumn.add(column.getColumnSize) // COLUMN_SIZE int => column size. + + jdbcColumn.add(null) // BUFFER_LENGTH is not used. + + jdbcColumn.add(column.getDecimalDigits) // DECIMAL_DIGITS int => number of fractional digits + + jdbcColumn.add(column.getNumPrecRadix) // NUM_PREC_RADIX int => typically either 10 or 2 + + jdbcColumn.add(DatabaseMetaData.columnNullable.asInstanceOf[Object]) // NULLABLE int => is NULL allowed? + + jdbcColumn.add(column.getComment) // REMARKS String => comment describing column (may be null) + + jdbcColumn.add(null) // COLUMN_DEF String => default value (may be null) + + jdbcColumn.add(null) // SQL_DATA_TYPE int => unused + + jdbcColumn.add(null) // SQL_DATETIME_SUB int => unused + + jdbcColumn.add(null) // CHAR_OCTET_LENGTH int + + jdbcColumn.add(column.getOrdinalPos.asInstanceOf[Object]) // ORDINAL_POSITION int + + jdbcColumn.add("YES") // IS_NULLABLE String + + jdbcColumn.add(null) // SCOPE_CATLOG String + + jdbcColumn.add(null) // SCOPE_SCHEMA String + + jdbcColumn.add(null) // SCOPE_TABLE String + + jdbcColumn.add(null) // SOURCE_DATA_TYPE short + + row = jdbcColumn + cnt = cnt + 1 + true + } else { + false + } + } + } + + } + + override def getColumnPrivileges(catalog: String, schema: String, table: String, columnNamePattern: String): ResultSet = null + + override def getTablePrivileges(catalog: String, schemaPattern: String, tableNamePattern: String): ResultSet = null + + override def getBestRowIdentifier(catalog: String, schema: String, table: String, scope: Int, nullable: Boolean): ResultSet = null + + override def getVersionColumns(catalog: String, schema: String, table: String): ResultSet = null + + override def getPrimaryKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getImportedKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getExportedKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getCrossReference(parentCatalog: String, parentSchema: String, parentTable: String, foreignCatalog: String, foreignSchema: String, foreignTable: String): ResultSet = null + + override def getTypeInfo: ResultSet = null + + override def getIndexInfo(catalog: String, schema: String, table: String, unique: Boolean, approximate: Boolean): ResultSet = null + + override def supportsResultSetType(`type`: Int): Boolean = true + + override def supportsResultSetConcurrency(`type`: Int, concurrency: Int): Boolean = false + + override def ownUpdatesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownUpdatesAreVisible not supported") + + override def ownDeletesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownDeletesAreVisible not supported") + + override def ownInsertsAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownInsertsAreVisible not supported") + + override def othersUpdatesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersUpdatesAreVisible not supported") + + override def othersDeletesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersDeletesAreVisible not supported") + + override def othersInsertsAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersInsertsAreVisible not supported") + + override def updatesAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "updatesAreDetected not supported") + + override def deletesAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "deletesAreDetected not supported") + + override def insertsAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "insertsAreDetected not supported") + + override def supportsBatchUpdates(): Boolean = false + + override def getUDTs(catalog: String, schemaPattern: String, typeNamePattern: String, types: Array[Int]): ResultSet = null + + override def getConnection: Connection = ujesSQLConnection + + override def supportsSavepoints(): Boolean = false + + override def supportsNamedParameters(): Boolean = false + + override def supportsMultipleOpenResults(): Boolean = false + + override def supportsGetGeneratedKeys(): Boolean = false + + override def getSuperTypes(catalog: String, schemaPattern: String, typeNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSuperTypes not supported") + + override def getSuperTables(catalog: String, schemaPattern: String, tableNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSuperTables not supported") + + override def getAttributes(catalog: String, schemaPattern: String, typeNamePattern: String, attributeNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getAttributes not supported") + + override def supportsResultSetHoldability(holdability: Int): Boolean = false + + override def getResultSetHoldability: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getResultSetHoldability not supported") + + override def getDatabaseMajorVersion: Int = 1 + + override def getDatabaseMinorVersion: Int = 1 + + override def getJDBCMajorVersion: Int = 3 + + override def getJDBCMinorVersion: Int = 0 + + override def getSQLStateType: Int = 2 + + override def locatorsUpdateCopy(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "locatorsUpdateCopy not supported") + + override def supportsStatementPooling(): Boolean = false + + override def getRowIdLifetime: RowIdLifetime = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getRowIdLifetime not supported") + + override def getSchemas(catalog: String, schemaPattern: String): ResultSet = null + + override def supportsStoredFunctionsUsingCallSyntax(): Boolean = false + + override def autoCommitFailureClosesAllResultSets(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "autoCommitFailureClosesAllResultSets not supported") + + override def getClientInfoProperties: ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getClientInfoProperties not supported") + + override def getFunctions(catalog: String, schemaPattern: String, functionNamePattern: String): ResultSet = null + + override def getFunctionColumns(catalog: String, schemaPattern: String, functionNamePattern: String, columnNamePattern: String): ResultSet = null + + override def getPseudoColumns(catalog: String, schemaPattern: String, tableNamePattern: String, columnNamePattern: String): ResultSet = null + + override def generatedKeyAlwaysReturned(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "generatedKeyAlwaysReturned not supported") + + override def unwrap[T](iface: Class[T]): T = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "unwrap not supported") + + override def isWrapperFor(iface: Class[_]): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "isWrapperFor not supported") +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala similarity index 85% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala index ddd04031c4..3fc3a1dc16 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala @@ -1,21 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Connection, Driver, DriverManager, DriverPropertyInfo, SQLFeatureNotSupportedException} import java.util.Properties import java.util.logging.Logger -import UJESSQLDriverMain._ +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriverMain._ import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions -/** - * Created by enjoyyin on 2019/5/27. - */ -class UJESSQLDriverMain extends Driver { - override def connect(url: String, info: Properties): Connection = if(acceptsURL(url)) { - val props = if(info != null) info else new Properties +class UJESSQLDriverMain extends Driver with Logging{ + + override def connect(url: String, properties: Properties): Connection = if(acceptsURL(url)) { + val props = if(properties != null) properties else new Properties props.putAll(parseURL(url)) + info(s"input url:$url, properties:$properties") val ujesClient = UJESClientFactory.getUJESClient(props) new UJESSQLConnection(ujesClient, props) } else throw new UJESSQLException(UJESSQLErrorCode.BAD_URL, "bad url: " + url) diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala new file mode 100644 index 0000000000..48675b7e7e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + +class UJESSQLException (errorCode: UJESSQLErrorCode) extends ErrorException(errorCode.getCode,errorCode.getMsg) { + def this(errorCode: UJESSQLErrorCode, msg: String) { + this(errorCode) + setErrCode(errorCode.getCode) + setDesc(msg) + } + + + /** + * add to deal with errorinfo derived from jobInfo + * @param errorCode + * @param msg + */ + def this(errorCode: Int,msg: String) { + this(UJESSQLErrorCode.ERRORINFO_FROM_JOBINFO) + setDesc(msg) + setErrCode(errorCode) + } + +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala similarity index 86% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala index f88ca4158f..8436e993e2 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala @@ -1,19 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.io.{InputStream, Reader} import java.net.URL -import java.sql.{Blob, Clob, Connection, Date, NClob, ParameterMetaData, PreparedStatement, Ref, ResultSet, ResultSetMetaData, RowId, SQLWarning, SQLXML, Time, Timestamp} +import java.sql.{Blob, Clob, Date, NClob, ParameterMetaData, PreparedStatement, Ref, ResultSetMetaData, RowId, SQLXML, Time, Timestamp} import java.util import java.util.Calendar - -/** - * Created by leebai on 2019/8/16 - */ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String) extends UJESSQLStatement(ujesSQLConnection) with PreparedStatement { private val parameters = new util.HashMap[Int,Any] + private var parameterMetaData: ParameterMetaData = _ + + private var batchTimes = 0 + private def updateSql(sql: String, parameters: util.HashMap[Int,Any]) : String = { if(!sql.contains("?")){ sql @@ -153,11 +169,23 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String } override def execute(): Boolean = { - super.execute(updateSql(sql,parameters)) + val res = super.execute(updateSql(sql,parameters)) + for (i <- 1 to batchTimes) { + super.execute(updateSql(sql,parameters)) + } + res + } + + override def executeBatch(): Array[Int] = { + + for (i <- 0 to batchTimes) { + super.execute(updateSql(sql,parameters)) + } + Array(1,1) } override def addBatch(): Unit = { - throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT) + this.batchTimes = this.batchTimes + 1 } override def setCharacterStream(parameterIndex: Int, reader: Reader, length: Int): Unit = { @@ -182,7 +210,8 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String override def getMetaData: ResultSetMetaData = { if(super.getResultSet == null){ - throw new UJESSQLException(UJESSQLErrorCode.RESULTSET_NULL) + //TODO 这里应该返回的是获取到到的结果集元数据 + return new UJESSQLResultSetMetaData } super.getResultSet.getMetaData } @@ -208,7 +237,12 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String } override def getParameterMetaData: ParameterMetaData = { - throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT) + synchronized { + if (null == this.parameterMetaData) { + this.parameterMetaData = new LinkisParameterMetaData(sql.count(_ =='?' )) + } + } + this.parameterMetaData } override def setRowId(parameterIndex: Int, x: RowId): Unit = { diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala similarity index 94% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala index e4fe963653..557878d1e7 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala @@ -1,19 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.io.{InputStream, Reader} import java.math.MathContext import java.net.URL -import java.sql.{Blob, Clob, Connection, Date, NClob, Ref, ResultSet, ResultSetMetaData, RowId, SQLWarning, SQLXML, Statement, Time, Timestamp} +import java.sql.{Blob, Clob, Connection, Date, NClob, Ref, ResultSet, RowId, SQLWarning, SQLXML, Statement, Time, Timestamp} import java.util.Calendar import java.{sql, util} + import com.webank.wedatasphere.linkis.ujes.client.request.ResultSetAction import com.webank.wedatasphere.linkis.ujes.client.response.ResultSetResult - - - -/** - * Created by leebai on 2019/8/14. - */ +import org.apache.commons.lang.StringUtils class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLStatement, maxRows: Int, fetchSize: Int) extends ResultSet { @@ -26,7 +38,6 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var resultSetMetaData: UJESSQLResultSetMetaData = new UJESSQLResultSetMetaData - private var maxRowNum : Int = _ private var fetchSizeNum : Int = _ @@ -36,11 +47,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var path : String = null - private val page : Int = 1 - - private val pageSize : Int = 5000 - - private var metaData : util.ArrayList[String] = _ + private var metaData : util.List[util.Map[String, String]] = _ private val statement : UJESSQLStatement = ujesStatement @@ -50,28 +57,42 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var warningChain : SQLWarning = null + init() + private def getResultSetPath(resultSetList: Array[String]): String = { - resultSetList(resultSetList.length-1) + if (resultSetList.length > 0){ + resultSetList(resultSetList.length-1) + } else { + "" + } } private def resultSetResultInit(): Unit = { if (path == null) path = getResultSetPath(resultSetList) val user = connection.getProps.getProperty("user") - val resultAction = ResultSetAction.builder.setUser(user).setPath(path).build() - resultSetResult = connection.ujesClient.resultSet(resultAction) + if (StringUtils.isNotBlank(path)){ + val resultAction = ResultSetAction.builder.setUser(user).setPath(path).build() + resultSetResult = connection.ujesClient.resultSet(resultAction) + } } private def metaDataInit(): Unit = { - metaData = resultSetResult.getMetadata.asInstanceOf[util.ArrayList[String]] + if ( null == resultSetResult ){ + return + } + metaData = resultSetResult.getMetadata.asInstanceOf[util.List[util.Map[String, String]]] for(cursor <- 1 to metaData.size()){ - val str: Array[String] = metaData.get(cursor-1).split(",") - resultSetMetaData.setColumnNameProperties(cursor,str(0).split(":")(1)) - resultSetMetaData.setDataTypeProperties(cursor,str(1).split(":")(1)) - resultSetMetaData.setCommentPropreties(cursor,str(2).split(":")(1)) + val col = metaData.get(cursor - 1) + resultSetMetaData.setColumnNameProperties(cursor, col.get("columnName")) + resultSetMetaData.setDataTypeProperties(cursor, col.get("dataType")) + resultSetMetaData.setCommentPropreties(cursor, col.get("comment")) } } private def resultSetInit(): Unit = { + if ( null == resultSetResult ){ + return + } resultSetRow = resultSetResult.getFileContent.asInstanceOf[util.ArrayList[util.ArrayList[String]]] } @@ -90,7 +111,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState override def next(): Boolean = { if(metaData == null) init() currentRowCursor += 1 - if(currentRowCursor > resultSetRow.size()-1) false + if(null == resultSetRow || currentRowCursor > resultSetRow.size()-1) false else{ updateCurrentRow(currentRowCursor) true @@ -204,7 +225,10 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState if(wasNull()) { throw new UJESSQLException(UJESSQLErrorCode.RESULTSET_ROWERROR, "Type is null") }else{ - any.asInstanceOf[Long] + any match { + case i:Integer => i.longValue() + case _ => any.asInstanceOf[Long] + } } } @@ -356,6 +380,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState } override def getMetaData: UJESSQLResultSetMetaData = { + if(metaData == null) init() resultSetMetaData } diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala new file mode 100644 index 0000000000..d910932bd1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala @@ -0,0 +1,115 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.ResultSetMetaData +import java.util + +class UJESSQLResultSetMetaData extends ResultSetMetaData { + private val columnNameProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private val dataTypeProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private val commentProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private[jdbc] def setColumnNameProperties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + columnNameProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + private[jdbc] def setDataTypeProperties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + dataTypeProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + private[jdbc] def setCommentPropreties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + commentProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + override def getColumnCount: Int = { + columnNameProperties.size + } + + override def isAutoIncrement(column: Int): Boolean = { + throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) + } + + override def isCaseSensitive(column: Int): Boolean = true + + override def isSearchable(column: Int): Boolean = true + + override def isCurrency(column: Int): Boolean = true + + override def isNullable(column: Int): Int = 1 + + override def isSigned(column: Int): Boolean = true + + override def getColumnDisplaySize(column: Int): Int = 1 + + override def getColumnLabel(column: Int): String = { + if(columnNameProperties.get(column) == null) { + throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + }else columnNameProperties.get(column) + } + + override def getColumnName(column: Int): String = { + getColumnLabel(column) + } + + override def getSchemaName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + //TODO 修改该参数 + override def getPrecision(column: Int): Int = 2147483647 + + override def getScale(column: Int): Int = { + columnNameProperties.size + } + + override def getTableName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getCatalogName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getColumnType(column: Int): Int = { + UJESSQLTypeParser.parserFromName(getColumnTypeName(column)) + } + + override def getColumnTypeName(column: Int): String = { + if(dataTypeProperties.get(column) == null) { + throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + }else dataTypeProperties.get(column) + } + + override def isReadOnly(column: Int): Boolean = { + true + } + + override def isWritable(column: Int): Boolean = { + false + } + + override def isDefinitelyWritable(column: Int): Boolean = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getColumnClassName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def unwrap[T](iface: Class[T]): T = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def isWrapperFor(iface: Class[_]): Boolean = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala similarity index 88% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala index e9021afa53..d5d93ab3fa 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Connection, ResultSet, SQLWarning, Statement} @@ -8,14 +24,12 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.EngineType import com.webank.wedatasphere.linkis.ujes.client.response.JobExecuteResult +import com.webank.wedatasphere.linkis.ujes.jdbc.hook.JDBCDriverPreExecutionHook import scala.collection.JavaConversions import scala.concurrent.TimeoutException import scala.concurrent.duration.Duration -/** - * Created by owenxu on 2019/8/19 - */ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) extends Statement with Logging{ private var jobExecuteResult: JobExecuteResult = _ @@ -25,6 +39,8 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e private var fetchSize = 100 private var queryTimeout = 0 + private var queryEnd = false + private[jdbc] def throwWhenClosed[T](op: => T): T = ujesSQLConnection.throwWhenClosed { if(isClosed) throw new UJESSQLException(UJESSQLErrorCode.STATEMENT_CLOSED) else op @@ -46,7 +62,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e } def clearQuery(): Unit = { - if(jobExecuteResult != null) { + if(jobExecuteResult != null && ! queryEnd) { Utils.tryAndWarn(ujesSQLConnection.ujesClient.kill(jobExecuteResult)) jobExecuteResult = null } @@ -79,10 +95,17 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e override def setCursorName(name: String): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT, "setCursorName not supported") override def execute(sql: String): Boolean = throwWhenClosed { - val action = JobExecuteAction.builder().setEngineType(EngineType.SPARK).addExecuteCode(sql) + var parsedSQL = sql + JDBCDriverPreExecutionHook.getPreExecutionHooks.foreach{ + preExecution => + parsedSQL = preExecution.callPreExecutionHook(parsedSQL) + } + val action = JobExecuteAction.builder().setEngineType(EngineType.SPARK).addExecuteCode(parsedSQL) .setCreator(ujesSQLConnection.creator).setUser(ujesSQLConnection.user) + if(ujesSQLConnection.variableMap.nonEmpty) action.setVariableMap(JavaConversions.mapAsJavaMap(ujesSQLConnection.variableMap)) jobExecuteResult = ujesSQLConnection.ujesClient.execute(action.build()) + queryEnd = false var status = ujesSQLConnection.ujesClient.status(jobExecuteResult) val atMost = if(queryTimeout > 0) Duration(queryTimeout, TimeUnit.MILLISECONDS) else Duration.Inf if(!status.isCompleted) Utils.tryThrow{ @@ -99,7 +122,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e if(!closed) { var jobInfo = ujesSQLConnection.ujesClient.getJobInfo(jobExecuteResult) if(status.isFailed) throw new ErrorException(jobInfo.getRequestPersistTask.getErrCode,jobInfo.getRequestPersistTask.getErrDesc) - var jobInfoStatus = jobInfo.getJobStatus + val jobInfoStatus = jobInfo.getJobStatus if(!jobInfoStatus.equals("Succeed")) Utils.tryThrow{ Utils.waitUntil(() => { jobInfo = ujesSQLConnection.ujesClient.getJobInfo(jobExecuteResult) @@ -116,6 +139,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e case t => t } val resultSetList = jobInfo.getResultSetList(ujesSQLConnection.ujesClient) + queryEnd = true if(resultSetList != null) { resultSet = new UJESSQLResultSet(resultSetList, this, maxRows, fetchSize) true diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala new file mode 100644 index 0000000000..094a7bd64b --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.{SQLException, Timestamp, Types} + +object UJESSQLTypeParser { + def parserFromName(typeName: String): Int = { + typeName.toLowerCase match { + case null => throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + case "string" => Types.CHAR + case "short" => Types.SMALLINT + case "int" => Types.INTEGER + case "long" => Types.BIGINT + case "float" => Types.FLOAT + case "double" => Types.DOUBLE + case "boolean" => Types.BOOLEAN + case "byte" => Types.TINYINT + case "char" => Types.CHAR + case "timestamp" => Types.TIMESTAMP + case _ => throw new SQLException( s"parameter type error,Type:$typeName") + } + } + + def parserFromVal(obj: Any): Int ={ + obj match { + case _: String => Types.CHAR + case _: Short => Types.SMALLINT + case _: Int => Types.INTEGER + case _: Long => Types.BIGINT + case _: Float => Types.FLOAT + case _: Double => Types.DOUBLE + case _: Boolean => Types.BOOLEAN + case _: Byte => Types.TINYINT + case _: Char => Types.CHAR + case _: Timestamp => Types.TIMESTAMP + case _ => throw new UJESSQLException(UJESSQLErrorCode.PREPARESTATEMENT_TYPEERROR) + } + } + def parserFromMetaData(dataType: Int): String = { + dataType match { + case Types.CHAR => "string" + case Types.SMALLINT => "short" + case Types.INTEGER => "int" + case Types.BIGINT => "long" + case Types.FLOAT => "float" + case Types.DOUBLE => "double" + case Types.BOOLEAN => "boolean" + case Types.TINYINT => "byte" + case Types.CHAR => "char" + case Types.TIMESTAMP => "timestamp" + case _ => throw new UJESSQLException(UJESSQLErrorCode.PREPARESTATEMENT_TYPEERROR) + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala new file mode 100644 index 0000000000..792d55c045 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.hook + +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} + +import scala.collection.mutable.ArrayBuffer + +trait JDBCDriverPreExecutionHook { + + def callPreExecutionHook(sql: String): String + +} + +object JDBCDriverPreExecutionHook extends Logging{ + + private val preExecutionHooks:Array[JDBCDriverPreExecutionHook] = { + val hooks = new ArrayBuffer[JDBCDriverPreExecutionHook]() + CommonVars("wds.linkis.jdbc.pre.hook.class", "com.webank.wedatasphere.linkis.ujes.jdbc.hook.impl.TableauPreExecutionHook").getValue.split(",") foreach { + hookStr => Utils.tryCatch{ + val clazz = Class.forName(hookStr.trim) + val obj = clazz.newInstance() + obj match { + case hook:JDBCDriverPreExecutionHook => hooks += hook + case _ => warn(s"obj is not a engineHook obj is ${obj.getClass}") + } + }{ + case e:Exception => error(s"failed to load class ${hookStr}", e) + } + } + hooks.toArray + } + + def getPreExecutionHooks = preExecutionHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala new file mode 100644 index 0000000000..ff5d9e4a0d --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.hook.impl + +import com.webank.wedatasphere.linkis.ujes.jdbc.hook.JDBCDriverPreExecutionHook + +class TableauPreExecutionHook extends JDBCDriverPreExecutionHook{ + override def callPreExecutionHook(sql: String): String = { + if (sql.contains("LOCAL TEMPORARY")){ + sql.replace("LOCAL TEMPORARY", "").replace("ON COMMIT PRESERVE ROWS", "") + } else if (sql.contains("GROUP BY 2")){ + sql.replace("GROUP BY 2","") + } else if (sql.contains("`#")) { + sql.replace("`#", "`") + } else if (sql.startsWith("INSERT")) { + sql.replace("(COL)", "").replaceAll("VALUES (.*)", "VALUES (1)") + } else if (sql.contains("CREATE INDEX")) { + "select 1" + } else{ + sql.replace("TOP", "").replace("CHECKTOP","") + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java new file mode 100644 index 0000000000..cba8812fa8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +/* + * Notice: + * if you want to test this module,you must rewrite default parameters and SQL we used for local test + * */ + +import java.sql.DriverManager; +import java.sql.SQLException; + +public class CreateConnection { + + private static UJESSQLConnection conn; + + public static UJESSQLConnection getConnection() throws ClassNotFoundException, SQLException { + Class.forName("com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver"); + conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://hostname:port","username","password"); + return conn; + } +} + diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java new file mode 100644 index 0000000000..9266cad771 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import org.junit.Assert; +import org.junit.Test; + +import java.sql.DriverManager; +import java.sql.SQLException; + +/* + * Notice: + * if you want to test this module,you must rewrite default parameters and SQL we used for local test + * */ + +public class JDBCSpiTest { + private static UJESSQLConnection conn; + public static UJESSQLConnection getConnection() throws ClassNotFoundException, SQLException { + Class.forName("com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver"); + conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://127.0.0.1:9001", "shanhuang", "Abcd1234@"); + return conn; + } + @Test + public void spiTest(){ + try { + UJESSQLConnection conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://hostname:port","username","password"); + Assert.assertNotNull(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java similarity index 86% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java index 1b712ed938..11c30b285f 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java @@ -1,8 +1,21 @@ -package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by owenxu on 2019/8/23. +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ +package com.webank.wedatasphere.linkis.ujes.jdbc; + /* * Notice: * if you want to test this module,you must rewrite default parameters and SQL we used for local test diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java similarity index 78% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java index 8f7ce56f4a..0046a5db8d 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java @@ -1,14 +1,30 @@ -package com.webank.wedatasphere.linkis.ujes.jdbc; - -/** - * Created by leebai on 2019/8/23. +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ +package com.webank.wedatasphere.linkis.ujes.jdbc; + /* * Notice: * if you want to test this module,you must rewrite default SQL we used for local test * */ -import org.junit.*; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; import java.sql.SQLException; @@ -66,7 +82,7 @@ public void execute() { @Test public void selectTest(){ - preStatement = conn.prepareStatement("select * from bdp_test"); + preStatement = conn.prepareStatement("select * from shanhuang_ind.testjohn1 limit 10"); UJESSQLResultSet resultSet = preStatement.executeQuery(); showResult(resultSet); Assert.assertTrue(resultSet.isAfterLast()); diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java similarity index 82% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java index 573156c35e..9a93fe73b7 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java @@ -1,8 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by leebai on 2019/8/23. - */ import org.junit.*; import java.sql.SQLException; diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java similarity index 84% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java index e7c21ee277..801ee11ac4 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java @@ -1,8 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by owenxu on 2019/8/23. - */ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd new file mode 100644 index 0000000000..ef1f01a1bd --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js new file mode 100644 index 0000000000..218f5759b8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js @@ -0,0 +1,5 @@ +(function dsbuilder(attr) { + var urlBuilder = "jdbc:linkis://" + attr[connectionHelper.attributeServer] + ":" + attr[connectionHelper.attributePort] + "/" + attr[connectionHelper.attributeDatabase]; + + return [urlBuilder]; +}) diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js new file mode 100644 index 0000000000..14949bfec1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js @@ -0,0 +1,12 @@ +(function propertiesbuilder(attr) { + var props = {}; + props["user"] = attr[connectionHelper.attributeUsername]; + props["password"] = attr[connectionHelper.attributePassword]; + + if (attr[connectionHelper.attributeSSLMode] == "require") { + props["ssl"] = "true"; + props["sslmode"] = "require"; + } + + return props; +}) diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr new file mode 100644 index 0000000000..bc17b3ef52 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr @@ -0,0 +1,24 @@ + + + + + + + + + + + server + port + dbname + username + password + sslmode + + + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd new file mode 100644 index 0000000000..c6b6c714e8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd @@ -0,0 +1,1205 @@ + + + + ABS(%1) + + + + ABS(%1) + + + + ACOS(%1) + + + + ASIN(%1) + + + + ATAN(%1) + + + + CEILING(%1) + + + + COS(%1) + + + + IF(%1 != 0, COS(%1)/SIN(%1), NULL) + + + + DEGREES(%1) + + + + CASE WHEN %2 = 0 THEN NULL ELSE ( %1 / %2 ) END + + + + + EXP(%1) + + + + FLOOR(%1) + + + + (((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN 1.5 ELSE 0.0 END) - (CASE WHEN ((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0) < 0.0) AND ((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN 1.5 ELSE 0.0 END) > 0.0) THEN 3.0 ELSE 0.0 END)) + (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0)) + + + + + ROUND(((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN SQRT(3.0) / 2.0 ELSE 0.0 END) - (CASE WHEN ((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)) < 0.0) AND ((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN SQRT(3.0) / 2.0 ELSE 0.0 END) > 0.0) THEN SQRT(3.0) ELSE 0.0 END)) + (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)),3) + + + + + (CASE WHEN %1 > 0 THEN LN(%1) ELSE CAST(NULL AS DOUBLE) END) + + + + (CASE WHEN %1 > 0 THEN LOG10(%1) ELSE CAST(NULL AS DOUBLE) END) + + + + (CASE WHEN %1 > 0 THEN LOG10(%1) / LOG10(%2) ELSE NULL END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + PI() + + + (CASE WHEN %1 < 0 AND FLOOR(%2) <> %2 THEN NULL ELSE POW(%1,%2) END) + + + + + POW(%1,%2) + + + + + POW(CAST(%1 AS DOUBLE),%2) + + + + + RADIANS(%1) + + + + ROUND(%1) + + + + ROUND(%1,CAST(%2 AS BIGINT)) + + + + + ROUND(%1,%2) + + + + + SIGN(%1) + + + + SIN(%1) + + + + (CASE WHEN %1 < 0 THEN CAST(NULL AS DOUBLE) ELSE SQRT(%1) END) + + + + POW(%1,2) + + + + (SIN(%1)/COS(%1)) + + + + XPATH_DOUBLE(%1,%2) + + + + + XPATH_FLOAT(%1,%2) + + + + + XPATH_INT(%1,%2) + + + + + XPATH_LONG(%1,%2) + + + + + XPATH_SHORT(%1,%2) + + + + + COALESCE(CAST(%1 AS DOUBLE), 0.0) + + + + COALESCE(CAST(%1 AS BIGINT), CAST(0 AS BIGINT)) + + + + ASCII(%1) + + + + %1 RLIKE CONCAT('.*', %2, '.*') + + + + + (CASE WHEN ((CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) IS NULL) OR (LENGTH(%2) IS NULL) THEN NULL WHEN LENGTH(%2) < 1 THEN '' WHEN (CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) < 1 THEN SUBSTRING(RTRIM(%1),CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) ELSE SUBSTRING(RTRIM(%1),CAST((CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) AS INT),CAST(LENGTH(%2) AS INT)) END) = %2 + + + + + INSTR( %1, %2 ) + + + + + (CASE WHEN (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN INSTR( %1, %2 ) WHEN 0 = INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) THEN 0 ELSE INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) + CAST(%3 AS BIGINT) - 1 END) + + + + + + (CASE WHEN (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN INSTR( %1, %2 ) WHEN 0 = INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) THEN 0 ELSE INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) + %3 - 1 END) + + + + + + GET_JSON_OBJECT(%1,%2) + + + + + CASE WHEN %2 >= 0 THEN SUBSTRING(%1,1,CAST(CAST(%2 AS BIGINT) AS INT)) ELSE NULL END + + + + + CASE WHEN %2 >= 0 THEN SUBSTRING(%1,1,CAST(%2 AS INT)) ELSE NULL END + + + + + LENGTH(%1) + + + + LOWER(%1) + + + + LTRIM(%1) + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%2 IS NULL) OR %2 < 1 THEN NULL ELSE SUBSTRING(%1,CAST(CAST(%2 AS BIGINT) AS INT),CAST(LENGTH(%1) - (CAST(%2 AS BIGINT)) + 1 AS INT)) END) + + + + + (CASE WHEN (%2 IS NULL) OR %2 < 1 THEN NULL ELSE SUBSTRING(%1,CAST(%2 AS INT),CAST(LENGTH(%1) - (%2) + 1 AS INT)) END) + + + + + (CASE WHEN (%2 IS NULL) OR (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN '' WHEN %2 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(CAST(%3 AS BIGINT) AS INT)) ELSE SUBSTRING(%1,CAST(CAST(%2 AS BIGINT) AS INT),CAST(CAST(%3 AS BIGINT) AS INT)) END) + + + + + + (CASE WHEN (%2 IS NULL) OR (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN '' WHEN %2 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(%3 AS INT)) ELSE SUBSTRING(%1,CAST(%2 AS INT),CAST(%3 AS INT)) END) + + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + PARSE_URL(%1,%2) + + + + + PARSE_URL(%1,'QUERY',%2) + + + + + REGEXP_EXTRACT(%1,%2,1) + + + + + REGEXP_EXTRACT(%1,%2,%3) + + + + + + REGEXP_REPLACE(%1,%2,%3) + + + + + + REGEXP_REPLACE(%1,%2,%3) + + + + + + (CASE WHEN %2 >= 0 THEN IF(LENGTH(%1) < %2 + 1, %1, SUBSTRING(%1, LENGTH(%1) - CAST(%2 AS INT) + 1)) ELSE NULL END) + + + + + (CASE WHEN %2 >= 0 THEN IF(LENGTH(%1) < %2 + 1, %1, SUBSTRING(%1, LENGTH(%1) - CAST(%2 AS INT) + 1)) ELSE NULL END) + + + + + RTRIM(%1) + + + + (CASE WHEN CAST(%1 AS BIGINT) >= 0 THEN SPACE(CAST(CAST(%1 AS BIGINT) AS INT)) ELSE CAST(NULL AS STRING) END) + + + + (CASE WHEN %1 >= 0 THEN SPACE(CAST(%1 AS INT)) ELSE CAST(NULL AS STRING) END) + + + + SPLIT(%1,%2)[%3] + + + + + + (CASE WHEN (1 IS NULL) OR (LENGTH(%2) IS NULL) THEN NULL WHEN LENGTH(%2) < 1 THEN '' WHEN 1 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) ELSE SUBSTRING(%1,CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) END) = %2 + + + + + TRIM(%1) + + + + UPPER(%1) + + + + XPATH_STRING(%1,%2) + + + + + %1 + + + + %1 + + + + CAST (TO_DATE(%1) AS DATE) + + + + CAST (%1 AS DATE) + + + + CAST (%1 AS DATE) + + + + %1 + + + + CAST(%1 AS TIMESTAMP) + + + + %1 + + + + CAST(%1 AS TIMESTAMP) + + + + (CASE WHEN %1 THEN 1.0 WHEN NOT %1 THEN 0.0 ELSE NULL END) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(UNIX_TIMESTAMP(%1) AS DOUBLE) + + + + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END) + + + + CAST(%1 AS BIGINT) + + + + CAST(%1 AS BIGINT) + + + + CAST(CAST(%1 AS DOUBLE) AS BIGINT) + + + + CAST(%1 AS BIGINT) + + + + CAST(UNIX_TIMESTAMP(%1) AS INT) + + + + (CASE WHEN %1 THEN '1' WHEN NOT %1 THEN '0' ELSE NULL END) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE (CASE WHEN %2 THEN 1 WHEN NOT %2 THEN 0 ELSE NULL END) END)=1 + + + + + COALESCE(CAST(%1 AS DOUBLE), CAST(%2 AS DOUBLE)) + + + + + COALESCE(CAST(%1 AS BIGINT), CAST(%2 AS BIGINT)) + + + + + COALESCE(%1, %2) + + + + + COALESCE(%1, %2) + + + + + COALESCE(%1, %2) + + + + + ((%1 AND %2) OR ((NOT %1) AND %3)) + + + + + + (CASE WHEN %1 THEN CAST(%2 AS DOUBLE) WHEN NOT %1 THEN CAST(%3 AS DOUBLE) ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + XPATH_BOOLEAN(%1,%2) + + + + + AVG(%1) + %1 + + + + AVG(CAST(%1 AS DOUBLE)) + %1 + + + + CORR(%1, %2) + CAST(NULL AS DOUBLE) + + + + + COUNT(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END) + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 1 ELSE 0 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)) + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 1 ELSE 0 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COVAR_SAMP(%1, %2) + CAST(NULL AS DOUBLE) + + + + + COVAR_POP(%1, %2) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) WHEN %2 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END + + + + + (MAX(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)=1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + percentile_approx(%1, 0.5) + %1 + + + + (MIN(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)=1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + PERCENTILE_APPROX(%1, %2) + %1 + + + + + PERCENTILE(%1, %2) + %1 + + + + + (CASE WHEN COUNT(%1) > 1 THEN STDDEV_SAMP(%1) ELSE NULL END) + CAST(NULL AS DOUBLE) + + + + STDDEV_POP(%1) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END) + + + + SUM(%1) + %1 + + + + SUM(%1) + %1 + + + + (CASE WHEN COUNT(%1) > 1 THEN VAR_SAMP(%1) ELSE NULL END) + CAST(NULL AS DOUBLE) + + + + VAR_POP(%1) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END) + + + + (NOT %1) + + + + (%1 AND NOT %2 OR NOT %1 AND %2) + + + + + (%1 <> %2) + + + + + (%1 <> %2) + + + + + (%1 <> %2) + + + + + (%1 <> CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) <> %2) + + + + + (%1 <> %2) + + + + + PMOD(%1, %2) + + + + + PMOD(%1, %2) + + + + + (%1 AND %2) + + + + + (%1 * %2) + + + + + (%1 * %2) + + + + + (%1 + %2) + + + + + (%1 + %2) + + + + + CONCAT(%1,%2) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(%1 AS BIGINT) + (%2 * 86400) AS BIGINT)) AS TIMESTAMP) + + + + + CAST(CONCAT(DATE_ADD(%1, CAST(%2 AS INT)), SUBSTR(CAST(%1 AS TIMESTAMP), 11)) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(CAST(%1 AS TIMESTAMP) AS BIGINT) + (%2 * 86400) AS BIGINT)) AS TIMESTAMP) + + + + + CAST(DATE_ADD(%1, CAST(%2 AS INT)) AS DATE) + + + + + (-%1) + + + + (%1 - %2) + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (-%1) + + + + (%1 - %2) + + + + + CAST(FROM_UNIXTIME(CAST(%1 AS BIGINT) - CAST((%2) * 86400 AS INT)) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(%1 AS BIGINT) - (%2) * 86400) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(%1 AS TIMESTAMP) AS BIGINT) - CAST((%2) * 86400 AS INT)) AS TIMESTAMP) + + + + + CAST(DATE_ADD(%1, CAST(-(%2) AS INT)) AS DATE) + + + + + (CASE WHEN %2 = 0 THEN NULL ELSE %1 / %2 END) + + + + + (CASE WHEN %2 = 0 THEN NULL ELSE CAST(%1 AS DOUBLE) / %2 END) + + + + + (%1 < %2) + + + + + (%1 < %2) + + + + + (%1 < %2) + + + + + (%1 < CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) < %2) + + + + + (%1 < %2) + + + + + (%1 <= %2) + + + + + (%1 <= %2) + + + + + (%1 <= %2) + + + + + (%1 <= CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) <= %2) + + + + + (%1 <= %2) + + + + + (%1 AND %2 OR NOT %1 AND NOT %2) + + + + + (%1 = %2) + + + + + (%1 = %2) + + + + + (%1 = %2) + + + + + (%1 = CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) = %2) + + + + + (%1 = %2) + + + + + (%1 > %2) + + + + + (%1 > %2) + + + + + (%1 > %2) + + + + + (%1 > CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) > %2) + + + + + (%1 > %2) + + + + + (%1 >= %2) + + + + + (%1 >= %2) + + + + + (%1 >= %2) + + + + + (%1 >= CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) >= %2) + + + + + (%1 >= %2) + + + + + (CASE WHEN %1 < 0 AND FLOOR(%2) <> %2 THEN NULL ELSE POW(%1,%2) END) + + + + + POW(%1,%2) + + + + + POW(CAST(%1 AS DOUBLE),%2) + + + + + (%1 OR %2) + + + + + DAY(%1) + + + + DAY(%1) + + + + MONTH(%1) + + + + MONTH(%1) + + + + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP()) AS TIMESTAMP) + + + CAST((MONTH(%1) - 1) / 3 + 1 AS BIGINT) + + + + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd 00:00:00') AS TIMESTAMP) + + + FLOOR((14 + DATEDIFF(%1, TRUNC(%1,'YY')) + DATEDIFF(TRUNC(%1,'YY'),NEXT_DAY(TRUNC(%1,'YY'),'SU')))/7) + + + + YEAR(%1) + + + + YEAR(%1) + + + + CAST(CONCAT(YEAR(%3)+%2, SUBSTR(CAST(%3 AS TIMESTAMP), 5)) AS TIMESTAMP) + CAST(CONCAT(ADD_MONTHS(%3,(%2 * 3)),SUBSTR(CAST(%3 AS TIMESTAMP),11)) AS TIMESTAMP) + CAST(CONCAT(ADD_MONTHS(%3,%2),SUBSTR(CAST(%3 AS TIMESTAMP),11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(7 * %2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2*3600) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2*60) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2) AS TIMESTAMP) + + + + + + + FLOOR(DATEDIFF(NEXT_DAY(%2,'SU'),NEXT_DAY(%1,'SU'))/7) + + + + + + + CAST(YEAR(%2) AS STRING) + CAST(CAST((MONTH(%2) - 1) / 3 + 1 AS BIGINT) AS STRING) + CAST(MONTH(%2) AS STRING) + CAST(DATEDIFF(TO_DATE(%2), TO_DATE(CAST(TRUNC(%2,'YY') AS DATE))) + 1 AS STRING) + CAST(DAY(%2) AS STRING) + CAST((8 + DATEDIFF(CAST(%2 AS DATE),NEXT_DAY(%2,'SU'))) AS STRING) + FORMAT_NUMBER(FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7),0) + CAST(HOUR(%2) AS STRING) + COALESCE(CAST(MINUTE(%2) AS STRING), '') + COALESCE(CAST(SECOND(%2) AS STRING), '') + + + + + FORMAT_NUMBER(FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7),0) + + + + + + YEAR(%2) + CAST((MONTH(%2) - 1) / 3 + 1 AS BIGINT) + MONTH(%2) + DATEDIFF(TO_DATE(%2), TO_DATE(CAST(TRUNC(%2,'YY') AS DATE))) + 1 + DAY(%2) + (8 + DATEDIFF(%2,NEXT_DAY(CAST(%2 AS DATE),'SU'))) + FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7) + HOUR(%2) + MINUTE(%2) + SECOND(%2) + + + + + FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7) + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml new file mode 100644 index 0000000000..b4d6fe2973 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt new file mode 100644 index 0000000000..afaf360d37 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-manager/label-common/pom.xml b/linkis-computation-governance/linkis-manager/label-common/pom.xml new file mode 100644 index 0000000000..e6e0c609d5 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/pom.xml @@ -0,0 +1,88 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-label-common + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + + org.reflections + reflections + ${reflections.version} + + + com.google.code.gson + gson + + + com.google.guava + guava + + + + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java new file mode 100644 index 0000000000..7d7d1e3786 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java @@ -0,0 +1,343 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.webank.wedatasphere.linkis.manager.label.entity.CloneableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.InheritableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.*; +import java.util.function.Function; + +import static com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils.Jackson.*; + +@SuppressWarnings("rawtypes") +public abstract class AbstractGenericLabelBuilder implements ExtensibleLabelBuilder { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractGenericLabelBuilder.class); + + /** + * Transform value object + * @param rawValue value + * @param parameterTypes parameters + * @param Any + * @return result + */ + @SuppressWarnings("unchecked") + protected V transformValueToConcreteType(Object rawValue, Type concreteType, Type[] parameterTypes, Function deserializer){ + if(null != rawValue){ + try { + Class> sourceClass = rawValue.getClass(); + Class> concreteClass = (Class>)concreteType; + if (concreteClass.isAssignableFrom(sourceClass)) { + if (CloneableLabel.class.isAssignableFrom(sourceClass)) { + //Just clone label + return (V) ((CloneableLabel) rawValue).clone(); + } + } else if (LabelUtils.isBasicType(concreteClass)) { + //Serialize the raw value first + return (V) convert(toJson(rawValue, null), concreteClass); + } else if (LabelUtils.isBasicType(rawValue.getClass())) { + String rawString = String.valueOf(rawValue); + if(null != deserializer){ + return deserializer.apply(rawString); + } + JavaType javaType = getJavaType(concreteType, parameterTypes); + if (concreteClass.equals(Map.class)) { + try { + return (V) convert(fromJson(rawString, Map.class, Object.class, Object.class), javaType); + } catch (Exception e) { + LOG.trace("Transform raw value fail, return empty object", e); + return fromJson("{}", javaType); + } + }else if (concreteClass.equals(List.class)) { + try { + return (V) convert(fromJson(rawString, List.class, Object.class), javaType); + } catch (Exception e) { + //Ignore + LOG.trace("Transform raw value fail, return empty list", e); + return fromJson("[]", javaType); + } + } + + } + //Try to convert value directly + return (V) LabelUtils.Jackson.convert(rawValue, getJavaType(concreteType, parameterTypes)); + }catch(Exception e){ + //Ignore + LOG.trace("Transform raw value fail, return null", e); + } + } + return null; + } + + + /** + * Find label's value class + * @param labelClass label class provided + * @return class array + */ + public Class>[] findActualLabelValueClass(Class extends Label> labelClass){ + Map, Type[]> classTypeVariableMap = new HashMap<>(); + Type[] classTypes = recurseToFindActualLabelValueType(labelClass, classTypeVariableMap); + if(null != classTypes) { + //Transform to class object + List> classesReturn = new ArrayList<>(); + //Expand combine types + classTypes = expandParameterizedType(classTypes); + for (Type classType : classTypes) { + if (classType instanceof Class) { + classesReturn.add((Class>) classType); + } else if (classType instanceof WildcardType) { + classesReturn.add(Object.class); + } + } + return classesReturn.toArray(new Class>[0]); + } + return null; + } + + /** + * Find label's value type + * @param labelType label class provided + * @return type array + */ + public Type[] findActualLabelValueType(Class extends Label> labelType){ + Map, Type[]> classTypeVariableMap = new HashMap<>(); + return recurseToFindActualLabelValueType(labelType, classTypeVariableMap); + } + /** + * Recurse to find label's value type + * @param labelClass label class + * @param classTypeVariableMap use to store the mapping relation between class and type + * @return value type array + */ + private Type[] recurseToFindActualLabelValueType(Class extends Label> labelClass, Map, Type[]> classTypeVariableMap){ + if(null == labelClass){ + return null; + } + //Store the reflect relation between parameter variable like 'T' and type like 'java.lang.String' + Map typeVariableReflect = new HashMap<>(); + Type[] typeParameters = labelClass.getTypeParameters(); + if(typeParameters.length > 0){ + Type[] classTypes = classTypeVariableMap.get(labelClass); + if(null == classTypes){ + return null; + } + for(int i = 0; i < classTypes.length; i ++ ){ + typeVariableReflect.put(typeParameters[i].getTypeName(), classTypes[i]); + } + } + if(labelClass.equals(Label.class) || labelClass.equals(InheritableLabel.class)){ + return classTypeVariableMap.get(labelClass); + } + // Search from interfaces to super class + Type[] valueTypes = findValueTypeFromInterface(labelClass, classTypeVariableMap, typeVariableReflect); + if(null == valueTypes){ + valueTypes = findValueTypeFromSuperclass(labelClass, classTypeVariableMap, typeVariableReflect); + } + return valueTypes; + } + + /** + * Find label's value type from interfaces + * @param labelClass label class + * @param classTypeVariableMap stored the mapping relation between class and type + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return value type array + */ + @SuppressWarnings("unchecked") + private Type[] findValueTypeFromInterface(Class extends Label> labelClass, + Map, Type[]> classTypeVariableMap, Map typeVariableReflect){ + Class>[] interfaces = labelClass.getInterfaces(); + if(interfaces.length > 0){ + for(int i = 0; i < interfaces.length; i ++){ + Class> interfaceClass = interfaces[i]; + if(Label.class.isAssignableFrom(interfaceClass)){ + //As the jdk doc, getInterfaces() and getGenericInterfaces() method has the same order + Type interfaceType = labelClass.getGenericInterfaces()[i]; + //If the interface type has type arguments, transform and store into 'classTypeVariableMap' + if(interfaceType instanceof ParameterizedType){ + Type[] actualTypes = ((ParameterizedType)interfaceType).getActualTypeArguments(); + actualTypes = transformParameterizedType(actualTypes, typeVariableReflect); + classTypeVariableMap.put(interfaceClass, actualTypes); + } + return recurseToFindActualLabelValueType((Class extends Label>)interfaceClass, classTypeVariableMap); + } + } + + } + return null; + } + + /** + * Find label's value type from super class + * @param label label class + * @param classTypeVariableMap stored the mapping relation between class and type + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return value type array + */ + @SuppressWarnings("unchecked") + private Type[] findValueTypeFromSuperclass(Class extends Label> label, + Map, Type[]> classTypeVariableMap, Map typeVariableReflect){ + Type superclassType = label.getGenericSuperclass(); + if(superclassType instanceof ParameterizedType){ + Type[] actualTypes = ((ParameterizedType)superclassType).getActualTypeArguments(); + actualTypes = transformParameterizedType(actualTypes, typeVariableReflect); + classTypeVariableMap.put(label.getSuperclass(), actualTypes); + } + return recurseToFindActualLabelValueType((Class extends Label>)label.getSuperclass(), classTypeVariableMap); + } + + /** + * Do transform + * @param rawTypes raw types + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return result + */ + private Type[] transformParameterizedType(Type[] rawTypes, Map typeVariableReflect){ + return resolveParameterizedType(rawTypes, (rawType)->{ + if(rawType instanceof TypeVariable){ + return typeVariableReflect.getOrDefault(rawType.getTypeName(), rawType); + } + return rawType; + }); + } + + /** + * Resolve parameterized type (parameterized type -> combined type) + * @param rawTypes unresolved types + * @param resolveFunc resolve function + * @return resolved types + */ + private Type[] resolveParameterizedType(Type[] rawTypes, Function resolveFunc){ + Queue queue = new LinkedList<>(); + List resolvedTypes = new ArrayList<>(); + CombineType combineType = null; + for(Type rawType : rawTypes){ + queue.add(rawType); + while(!queue.isEmpty()){ + Type typeInQueue = queue.poll(); + //Change the combineType used currently + if(typeInQueue instanceof CombineType){ + combineType = (CombineType)typeInQueue; + continue; + } + if(typeInQueue instanceof ParameterizedType){ + //Construct a new combine type and add to queue + CombineType newCombineType = new CombineType(((ParameterizedType) typeInQueue).getRawType()); + queue.add(newCombineType); + Type[] actualTypes = ((ParameterizedType) typeInQueue).getActualTypeArguments(); + //Add the type arguments to queue + queue.addAll(Arrays.asList(actualTypes)); + //Add the combineType exist to the queue + if(null != combineType){ + combineType.childTypes.add(newCombineType); + queue.add(combineType); + }else{ + resolvedTypes.add(newCombineType); + } + }else if (null != combineType){ + combineType.childTypes.add(resolveFunc.apply(typeInQueue)); + }else{ + resolvedTypes.add(resolveFunc.apply(typeInQueue)); + } + } + combineType = null; + } + return resolvedTypes.toArray(new Type[0]); + } + + /** + * Expand combined types to array + * @param resolvedTypes combined types + * @return types + */ + private Type[] expandParameterizedType(Type[] resolvedTypes){ + Queue queue = new LinkedList<>(); + List expandTypes = new ArrayList<>(); + for(Type expandType : resolvedTypes){ + queue.add(expandType); + while(!queue.isEmpty()){ + Type typeInQueue = queue.poll(); + if(typeInQueue instanceof CombineType){ + CombineType combineType = (CombineType)typeInQueue; + expandTypes.add(combineType.actual); + queue.addAll(combineType.childTypes); + }else{ + expandTypes.add(typeInQueue); + } + } + } + return expandTypes.toArray(new Type[0]); + } + + /** + * Transform to Jackson's JavaType + * @param concreteType concrete type + * @param parameterTypes parameter type + * @return + */ + private JavaType getJavaType(Type concreteType, Type... parameterTypes){ + List javaTypes = new ArrayList<>(); + for (Type parameterType : parameterTypes) { + if (parameterType instanceof CombineType) { + CombineType combineType = (CombineType) parameterType; + javaTypes.add(getJavaType(combineType.actual, combineType.childTypes.toArray(new Type[0]))); + } else { + javaTypes.add(getJavaType(parameterType)); + } + } + if(javaTypes.size() > 0){ + Class> rawClass = Object.class; + if (concreteType instanceof Class) { + rawClass = (Class>) concreteType; + } + return TypeFactory.defaultInstance().constructParametricType(rawClass, javaTypes.toArray(new JavaType[0])); + } + return TypeFactory.defaultInstance().constructType(concreteType); + } + + /** + * Combine different type object + */ + protected static class CombineType implements Type{ + + /** + * Actual type + */ + protected Type actual; + + /** + * Children types + */ + protected List childTypes = new ArrayList<>(); + + CombineType(Type actual){ + this.actual = actual; + } + } +} diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java new file mode 100644 index 0000000000..1d16c8e116 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.webank.wedatasphere.linkis.manager.label.constant.LabelConstant; +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant; +import com.webank.wedatasphere.linkis.manager.label.entity.CombinedLabelImpl; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.exception.LabelErrorException; + +import javax.annotation.Nullable; +import java.util.List; + +public class CombinedLabelBuilder implements LabelBuilder { + + + @Override + public boolean canBuild(String labelKey) { + if (labelKey.startsWith(LabelKeyConstant.COMBINED_LABEL_KEY_PREFIX)) { + return true; + } + return false; + } + + @Override + public Label> build(String labelKey, @Nullable Object valueObj) throws LabelErrorException { + if (null != valueObj || valueObj instanceof List) { + try { + List> labels = (List>) valueObj; + return new CombinedLabelImpl(labels); + } catch (Throwable e) { + throw new LabelErrorException(LabelConstant.LABEL_BUILDER_ERROR_CODE, "Failed to build combinedLabel", e); + } + } + return null; + } +} diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java new file mode 100644 index 0000000000..02eff9ff94 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java @@ -0,0 +1,253 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.webank.wedatasphere.linkis.manager.label.conf.LabelCommonConfig; +import com.webank.wedatasphere.linkis.manager.label.constant.LabelConstant; +import com.webank.wedatasphere.linkis.manager.label.entity.InheritableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.entity.SerializableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.annon.KeyMethod; +import com.webank.wedatasphere.linkis.manager.label.exception.LabelErrorException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.reflections.Reflections; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.*; +import java.util.function.Function; + +/** + * To build different types of label + */ +@SuppressWarnings(value= {"unchecked", "rawtypes"}) +public class DefaultGlobalLabelBuilder extends AbstractGenericLabelBuilder{ + + private static final Logger LOG = LoggerFactory.getLogger(DefaultGlobalLabelBuilder.class); + + private static final Reflections LABEL_ENTITY_REFLECTS; + + private static final Function DEFAULT_STRING_DESERIALIZER = stringValue -> stringValue; + + private static final Map>> LABEL_KEY_TYPE_MAP = new HashMap<>(); + + static{ + List packagesPath = new ArrayList<>(); + packagesPath.add(Label.class.getPackage().getName()); + String definedEntityPackages = LabelCommonConfig.LABEL_ENTITY_PACKAGES.getValue(); + if(StringUtils.isNotBlank(definedEntityPackages)){ + packagesPath.addAll(Arrays.asList(definedEntityPackages.split(","))); + } + LABEL_ENTITY_REFLECTS = new Reflections(packagesPath.toArray()); + //Lazy load all label keys of label entities + //Scan methods in Label to find annotation @LabelKey + Method[] methods = Label.class.getMethods(); + Method getKeyMethod = null; + for(Method method : methods){ + if(method.isAnnotationPresent(KeyMethod.class)){ + getKeyMethod = method; + } + } + if(null != getKeyMethod) { + @SuppressWarnings("rawtypes") + Set> labelEntities = LABEL_ENTITY_REFLECTS.getSubTypesOf(Label.class); + Method finalGetKeyMethod = getKeyMethod; + labelEntities.forEach((labelEntity) -> { + //New instance and then invoke get_key method + if(!Modifier.isInterface(labelEntity.getModifiers()) && + !Modifier.isAbstract(labelEntity.getModifiers())) { + try { + Label> label = labelEntity.newInstance(); + String labelKey = (String) finalGetKeyMethod.invoke(label); + if (StringUtils.isNotBlank(labelKey)) { + LABEL_KEY_TYPE_MAP.put(labelKey, (Class extends Label>>) labelEntity); + } + } catch (InstantiationException | IllegalAccessException e) { + LOG.info("Fail to reflect to new a label instance: [" + labelEntity.getSimpleName() + "]", e); + } catch (InvocationTargetException e) { + LOG.info("Fail to invoke method: [" + finalGetKeyMethod.getName() + + "] of label instance: [" + labelEntity.getSimpleName() + "]", e); + } + } + }); + } + } + + @Override + public boolean canBuild(String labelKey, Class> labelClass) { + //Support all sub classes/interfaces of Label + return null == labelClass || Label.class.isAssignableFrom(labelClass); + } + + @Override + public > T build(String labelKey, Object valueObj, Class> labelClass, Type... valueTypes) throws LabelErrorException { + Class extends Label> suitableLabelClass = getSuitableLabelClass(labelKey, labelClass); + if(null != suitableLabelClass){ + Type suitableValueType = getSuitableValueType(suitableLabelClass, valueTypes); + if(null != suitableValueType){ + return buildInner(labelKey, valueObj, suitableLabelClass, suitableValueType); + } + } + return null; + } + + + @Override + public > T build(String labelKey, Object valueObj, Class labelType) throws LabelErrorException { + return build(labelKey, valueObj, (Class>)labelType); + } + + @Override + public
+ */ +public class EngineConnExecutorErrorCode { + + public static final int INVALID_ENGINE_TYPE = 40100; + + public static final int INVALID_METHOD = 40101; + + public static final int INVALID_PARAMS = 40102; + + public static final int INVALID_LOCK = 40103; + + public static final int INVALID_TASK = 40104; + + public static final int SEND_TO_ENTRANCE_ERROR = 40105; + + public static final int INIT_EXECUTOR_FAILED = 40106; + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java new file mode 100644 index 0000000000..78a8a07cb8 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/exception/engineconn/EngineConnExecutorErrorException.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.exception.engineconn; + +import com.webank.wedatasphere.linkis.common.exception.ErrorException; + +public class EngineConnExecutorErrorException extends ErrorException { + + public EngineConnExecutorErrorException(int errCode, String desc) { + super(errCode, desc); + } + + public EngineConnExecutorErrorException(int errCode, String desc, String ip, int port, String serviceKind) { + super(errCode, desc, ip, port, serviceKind); + } + + public EngineConnExecutorErrorException(int errCode, String desc, Throwable e) { + this(errCode, desc); + initCause(e); + } + + +} diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala new file mode 100644 index 0000000000..f525297c02 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/RequestQueryGlobalConfig.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.conf + +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.protocol.{CacheableProtocol, RetryableProtocol} + +trait ConfigProtocol + +case class RequestQueryGlobalConfig(username: String) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestQueryEngineConfig(userCreatorLabel: UserCreatorLabel, engineTypeLabel: EngineTypeLabel, filter: String = null) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestQueryEngineTypeDefault(engineTypeLabel: EngineTypeLabel) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + +case class RequestConfigByLabel(labels: java.util.List[Label[_]], isMerge: Boolean = true) extends CacheableProtocol with RetryableProtocol with ConfigProtocol + + diff --git a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala similarity index 89% rename from core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala rename to linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala index 2b9129eb0d..50c6c3c8c5 100644 --- a/core/cloudProtocol/src/main/scala/com/webank/wedatasphere/linkis/protocol/config/ResponseQueryConfig.scala +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/conf/ResponseQueryConfig.scala @@ -14,13 +14,10 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.protocol.config +package com.webank.wedatasphere.linkis.governance.common.protocol.conf import java.util -/** - * Created by enjoyyin on 2018/10/17. - */ class ResponseQueryConfig extends ConfigProtocol { private var keyAndValue: util.Map[String, String] = _ def getKeyAndValue :util.Map[String, String] = keyAndValue diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala new file mode 100644 index 0000000000..8cdbfbc5bd --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/engineconn/RequestEngineStatus.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.engineconn + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.NodeExistStatus +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + +import java.util + +case class RequestEngineStatusBatch(engineList: util.List[ServiceInstance]) extends RequestProtocol + +case class ResponseEngineStatusBatch(engineStatus: util.Map[ServiceInstance, NodeExistStatus], msg: String) + diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala new file mode 100644 index 0000000000..6666d56474 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/RequestTask.scala @@ -0,0 +1,86 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import java.util + +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + +trait RequestTask { + def getCode: String + def setCode(code: String): Unit + def getLock: String + def setLock(lock: String): Unit + def getProperties: util.Map[String, Object] + def setProperties(properties: util.Map[String, Object]) + def data(key: String, value: Object): Unit + def getLabels: util.List[Label[_]] + def setLabels(labels: util.List[Label[_]]) +} +object RequestTask { + private val header = "#rt_" + val RESULT_SET_STORE_PATH = header + "rs_store_path" +} +class RequestTaskExecute extends RequestTask with RequestProtocol { + private var code: String = _ + private var lock: String = _ + private var properties: util.Map[String, Object] = new util.HashMap[String, Object] + + private var labels: util.List[Label[_]] = new util.ArrayList[Label[_]](4) + + override def getCode: String = code + + override def setCode(code: String): Unit = this.code = code + + override def getLock: String = lock + + override def setLock(lock: String): Unit = this.lock = lock + + override def getProperties: util.Map[String, Object] = properties + + override def setProperties(properties: util.Map[String, Object]): Unit = this.properties = properties + + override def data(key: String, value: Object): Unit = { + if(properties == null) properties = new util.HashMap[String, Object] + properties.put(key, value) + } + + + + override def getLabels: util.List[Label[_]] = labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels +} + +trait TaskState extends RequestProtocol {} + +case class RequestTaskPause(execId: String) extends TaskState +case class RequestTaskResume(execId: String) extends TaskState +case class RequestTaskKill(execId: String) extends TaskState + + +/** + * The status of requesting job execution, mainly used for: + * 1. If the engine has not sent information to the entity for a long time, the enumeration periodically requests status information + * 2. If the entance of the request engine is hanged, the newly taken entity first requests the status of the job from the engine, the engine maintains the new sender information, + * and then sends log information to the sender. + * 请求Job执行的状态,主要用于: + * 1. 如果engine很久没有给entrance发送信息,entrance定时请求一次状态信息 + * 2. 如果请求engine的entrance挂掉了,新接手的entrance第一次向engine请求Job的状态,engine维系新的sender信息,后续向该sender发送日志信息 + */ +case class RequestTaskStatus(execId: String) extends TaskState \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala new file mode 100644 index 0000000000..1fa8400949 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseEngineConnPid.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.protocol.RetryableProtocol +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol + + +/** + * + * @param pid + */ +case class ResponseEngineConnPid(serviceInstance: ServiceInstance, pid: String, ticketId: String) extends RetryableProtocol with RequestProtocol + + + diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala new file mode 100644 index 0000000000..248fb82d93 --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/protocol/task/ResponseTaskExecute.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.protocol.task + +import java.util + +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.protocol.{BroadcastProtocol, RetryableProtocol} + +case class ResponseTaskExecute(execId: String) + +case class ResponseTaskProgress(execId: String, progress: Float, progressInfo: Array[JobProgressInfo]) extends RetryableProtocol with RequestProtocol + +case class ResponseEngineLock(lock: String) + +case class EngineConcurrentInfo(runningTasks: Int, pendingTasks: Int, succeedTasks: Int, failedTasks: Int) +case class EngineOverloadInfo(maxMemory: Long, usedMemory: Long, systemCPUUsed: Float) + +case class ResponseEngineStatusChanged(instance: String, fromStatus: ExecutionNodeStatus, toStatus: ExecutionNodeStatus, + overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo) + extends BroadcastProtocol + +case class ResponseEngineInfo(createEntranceInstance: String, creator: String, user: String, properties: util.Map[String, String]) + +case class ResponseEngineStatus(instance: String, status: ExecutionNodeStatus, overload: EngineOverloadInfo, concurrent: EngineConcurrentInfo, + engineInfo: ResponseEngineInfo) + +case class ResponseTaskLog(execId: String, log: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskError(execId: String, errorMsg: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskStatus(execId: String, status: ExecutionNodeStatus) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskResultSet(execId: String, output: String, alias: String) extends RetryableProtocol with RequestProtocol + +case class ResponseTaskResultSize(execId: String, resultSize: Int) extends RetryableProtocol with RequestProtocol \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala new file mode 100644 index 0000000000..e54827aa1b --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/EngineConnArguments.scala @@ -0,0 +1,144 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.utils + +import org.apache.commons.lang.StringUtils + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + +trait EngineConnArguments { + + def getSpringConfMap: Map[String, String] + + def getEngineConnConfMap: Map[String, String] + +} + +trait EngineConnArgumentsBuilder { + + def addSpringConf(confMap: Map[String, String]): EngineConnArgumentsBuilder + + def addSpringConf(key: String, value: String): EngineConnArgumentsBuilder + + def addEngineConnConf(confMap: Map[String, String]): EngineConnArgumentsBuilder + + def addEngineConnConf(key: String, value: String): EngineConnArgumentsBuilder + + def build(): EngineConnArguments + +} + +object EngineConnArgumentsBuilder { + def newBuilder(): EngineConnArgumentsBuilder = new DefaultEngineConnArgumentsBuilder +} + +class DefaultEngineConnArgumentsBuilder extends EngineConnArgumentsBuilder { + + private val engineConnOptionMap = new mutable.HashMap[String, String]() + private val springOptionMap = new mutable.HashMap[String, String]() + + override def addSpringConf(confMap: Map[String, String]): EngineConnArgumentsBuilder = { + springOptionMap ++= confMap + this + } + + override def addSpringConf(key: String, value: String): EngineConnArgumentsBuilder = { + springOptionMap += key -> value + this + } + + override def addEngineConnConf(confMap: Map[String, String]): EngineConnArgumentsBuilder = { + engineConnOptionMap ++= confMap + this + } + + override def addEngineConnConf(key: String, value: String): EngineConnArgumentsBuilder = { + engineConnOptionMap += key -> value + this + } + + override def build(): EngineConnArguments = new EngineConnArguments { + override def getSpringConfMap: Map[String, String] = springOptionMap.toMap + override def getEngineConnConfMap: Map[String, String] = engineConnOptionMap.toMap + } +} + +trait EngineConnArgumentsParser { + + def parseToObj(args: Array[String]): EngineConnArguments + + def parseToArgs(engineConnArguments: EngineConnArguments): Array[String] + +} +object EngineConnArgumentsParser { + + val LABEL_PREFIX = "label." + + private val parser = new DefaultEngineConnArgumentsParser + + def getEngineConnArgumentsParser: EngineConnArgumentsParser = parser +} + +class DefaultEngineConnArgumentsParser extends EngineConnArgumentsParser { + + protected val ENGINE_CONN_CONF = "--engineconn-conf" + protected val SPRING_CONF = "--spring-conf" + + protected val keyValueRegex = "([^=]+)=(.+)".r + + override def parseToObj(args: Array[String]): EngineConnArguments = { + var i = 0 + val argumentsBuilder = new DefaultEngineConnArgumentsBuilder + while(i < args.length) { + args(i) match { + case ENGINE_CONN_CONF => + addKeyValue(args(i + 1), (key, value) => { + argumentsBuilder.addEngineConnConf(key, value) + i += 1 + }) + case SPRING_CONF => + addKeyValue(args(i + 1), (key, value) => { + argumentsBuilder.addSpringConf(key, value) + i += 1 + }) + case _ => throw new IllegalArgumentException(s"illegal command line, ${args(i)} cannot recognize.") + } + i += 1 + } + argumentsBuilder.build() + } + + private def addKeyValue(keyValue: String, argumentsBuilder: (String, String) => Unit): Unit = keyValue match { + case keyValueRegex(key, value) => + argumentsBuilder(key, value) + case _ => throw new IllegalArgumentException("illegal command line, format: --conf key=value.") + } + + override def parseToArgs(engineConnArguments: EngineConnArguments): Array[String] = { + val options = ArrayBuffer[String]() + def write(confMap: Map[String, String], optionType: String): Unit = confMap.foreach { case (key, value) => + if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) { + options += optionType + options += (key + "=" + value) + } + } + write(engineConnArguments.getEngineConnConfMap, ENGINE_CONN_CONF) + write(engineConnArguments.getSpringConfMap, SPRING_CONF) + options.toArray + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala new file mode 100644 index 0000000000..a64e6db06d --- /dev/null +++ b/linkis-computation-governance/linkis-computation-governance-common/src/main/scala/com/webank/wedatasphere/linkis/governance/common/utils/GovernanceConstant.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.governance.common.utils + +object GovernanceConstant { + + val TASK_SOURCE_MAP_KEY = "source" + + val TASK_RESOURCES_STR = "resources" + + val TASK_RESOURCE_ID_STR = "resourceId" + + val TASK_RESOURCE_VERSION_STR = "version" + + val TASK_RESOURCE_FILE_NAME_STR = "fileName" + + val REQUEST_ENGINE_STATUS_BATCH_LIMIT = 500 +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml new file mode 100644 index 0000000000..4a1411e937 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/pom.xml @@ -0,0 +1,70 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-linux-launch + + + + com.webank.wedatasphere.linkis + linkis-engineconn-manager-core + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala new file mode 100644 index 0000000000..1782faa255 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-linux-launch/src/main/scala/com/webank/wedatasphere/linkis/ecm/linux/launch/LinuxProcessEngineConnLaunch.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.linux.launch + +import com.webank.wedatasphere.linkis.ecm.core.launch.ProcessEngineConnLaunch + + + +class LinuxProcessEngineConnLaunch extends ProcessEngineConnLaunch { + + override protected def execFile: Array[String] = Array("sh", getPreparedExecFile) + + override protected def sudoCommand(user: String, command: String): Array[String] = + Array("sudo", "su", "-", user, "-c", command) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml new file mode 100644 index 0000000000..6a2fdead19 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/pom.xml @@ -0,0 +1,85 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-engineconn-manager-core + + + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-plugin-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala new file mode 100644 index 0000000000..df8b71f7d8 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConn.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + +import java.io.Closeable +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.ecm.core.launch.{EngineConnLaunchRunner, EngineConnManagerEnv} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnCreationDesc +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineConn extends Closeable { + + def getTickedId: String + + def setTickedId(tickedId: String) + + def getServiceInstance: ServiceInstance + + def setServiceInstance(serviceInstance: ServiceInstance): Unit + + def getResource: NodeResource + + def setResource(resource: NodeResource): Unit + + def getLabels: util.List[Label[_]] + + def setLabels(labels: util.List[Label[_]]): Unit + + def getStatus: NodeStatus + + def setStatus(status: NodeStatus): Unit + + def getCreationDesc: EngineConnCreationDesc + + def setCreationDesc(desc: EngineConnCreationDesc): Unit + + def getEngineConnInfo: EngineConnInfo + + def setEngineConnInfo(engineConnInfo: EngineConnInfo): Unit + + def getEngineConnManagerEnv: EngineConnManagerEnv + + def setEngineConnManagerEnv(env: EngineConnManagerEnv): Unit + + def getEngineConnLaunchRunner: EngineConnLaunchRunner + + def setEngineConnLaunchRunner(runner: EngineConnLaunchRunner): Unit + + def setPid(pid: String): Unit + + def getPid: String + + override def close(): Unit = {} +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala new file mode 100644 index 0000000000..e2fcd4a81c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/EngineConnInfo.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + + +class EngineConnInfo { + + private var errorCode: Int = 0 + private var errorMsg: String = _ + + def setErrorCode(errorCode: Int): Unit = this.errorCode = errorCode + + def getErrorCode: Int = errorCode + + def setErrorMsg(errorMsg: String): Unit = this.errorMsg = errorMsg + + def getErrorMsg: String = errorMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala new file mode 100644 index 0000000000..2a31060f39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/engineconn/YarnEngineConn.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.engineconn + + +trait YarnEngineConn extends EngineConn { + + def getApplicationId: String + + def setApplicationId(applicationId: String): Unit + + def getApplicationURL: String + + def setApplicationURL(applicationURL: String): Unit + + def getYarnMode: String + + def setYarnMode(yarnMode: String): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala new file mode 100644 index 0000000000..dafe19cc94 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/DiscoveryMsgGenerator.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.util + +import scala.collection.JavaConversions._ + + +trait DiscoveryMsgGenerator { + + def generate(engineConnManagerEnv: EngineConnManagerEnv): java.util.Map[String, String] + +} + +class EurekaDiscoveryMsgGenerator extends DiscoveryMsgGenerator { + override def generate(engineConnManagerEnv: EngineConnManagerEnv): util.Map[String, String] = + engineConnManagerEnv.properties.get("eureka.client.serviceUrl.defaultZone") + .map(v => Map("eureka.client.serviceUrl.defaultZone" -> v)).getOrElse[Map[String,String]](Map.empty) +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala new file mode 100644 index 0000000000..e2973b61df --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunch.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest + + + +trait EngineConnLaunch { + + def setEngineConnLaunchRequest(request: EngineConnLaunchRequest): Unit + + def setEngineConnManagerEnv(engineConnManagerEnv: EngineConnManagerEnv): Unit + + def launch(): Unit + + def kill(): Unit + + def isAlive: Boolean + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala new file mode 100644 index 0000000000..bf81c3ac39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnLaunchRunner.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + + +trait EngineConnLaunchRunner extends Runnable { + + /** + * + * @param launch + */ + def setEngineConnLaunch(launch: EngineConnLaunch): Unit + + def getEngineConnLaunch: EngineConnLaunch + + def stop(): Unit + +} +class EngineConnLaunchRunnerImpl extends EngineConnLaunchRunner { + + private var launch: EngineConnLaunch = _ + /** + * + * @param launch + */ + override def setEngineConnLaunch(launch: EngineConnLaunch): Unit = this.launch = launch + + override def getEngineConnLaunch: EngineConnLaunch = launch + + override def stop(): Unit = launch.kill() + + override def run(): Unit = { + launch.launch() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala new file mode 100644 index 0000000000..71ef80222a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/EngineConnManagerEnv.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + + +trait EngineConnManagerEnv { + + val engineConnManagerHomeDir: String + val engineConnWorkDir: String + val engineConnLogDirs: String + val engineConnTempDirs: String + val engineConnManagerHost: String + val engineConnManagerPort: String + val linkDirs: Map[String, String] + val properties: Map[String, String] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala new file mode 100644 index 0000000000..1f851a6e92 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandBuilder.scala @@ -0,0 +1,91 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.OutputStream + +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.LaunchConstants +import org.apache.commons.io.IOUtils + + +trait ProcessEngineCommandBuilder { + + def setCommand(command: Array[String]): Unit + + def setEnv(key: String, value: String): Unit + + def newLine(command: Array[String]) + + def link(fromPath: String, toPath: String) + + def mkdir(dir: String): Unit + + def writeTo(output: OutputStream): Unit + + def replaceExpansionMarker(value: String): String + +} + +abstract class ShellProcessEngineCommandBuilder extends ProcessEngineCommandBuilder { + + private val LINE_SEPARATOR = System.getProperty("line.separator") + private val sb = new StringBuilder + + def newLine(command: String): Unit = newLine(Array(command)) + + override def newLine(command: Array[String]): Unit = { + command.foreach(sb ++= _) + sb ++= LINE_SEPARATOR + } + + def writeTo(output: OutputStream): Unit = { + IOUtils.write(sb, output) + } + + override def replaceExpansionMarker(value: String): String = value.replaceAll(LaunchConstants.EXPANSION_MARKER_LEFT, "\\${") + .replaceAll(LaunchConstants.EXPANSION_MARKER_RIGHT, "}") +} + +class UnixProcessEngineCommandBuilder extends ShellProcessEngineCommandBuilder { + + newLine("#!/bin/bash") + + private def addErrorCheck(): Unit = { + newLine("linkis_engineconn_errorcode=$?") + newLine("if [ $linkis_engineconn_errorcode -ne 0 ]") + newLine("then") + newLine(" exit $linkis_engineconn_errorcode") + newLine("fi") + } + + override def setCommand(command: Array[String]): Unit = { + newLine(Array(s"exec /bin/bash -c ${"\""}${command.mkString(" ")}${"\""}")) + addErrorCheck() + } + + override def setEnv(key: String, value: String): Unit = newLine(Array("export ", key, "=\"", value, "\"")) + + override def link(fromPath: String, toPath: String): Unit = { + newLine(Array("ln -sf \"", fromPath, "\" \"", toPath, "\"")) + addErrorCheck() + } + + override def mkdir(dir: String): Unit = { + newLine(Array("mkdir -p ", dir)) + addErrorCheck() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala new file mode 100644 index 0000000000..fbc1724603 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineCommandExec.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.File +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging + + +trait ProcessEngineCommandExec { + + def execute(): Unit + + def getProcess: Process + +} + +class ShellProcessEngineCommandExec(command: Array[String], baseDir: String, + environment: util.Map[String, String], timeout: Long) extends + ProcessEngineCommandExec with Logging { + + private var process: Process = _ + + def this(command: Array[String], baseDir: String) = this(command, baseDir, null, 0) + + def this(command: Array[String]) = this(command, null) + + override def execute(): Unit = { + + info(s"Invoke subProcess, base dir ${this.baseDir} cmd is: ${command.mkString}") + val builder = new ProcessBuilder(command: _*) + if (environment != null) builder.environment.putAll(this.environment) + if (baseDir != null) builder.directory(new File(this.baseDir)) + builder.redirectErrorStream(true) + process = builder.start + } + + override def getProcess: Process = process +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala new file mode 100644 index 0000000000..9146b56618 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/launch/ProcessEngineConnLaunch.scala @@ -0,0 +1,171 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.launch + +import java.io.{File, InputStream, OutputStream} +import java.net.ServerSocket + +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.exception.ErrorException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.utils.{EngineConnArgumentsBuilder, EngineConnArgumentsParser} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.conf.EnvConfiguration +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.Environment._ +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.LaunchConstants._ +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.{Environment, ProcessEngineConnLaunchRequest} +import org.apache.commons.io.{FileUtils, IOUtils} +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +trait ProcessEngineConnLaunch extends EngineConnLaunch with Logging { + + private var request: ProcessEngineConnLaunchRequest = _ + private var engineConnManagerEnv: EngineConnManagerEnv = _ + private var discoveryMsgGenerator: DiscoveryMsgGenerator = _ + private var processBuilder: ProcessEngineCommandBuilder = _ + private var preparedExecFile: String = _ + private var process: Process = _ + + private var engineConnPort: String = _ + + protected def newProcessEngineConnCommandBuilder(): ProcessEngineCommandBuilder = new UnixProcessEngineCommandBuilder + + protected def newProcessEngineConnCommandExec(command: Array[String], workDir: String): ProcessEngineCommandExec = + new ShellProcessEngineCommandExec(command, workDir) + + override def setEngineConnLaunchRequest(request: EngineConnLaunchRequest): Unit = request match { + case processEngineConnLaunchRequest: ProcessEngineConnLaunchRequest => + this.request = processEngineConnLaunchRequest + case _ => //TODO exception + } + + override def setEngineConnManagerEnv(engineConnManagerEnv: EngineConnManagerEnv): Unit = this.engineConnManagerEnv = engineConnManagerEnv + + def setDiscoveryMsgGenerator(discoveryMsgGenerator: DiscoveryMsgGenerator): Unit = this.discoveryMsgGenerator = discoveryMsgGenerator + + def getEngineConnLaunchRequest: EngineConnLaunchRequest = request + + private def initializeEnv(): Unit = { + val environment = request.environment + def putIfExists(enum: Environment): Unit = { + val key = enum.toString + val conf = CommonVars.apply(key, "") + if(StringUtils.isNotBlank(conf.getValue)) environment.put(key, conf.getValue) + } + Environment.values foreach { + case USER => environment.put(USER.toString, request.user) + case ECM_HOME => environment.put(ECM_HOME.toString, engineConnManagerEnv.engineConnManagerHomeDir) + case PWD => environment.put(PWD.toString, engineConnManagerEnv.engineConnWorkDir) + case LOG_DIRS => environment.put(LOG_DIRS.toString, engineConnManagerEnv.engineConnLogDirs) + case TEMP_DIRS => environment.put(TEMP_DIRS.toString, engineConnManagerEnv.engineConnTempDirs) + case ECM_HOST => environment.put(ECM_HOST.toString, engineConnManagerEnv.engineConnManagerHost) + case ECM_PORT => environment.put(ECM_PORT.toString, engineConnManagerEnv.engineConnManagerPort) + case HADOOP_HOME => putIfExists(HADOOP_HOME) + case HADOOP_CONF_DIR => putIfExists(HADOOP_CONF_DIR) + case HIVE_CONF_DIR => putIfExists(HIVE_CONF_DIR) + case RANDOM_PORT => environment.put(RANDOM_PORT.toString, findAvailPort().toString) + case _ => + } + } + + private def findAvailPort(): Int = { + val socket = new ServerSocket(0) + Utils.tryFinally(socket.getLocalPort)(IOUtils.closeQuietly(socket)) + } + + private def addAvailPort(value: String): String = { + var existsRandomPort = value.contains(CLASS_PATH_SEPARATOR) + var newValue = value + while(existsRandomPort) { + newValue = value.replaceFirst(CLASS_PATH_SEPARATOR, findAvailPort().toString) + existsRandomPort = value.contains(CLASS_PATH_SEPARATOR) + } + newValue + } + + override def launch(): Unit = { + request.necessaryEnvironments.foreach{e => + val env = CommonVars(e, "") + if(StringUtils.isEmpty(env.getValue)) + throw new ErrorException(30000, s"Necessary environment $e is not exists!(必须的环境变量 $e 不存在!)") //TODO exception + else request.environment.put(e, env.getValue) + } + prepareCommand() + val exec = newProcessEngineConnCommandExec(sudoCommand(request.user, execFile.mkString(" ")), engineConnManagerEnv.engineConnWorkDir) + exec.execute() + process = exec.getProcess + } + + protected def execFile: Array[String] + + def getEngineConnPort: String = engineConnPort + + protected def getCommandArgs: Array[String] = { + if (request.creationDesc.properties.exists { case (k, v) => k.contains(" ") || (v != null && v.contains(" ")) }) + throw new ErrorException(30000, "Startup parameters contain spaces!(启动参数中包含空格!)") //TODO exception + val arguments = EngineConnArgumentsBuilder.newBuilder() + engineConnPort = findAvailPort().toString + var springConf = Map("spring.application.name" -> GovernanceCommonConf.ENGINE_CONN_SPRING_NAME.getValue, + "server.port" -> engineConnPort, "spring.profiles.active" -> "engineconn", + "logging.config" -> s"classpath:${EnvConfiguration.LOG4J2_XML_FILE.getValue}") ++: discoveryMsgGenerator.generate(engineConnManagerEnv) + request.creationDesc.properties.filter(_._1.startsWith("spring.")).foreach { case (k, v) => + springConf = springConf += (k -> v) + } + arguments.addSpringConf(springConf.toMap) + var engineConnConf = Map("ticketId" -> request.ticketId, "user" -> request.user) + engineConnConf = engineConnConf ++: request.labels.map(l => EngineConnArgumentsParser.LABEL_PREFIX + l.getLabelKey -> l.getStringValue).toMap + engineConnConf = engineConnConf ++: request.creationDesc.properties.filterNot(_._1.startsWith("spring.")).toMap + arguments.addEngineConnConf(engineConnConf) + EngineConnArgumentsParser.getEngineConnArgumentsParser.parseToArgs(arguments.build()) + } + + override def kill(): Unit = process.destroy() + + override def isAlive: Boolean = process.isAlive + + protected def prepareCommand(): Unit = { + processBuilder = newProcessEngineConnCommandBuilder() + engineConnManagerEnv.linkDirs.foreach{case (k, v) => processBuilder.link(k, v)} + initializeEnv() + request.environment.foreach{ case (k, v) => + var value = v.replaceAll(CLASS_PATH_SEPARATOR, File.pathSeparator) + value = addAvailPort(value) + processBuilder.setEnv(k, processBuilder.replaceExpansionMarker(value)) + } + val execCommand = request.commands.map(processBuilder.replaceExpansionMarker(_)).map(addAvailPort) ++ getCommandArgs + //execCommand = sudoCommand(request.user, execCommand.mkString(" ")) + processBuilder.setCommand(execCommand) + preparedExecFile = new File(engineConnManagerEnv.engineConnWorkDir, "engineConnExec.sh").getPath + val output = getFileOutputStream + Utils.tryFinally(processBuilder.writeTo(output))(output.close()) + } + + protected def sudoCommand(user: String, command: String): Array[String] + + protected def getFileOutputStream: OutputStream = FileUtils.openOutputStream(new File(preparedExecFile)) + + protected def getPreparedExecFile: String = preparedExecFile + + def getProcessInputStream:InputStream = process.getInputStream + + def processWaitFor:Int =process.waitFor + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala new file mode 100644 index 0000000000..fc13ec07de --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMAsyncListenerBus.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerEventBus + + +class ECMAsyncListenerBus(capacity: Int, name: String) + (consumerThreadSize: Int, threadMaxFreeTime: Long) + extends ListenerEventBus[ECMEventListener, ECMEvent](capacity, name)(consumerThreadSize, threadMaxFreeTime) { + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: ECMEventListener, event: ECMEvent): Unit = listener.onEvent(event) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java new file mode 100644 index 0000000000..011137d69a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEvent.java @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener; + +import com.webank.wedatasphere.linkis.common.listener.Event; + + +public interface ECMEvent extends Event { +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala new file mode 100644 index 0000000000..242972feb1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMEventListener.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.{Event, EventListener} +import com.webank.wedatasphere.linkis.common.utils.Logging + + +trait ECMEventListener extends EventListener with Logging { + + def onEvent(event: ECMEvent) + + override def onEventError(event: Event, t: Throwable): Unit = { + error(s"async message invoke failed ${event.toString}", t) + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala new file mode 100644 index 0000000000..208fe6fd68 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/listener/ECMSyncListenerBus.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerBus + +class ECMSyncListenerBus extends ListenerBus[ECMEventListener, ECMEvent] { + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: ECMEventListener, event: ECMEvent): Unit = listener.onEvent(event) +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala new file mode 100644 index 0000000000..6245c57b5e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/metrics/ECMMetrics.scala @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.metrics + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn + + + +trait ECMMetrics { + + def getStartingEngineConns: Array[_ <: EngineConn] + + def getRunningEngineConns: Array[EngineConn] + + def getSucceedEngineConns: Array[EngineConn] + + def getFailedEngineConns: Array[EngineConn] + + def increaseStartingEngineConn(engineConn: EngineConn): Unit + + def increaseRunningEngineConn(engineConn: EngineConn): Unit + + def increaseSuccessEngineConn(engineConn: EngineConn): Unit + + def increaseFailedEngineConn(engineConn: EngineConn): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala new file mode 100644 index 0000000000..44fef7ce3a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/ECMHealthReport.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.report + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +trait ECMHealthReport extends NodeHealthReport { + + def setProtectedResource(protectedResource: Resource): Unit + + def getProtectResource: Resource + + def setOverload(nodeOverLoadInfo: NodeOverLoadInfo): Unit + + def getOverload: NodeOverLoadInfo + + def setRunningEngineConns(runningEngines: Array[EngineConn]) + + def getRunningEngineConns: Array[EngineConn] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala new file mode 100644 index 0000000000..ebd7c87a22 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-core/src/main/scala/com/webank/wedatasphere/linkis/ecm/core/report/NodeHealthReport.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.core.report + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +trait NodeHealthReport { + + def getReportTime: Long + + def setReportTime(reportTime: Long): Unit + + def getNodeStatus: NodeStatus + + def setNodeStatus(nodeStatus: NodeStatus): Unit + + def setNodeMsg(msg: String): Unit + + def getNodeMsg: String + + def getUsedResource: Resource + + def setUsedResource(resource: Resource): Unit + + def getTotalResource: Resource + + def setTotalResource(resource: Resource): Unit + + def setNodeId(nodeId: String): Unit + + def getNodeId: String + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml new file mode 100644 index 0000000000..06b7609354 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/pom.xml @@ -0,0 +1,141 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-engineconn-manager-server + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-manager-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-linux-launch + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + provided + + + + + com.webank.wedatasphere.linkis + linkis-bml-client + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + org.json4s + json4s-jackson_${scala.binary.version} + ${json4s.version} + provided + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + false + + + make-assembly + package + + single + + + + src/main/assembly/distribution.xml + + + + + + false + out + false + false + + src/main/assembly/distribution.xml + + + + + + + ${basedir}/src/main/resources + + **/*.properties + **/*.xml + **/*.yml + + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml new file mode 100644 index 0000000000..ef1578ec9c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/assembly/distribution.xml @@ -0,0 +1,73 @@ + + + + linkis-engineconn-manager + + dir + + false + linkis-engineconn-manager + + + + + + lib + true + true + false + true + true + + + + + + + + ${basedir}/src/main/resources + + * + + 0777 + conf + unix + + + + + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java new file mode 100644 index 0000000000..9e38ce8793 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/java/com/webank/wedatasphere/linkis/ecm/server/ECMApplication.java @@ -0,0 +1,122 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import com.webank.wedatasphere.linkis.common.ServiceInstance; +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMAsyncListenerBus; +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMSyncListenerBus; +import com.webank.wedatasphere.linkis.ecm.server.context.ECMContext; +import com.webank.wedatasphere.linkis.ecm.server.listener.ECMClosedEvent; +import com.webank.wedatasphere.linkis.ecm.server.listener.ECMReadyEvent; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.EventListener; + +import static com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.ECM_ASYNC_BUS_WAITTOEMPTY_TIME; + + +public class ECMApplication extends DataWorkCloudApplication { + + private static ECMContext ecmContext; + + private volatile static boolean ready; + + private static ServiceInstance ecmServiceInstance; + + private static String[] parmas; + + public static void main(String[] args) throws ReflectiveOperationException { + parmas = args; + DataWorkCloudApplication.main(args); + } + + public static ECMContext getContext() { + return ecmContext; + } + + public static void setContext(ECMContext context) { + ecmContext = context; + } + + public static ServiceInstance getECMServiceInstance() { + return ecmServiceInstance; + } + + public static void setECMServiceInstance(ServiceInstance serviceInstance) { + ecmServiceInstance = serviceInstance; + } + + public static boolean isReady() { + return ready; + } + + public static void setReady(boolean applicationReady) { + ready = applicationReady; + } + + public static String[] getParmas() { + return parmas; + } +} + + +@Configuration +class ECMApplicationListener { + + private final Log logger = LogFactory.getLog(this.getClass()); + + @EventListener + public void onApplicationReady(ApplicationReadyEvent event) { + ServiceInstance serviceInstance = DataWorkCloudApplication.getServiceInstance(); + ECMApplication.setECMServiceInstance(serviceInstance); + ECMContext context = event.getApplicationContext().getBean(ECMContext.class); + ECMApplication.setContext(context); + ECMAsyncListenerBus emAsyncListenerBus = context.getECMAsyncListenerBus(); + ECMSyncListenerBus emSyncListenerBus = context.getECMSyncListenerBus(); + emAsyncListenerBus.start(); + ECMReadyEvent ecmReadyEvent = new ECMReadyEvent(ECMApplication.getParmas()); + emAsyncListenerBus.postToAll(ecmReadyEvent); + emSyncListenerBus.postToAll(ecmReadyEvent); + ECMApplication.setReady(true); + logger.info(String.format("ECM:%s is ready", serviceInstance)); + } + + @EventListener + public void onApplicationClosed(ContextClosedEvent contextClosedEvent) { + ServiceInstance serviceInstance = DataWorkCloudApplication.getServiceInstance(); + ECMApplication.setReady(false); + ECMClosedEvent ecmClosedEvent = new ECMClosedEvent(); + ECMApplication.getContext().getECMSyncListenerBus().postToAll(ecmClosedEvent); + ECMAsyncListenerBus ecmAsyncListenerBus = ECMApplication.getContext().getECMAsyncListenerBus(); + ecmAsyncListenerBus.postToAll(ecmClosedEvent); + logger.info(String.format("wait ECM:%s asyncBus empty", serviceInstance)); + try { + ecmAsyncListenerBus.waitUntilEmpty(ECM_ASYNC_BUS_WAITTOEMPTY_TIME()); + } catch (Throwable e) { + logger.error("wait ECM asyncBus empty failed", e); + } + logger.info("ECM asyncBus is empty"); + ecmAsyncListenerBus.stop(); + logger.info("ECM is closed"); + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml new file mode 100644 index 0000000000..b644f75f86 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/application.yml @@ -0,0 +1,29 @@ +server: + port: 9102 +spring: + application: + name: linkis-cg-engineconnmanager + + +eureka: + client: + serviceUrl: + defaultZone: http://127.0.0.1:20303/eureka/ + instance: + metadata-map: + test: wedatasphere + +management: + endpoints: + web: + exposure: + include: refresh,info + health: + db: + enabled: false +logging: + config: classpath:log4j2.xml + +ribbon: + ReadTimeout: 60000 + ConnectTimeout: 60000 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties new file mode 100644 index 0000000000..6c12e6aa27 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/linkis-server.properties @@ -0,0 +1,18 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +##restful +wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.em.restful + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..0f19fc3c17 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala new file mode 100644 index 0000000000..3ad3d73796 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/conf/ECMConfiguration.scala @@ -0,0 +1,75 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.conf + +import java.io.File +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} +import com.webank.wedatasphere.linkis.common.utils.ByteTimeUtils +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf + +import scala.concurrent.duration.Duration + + +object ECMConfiguration { + + //listenerbus + val ECM_ASYNC_BUS_CAPACITY: Int = CommonVars("wds.linkis.ecm.async.bus.capacity", 500).getValue + val ECM_ASYNC_BUS_NAME: String = CommonVars("wds.linkis.ecm.async.bus.name", "em_async_bus").getValue + val ECM_ASYNC_BUS_CONSUMER_SIZE: Int = CommonVars("wds.linkis.ecm.async.bus.consumer.size", 30).getValue + val ECM_ASYNC_BUS_THREAD_MAX_FREE_TIME: Long = CommonVars("wds.linkis.ecm.async.bus.max.free.time", ByteTimeUtils.timeStringAsMs("2m")).getValue + val ECM_ASYNC_BUS_WAITTOEMPTY_TIME: Long = CommonVars("wds.linkis.ecm.async.bus.waittoempty.time", 5000L).getValue + + //resource + val ECM_MAX_MEMORY_AVAILABLE: Long = CommonVars[Long]("wds.linkis.ecm.memory.max", ByteTimeUtils.byteStringAsBytes("80g")).getValue + val ECM_MAX_CORES_AVAILABLE: Int = CommonVars[Integer]("wds.linkis.ecm.cores.max", 50).getValue + val ECM_MAX_CREATE_INSTANCES: Int = CommonVars[Integer]("wds.linkis.ecm.engineconn.instances.max", 50).getValue + + val ECM_PROTECTED_MEMORY: Long = CommonVars[Long]("wds.linkis.ecm.protected.memory", ByteTimeUtils.byteStringAsBytes("4g")).getValue + val ECM_PROTECTED_CORES: Int = CommonVars[Integer]("wds.linkis.ecm.protected.cores.max", 2).getValue + val ECM_PROTECTED_INSTANCES: Int = CommonVars[Integer]("wds.linkis.ecm.protected.engine.instances", 2).getValue + + val MANAGER_SPRING_NAME: String = GovernanceCommonConf.MANAGER_SPRING_NAME.getValue + + val ENGINE_CONN_MANAGER_SPRING_NAME: String = GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue + + val ECM_HEALTH_REPORT_PERIOD: Long = CommonVars("wds.linkis.ecm.health.report.period", 5).getValue + + val ECM_HEALTH_REPORT_DELAY: Long = CommonVars("wds.linkis.ecm.health.report.delay", 10).getValue + + val ENGINECONN_SPRING_NAME: String = CommonVars("wds.linkis.engineconn.spring.name", "linkis-cg-engineplugin").getValue + + val ECM_HOME_DIR: String = CommonVars("wds.linkis.ecm.home.dir", this.getClass.getResource("/").getPath).getValue + + val ENGINECONN_ROOT_DIR: String = CommonVars("wds.linkis.engineconn.root.dir", s"${ECM_HOME_DIR}engineConnRootDir").getValue + + val ENGINECONN_PUBLIC_DIR: String = CommonVars("wds.linkis.engineconn.public.dir", s"$ENGINECONN_ROOT_DIR${File.separator}engineConnPublickDir").getValue + + val ECM_LAUNCH_MAX_THREAD_SIZE: Int = CommonVars("wds.linkis.ecm.launch.max.thread.size", 100).getValue + + val ECM_EUREKA_DEFAULTZONE: String = CommonVars("wds.linkis.eureka.defaultZone", "http://127.0.0.1:20303/eureka/").getValue + + /** + * engineconn创建时间,如果为0,则使用ms中默认的 + */ + val ENGINECONN_CREATE_DURATION: Duration = Duration(CommonVars("wds.linkis.ecm.engineconn.create.duration", 0).getValue, TimeUnit.MILLISECONDS) + + val WAIT_ENGINECONN_PID = CommonVars("wds.linkis.engineconn.wait.callback.pid", new TimeType("3s")) + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala new file mode 100644 index 0000000000..226c0a4048 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/DefaultECMContext.scala @@ -0,0 +1,41 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.context + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMAsyncListenerBus, ECMSyncListenerBus} +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.metrics.DefaultECMMetrics +import org.springframework.stereotype.Component + + +@Component +class DefaultECMContext extends ECMContext { + + private val emSyncListenerBus = new ECMSyncListenerBus + + private val emAsyncListenerBus = new ECMAsyncListenerBus(ECM_ASYNC_BUS_CAPACITY, ECM_ASYNC_BUS_NAME)(ECM_ASYNC_BUS_CONSUMER_SIZE, ECM_ASYNC_BUS_THREAD_MAX_FREE_TIME) + + private val metrics = new DefaultECMMetrics + + + override def getECMAsyncListenerBus: ECMAsyncListenerBus = emAsyncListenerBus + + override def getECMSyncListenerBus: ECMSyncListenerBus = emSyncListenerBus + + override def getECMMetrics: ECMMetrics = metrics +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala new file mode 100644 index 0000000000..42312ff750 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/context/ECMContext.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.context + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMAsyncListenerBus, ECMSyncListenerBus} +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics + + +trait ECMContext { + + def getECMAsyncListenerBus: ECMAsyncListenerBus + + def getECMSyncListenerBus: ECMSyncListenerBus + + def getECMMetrics:ECMMetrics + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala new file mode 100644 index 0000000000..ebdec3affb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/converter/ECMEngineConverter.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.converter + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, YarnEngineConn} +import com.webank.wedatasphere.linkis.ecm.server.engineConn.DefaultYarnEngineConn +import org.springframework.beans.BeanUtils + + +object ECMEngineConverter { + + def engineConn2YarnEngineConn(engineConn: EngineConn)(implicit updateFunction: YarnEngineConn => Unit): YarnEngineConn = { + val conn = new DefaultYarnEngineConn + BeanUtils.copyProperties(engineConn, conn) + updateFunction(conn) + conn + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala new file mode 100644 index 0000000000..620eed4b8a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultEngineConn.scala @@ -0,0 +1,99 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.engineConn + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, EngineConnInfo} +import com.webank.wedatasphere.linkis.ecm.core.launch.{EngineConnLaunchRunner, EngineConnManagerEnv} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnCreationDesc +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +class DefaultEngineConn extends EngineConn { + + /** + * starting :初始状态 + * success:成功启动并且安全退出 + * Failed:启动失败 + * Running:容器运行中 + */ + @volatile private var status: NodeStatus = _ + + private var tickedId: String = _ + + private var resource: NodeResource = _ + + private var labels: util.List[Label[_]] = _ + + private var engineConnCreationDesc: EngineConnCreationDesc = _ + + private var engineConnInfo: EngineConnInfo = _ + + private var ecmEnv: EngineConnManagerEnv = _ + + private var engineConnLaunchRunner: EngineConnLaunchRunner = _ + + private var instance: ServiceInstance = _ + + private var pid: String = _ + + override def getResource: NodeResource = resource + + override def setResource(resource: NodeResource): Unit = this.resource = resource + + override def getLabels: util.List[Label[_]] = labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels + + override def getStatus: NodeStatus = status + + override def getCreationDesc: EngineConnCreationDesc = engineConnCreationDesc + + override def getEngineConnInfo: EngineConnInfo = engineConnInfo + + override def getEngineConnLaunchRunner: EngineConnLaunchRunner = engineConnLaunchRunner + + override def setEngineConnLaunchRunner(runner: EngineConnLaunchRunner): Unit = this.engineConnLaunchRunner = runner + + override def setEngineConnInfo(engineConnInfo: EngineConnInfo): Unit = this.engineConnInfo = engineConnInfo + + override def getTickedId: String = tickedId + + override def setTickedId(tickedId: String): Unit = this.tickedId = tickedId + + override def setStatus(status: NodeStatus): Unit = this.status = status + + override def setCreationDesc(engineConnCreationDesc: EngineConnCreationDesc): Unit = this.engineConnCreationDesc = engineConnCreationDesc + + override def getServiceInstance: ServiceInstance = instance + + override def setServiceInstance(instance: ServiceInstance): Unit = this.instance = instance + + override def getPid: String = pid + + override def setPid(pid: String): Unit = this.pid = pid + + override def getEngineConnManagerEnv: EngineConnManagerEnv = ecmEnv + + override def setEngineConnManagerEnv(env: EngineConnManagerEnv): Unit = this.ecmEnv = env + + override def toString = s"DefaultEngineConn($status, $tickedId, $resource, $labels, $engineConnCreationDesc, $engineConnInfo, $ecmEnv, $engineConnLaunchRunner, $instance, $pid)" +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala new file mode 100644 index 0000000000..001361d4e2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/engineConn/DefaultYarnEngineConn.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.engineConn + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.YarnEngineConn + + +class DefaultYarnEngineConn extends DefaultEngineConn with YarnEngineConn { + + var applicationId: String = _ + + var applicationURL: String = _ + + var yarnMode: String = _ + + override def getApplicationId: String = applicationId + + override def setApplicationId(applicationId: String): Unit = this.applicationId = applicationId + + override def getApplicationURL: String = applicationURL + + override def setApplicationURL(applicationURL: String): Unit = this.applicationURL = applicationURL + + override def getYarnMode: String = yarnMode + + override def setYarnMode(yarnMode: String): Unit = this.yarnMode = yarnMode + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala new file mode 100644 index 0000000000..03f6b9a4ec --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/exception/ECMErrorException.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.exception + +import com.webank.wedatasphere.linkis.common.exception.{ErrorException, WarnException} + + +class ECMErrorException(errorCode: Int, desc: String) extends ErrorException(errorCode, desc) { + def this(errorCode: Int, desc: String, t: Throwable) { + this(errorCode, desc) + this.initCause(t) + } +} + +class ECMWarnException(errCode: Int, desc: String) extends WarnException(errCode, desc) + + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala new file mode 100644 index 0000000000..ba6fa5c628 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/listener/ECMReadyEvent.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.listener + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMEvent +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +case class ECMReadyEvent(params: Array[String]) extends ECMEvent + +case class ECMClosedEvent() extends ECMEvent + +case class EngineConnStatusChageEvent(from: NodeStatus, to: NodeStatus) extends ECMEvent + +case class YarnAppIdCallbackEvent(protocol: YarnAPPIdCallbackProtocol) extends ECMEvent + +case class YarnInfoCallbackEvent(protocol: YarnInfoCallbackProtocol) extends ECMEvent + +case class EngineConnPidCallbackEvent(protocol: ResponseEngineConnPid) extends ECMEvent + +case class EngineConnAddEvent(conn: EngineConn) extends ECMEvent + +case class EngineConnStatusChangeEvent(tickedId: String, updateStatus: NodeStatus) extends ECMEvent + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala new file mode 100644 index 0000000000..5b24a7d8b2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/metrics/DefaultECMMetrics.scala @@ -0,0 +1,106 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.metrics + + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.metrics.ECMMetrics +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus._ + +import scala.collection.JavaConversions._ + + +class DefaultECMMetrics extends ECMMetrics { + + + private val startingEngineConnCount = new AtomicInteger(0) + + private val runningEngineConnCount = new AtomicInteger(0) + + private val successEngineConnCount = new AtomicInteger(0) + + private val failedEngineConnCount = new AtomicInteger(0) + + private val startingEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val runningEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val successEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + private val failedEngineConnMap = new ConcurrentHashMap[String, EngineConn](64) + + override def getStartingEngineConns: Array[EngineConn] = getEngineConns(startingEngineConnMap) + + override def getRunningEngineConns: Array[EngineConn] = getEngineConns(runningEngineConnMap) + + override def getSucceedEngineConns: Array[EngineConn] = getEngineConns(successEngineConnMap) + + override def getFailedEngineConns: Array[EngineConn] = getEngineConns(failedEngineConnMap) + + private val getEngineConns = (map: ConcurrentHashMap[String, EngineConn]) => map.values().toSeq.toArray + + private val decreaseEngineConnMetric = (engineConn: EngineConn, map: ConcurrentHashMap[String, EngineConn], count: AtomicInteger) => { + val conn = map.remove(engineConn.getTickedId) + if (conn != null) { + count.decrementAndGet() + } + } + + private val increaseEngineConnMetric = (engineConn: EngineConn, map: ConcurrentHashMap[String, EngineConn], count: AtomicInteger, status: NodeStatus) => { + if (engineConn.getStatus.equals(status)) { + count.incrementAndGet() + map.put(engineConn.getTickedId, engineConn) + } + } + + override def increaseStartingEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, startingEngineConnMap, startingEngineConnCount, Starting) + } + + def decreseStartingEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, startingEngineConnMap, startingEngineConnCount) + } + + override def increaseRunningEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, runningEngineConnMap, runningEngineConnCount, Running) + } + + def decreseRunningEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, runningEngineConnMap, runningEngineConnCount) + } + + override def increaseSuccessEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, successEngineConnMap, successEngineConnCount, Success) + } + + def decreaseSuccessEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, successEngineConnMap, successEngineConnCount) + } + + override def increaseFailedEngineConn(engineConn: EngineConn): Unit = { + increaseEngineConnMetric(engineConn, failedEngineConnMap, failedEngineConnCount, Failed) + } + + def decreaseFailedEngineConn(engineConn: EngineConn): Unit = { + decreaseEngineConnMetric(engineConn, failedEngineConnMap, failedEngineConnCount) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala new file mode 100644 index 0000000000..de3e6e75d4 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/report/DefaultECMHealthReport.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.report + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +class DefaultECMHealthReport extends ECMHealthReport { + + private var protectedResource: Resource = _ + + private var totalResource: Resource = _ + + private var usedResource: Resource = _ + + private var overload: NodeOverLoadInfo = _ + + private var runningEngineConns: Array[EngineConn] = _ + + private var reportTime: Long = _ + + private var nodeStatus: NodeStatus = _ + + private var nodeMsg: String = _ + + private var nodeId: String = _ + + override def setProtectedResource(protectedResource: Resource): Unit = this.protectedResource = protectedResource + + override def getProtectResource: Resource = protectedResource + + override def setOverload(overload: NodeOverLoadInfo): Unit = this.overload = overload + + override def getOverload: NodeOverLoadInfo = overload + + override def setRunningEngineConns(runningEngines: Array[EngineConn]): Unit = this.runningEngineConns = runningEngineConns + + override def getRunningEngineConns: Array[EngineConn] = runningEngineConns + + override def getReportTime: Long = reportTime + + override def setReportTime(reportTime: Long): Unit = this.reportTime = reportTime + + override def getNodeStatus: NodeStatus = nodeStatus + + override def setNodeStatus(nodeStatus: NodeStatus): Unit = this.nodeStatus = nodeStatus + + override def setNodeMsg(nodeMsg: String): Unit = this.nodeMsg = nodeMsg + + override def getNodeMsg: String = nodeMsg + + override def getUsedResource: Resource = usedResource + + override def setUsedResource(usedResource: Resource): Unit = this.usedResource = usedResource + + override def getTotalResource: Resource = totalResource + + override def setTotalResource(totalResource: Resource): Unit = this.totalResource = totalResource + + override def setNodeId(nodeId: String): Unit = this.nodeId = nodeId + + override def getNodeId: String = nodeId +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala new file mode 100644 index 0000000000..2df4e9d45a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMHealthService.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} + + +trait ECMHealthService{ + + def getLastEMHealthReport: ECMHealthReport + + def reportHealth(report: ECMHealthReport): Unit + + def generateHealthReport(reportTime:Long): ECMHealthReport + + def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala new file mode 100644 index 0000000000..408bf25c62 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMMetricsService.scala @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + + +trait ECMMetricsService { + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala new file mode 100644 index 0000000000..2ade991a79 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ECMRegisterService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.em.{RegisterEMRequest, StopEMRequest} + + +trait ECMRegisterService { + + def registerECM(event: RegisterEMRequest): Unit + + def unRegisterECM(event: StopEMRequest): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala new file mode 100644 index 0000000000..de7c5b8528 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnKillService.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineStopRequest, EngineStopResponse} + + +trait EngineConnKillService { + + def dealEngineConnStop(engineStopRequest: EngineStopRequest): EngineStopResponse + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala new file mode 100644 index 0000000000..c98801d374 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnLaunchService.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.entity.node.EngineNode +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.{EngineConnBuildRequest, EngineConnLaunchRequest} + + + +trait EngineConnLaunchService { + /** + * launchEngine启动一个引擎的方法 + * + * @param engineConnBuildRequest 封装了引擎启动的参数 + */ + def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest): EngineNode + + def launchEngineConn(engineConnLaunchRequest: EngineConnLaunchRequest, duration: Long): EngineNode + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala new file mode 100644 index 0000000000..bfb7ef8942 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnListService.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import java.util + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnLaunchRunner +import com.webank.wedatasphere.linkis.manager.common.entity.resource.Resource + + +/** + * The enginelistservice interface manages the interface started by the engine + * The most important submit method is to put the thread that starts the engine into the thread pool to start + * EngineListService接口管理引擎启动的接口 + * 最重要的submit方法是将启动引擎的线程放入到线程池中进行启动 + */ +trait EngineConnListService { + + def init(): Unit + + def getEngineConn(engineConnId: String): Option[EngineConn] + + def getEngineConns: util.List[EngineConn] + + def addEngineConn(engineConn: EngineConn): Unit + + def killEngineConn(engineConnId: String): Unit + + def getUsedResources: Resource + + def submit(runner: EngineConnLaunchRunner): Option[EngineConn] + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala new file mode 100644 index 0000000000..4d751de00b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnPidCallbackService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid + + +trait EngineConnPidCallbackService { + + + def dealPid(protocol: ResponseEngineConnPid): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala new file mode 100644 index 0000000000..8e234ded25 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/EngineConnStatusCallbackService.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallback + + +trait EngineConnStatusCallbackService { + + def dealEngineConnStatusCallback(protocol: EngineConnStatusCallback): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala new file mode 100644 index 0000000000..6ff1b35092 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LocalDirsHandleService.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + + +trait LocalDirsHandleService { + + def getEngineConnManagerHomeDir: String + + def getEngineConnWorkDir(user: String, ticketId: String): String + + def getEngineConnPublicDir: String + + def getEngineConnLogDir(user: String, ticketId: String): String + + def getEngineConnTmpDir(user: String, ticketId: String): String + + def cleanup(): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala new file mode 100644 index 0000000000..74f829d20d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/LogCallbackService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.protocol.callback.LogCallbackProtocol + + + +trait LogCallbackService { + + def dealLog(protocol: LogCallbackProtocol): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala new file mode 100644 index 0000000000..0a74ea8dcf --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/ResourceLocalizationService.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest + + +trait ResourceLocalizationService { + + def handleInitEngineConnResources(request: EngineConnLaunchRequest, engineConn: EngineConn): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala new file mode 100644 index 0000000000..4ed8ecf75f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/YarnCallbackService.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service + +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +trait YarnCallbackService { + + def dealApplicationId(protocol: YarnAPPIdCallbackProtocol): Unit + + def dealApplicationURI(protocol: YarnInfoCallbackProtocol): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala new file mode 100644 index 0000000000..7a0e7d4335 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/AbstractEngineConnLaunchService.scala @@ -0,0 +1,134 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, EngineConnInfo} +import com.webank.wedatasphere.linkis.ecm.core.launch._ +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.engineConn.DefaultEngineConn +import com.webank.wedatasphere.linkis.ecm.server.listener.{EngineConnAddEvent, EngineConnStatusChangeEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.{EngineConnLaunchService, ResourceLocalizationService} +import com.webank.wedatasphere.linkis.ecm.server.util.ECMUtils +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus.Failed +import com.webank.wedatasphere.linkis.manager.common.entity.node.{AMEngineNode, EngineNode} +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallbackToAM +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.rpc.Sender +import org.apache.commons.lang.exception.ExceptionUtils + +import scala.concurrent.duration.Duration +import scala.concurrent.{Await, ExecutionContextExecutorService, Future} +import scala.util.{Failure, Success} + + +abstract class AbstractEngineConnLaunchService extends EngineConnLaunchService with Logging { + + + protected implicit val executor: ExecutionContextExecutorService = Utils.newCachedExecutionContext(ECM_LAUNCH_MAX_THREAD_SIZE, "EngineConn-Manager-Thread-") + + protected var resourceLocalizationService: ResourceLocalizationService = _ + + def setResourceLocalizationService(service: ResourceLocalizationService): Unit = this.resourceLocalizationService = service + + + def beforeLaunch(conn: EngineConn, duration: Long): Unit = {} + + def afterLaunch(conn: EngineConn, duration: Long): Unit = {} + + override def launchEngineConn(request: EngineConnLaunchRequest, duration: Long): EngineNode = { + //1.创建engineConn和runner,launch 并设置基础属性 + val conn = createEngineConn + val runner = createEngineConnLaunchRunner + val launch = createEngineConnLaunch + launch.setEngineConnLaunchRequest(request) + runner.setEngineConnLaunch(launch) + conn.setEngineConnLaunchRunner(runner) + conn.setLabels(request.labels) + conn.setCreationDesc(request.creationDesc) + conn.setResource(request.nodeResource) + conn.setTickedId(request.ticketId) + conn.setStatus(NodeStatus.Starting) + conn.setEngineConnInfo(new EngineConnInfo) + //2.资源本地化,并且设置ecm的env环境信息 + getResourceLocalizationServie.handleInitEngineConnResources(request, conn) + //3.添加到list + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnAddEvent(conn)) + //4.run + try { + beforeLaunch(conn, duration) + runner.run() + launch match { + case pro: ProcessEngineConnLaunch => + val serviceInstance = ServiceInstance(GovernanceCommonConf.ENGINE_CONN_SPRING_NAME.getValue, ECMUtils.getInstanceByPort(pro.getEngineConnPort)) + conn.setServiceInstance(serviceInstance) + case _ => + } + + val future = Future { + afterLaunch(conn, duration) + } + + future onComplete { + case Failure(t) => + throw t + case Success(_) => + info(s"init ${conn.getServiceInstance} succeed.") + } + //超时忽略,如果状态翻转了则直接返回 + Utils.tryQuietly(Await.result(future, Duration(WAIT_ENGINECONN_PID.getValue.toLong, TimeUnit.MILLISECONDS))) + } catch { + //failed,1.被ms打断,2.超时,3.普通错误,比如process + case t: Throwable => + error(s"init ${conn.getServiceInstance} failed, now stop and delete it. message: ${t.getMessage}") + conn.getEngineConnLaunchRunner.stop() + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(conn.getServiceInstance, + NodeStatus.ShuttingDown, " wait init failed , reason " + ExceptionUtils.getRootCauseMessage(t))) + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(conn.getTickedId, Failed)) + throw t + } + val engineNode = new AMEngineNode() + engineNode.setLabels(conn.getLabels) + + engineNode.setServiceInstance(conn.getServiceInstance) + engineNode.setOwner(request.user) + engineNode.setMark("process") + engineNode + } + + def createEngineConn: EngineConn = new DefaultEngineConn + + + def createEngineConnLaunchRunner: EngineConnLaunchRunner = new EngineConnLaunchRunnerImpl + + + def createEngineConnLaunch: EngineConnLaunch + + + def getResourceLocalizationServie: ResourceLocalizationService = { + // TODO: null 抛出异常 + this.resourceLocalizationService + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala new file mode 100644 index 0000000000..d8c292c02a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/BmlResourceLocalizationService.scala @@ -0,0 +1,131 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.io.File +import java.nio.file.Paths + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.{Utils, ZipUtils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnManagerEnv +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.service.{LocalDirsHandleService, ResourceLocalizationService} +import com.webank.wedatasphere.linkis.ecm.server.util.ECMUtils +import com.webank.wedatasphere.linkis.manager.common.protocol.bml.BmlResource +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.EngineConnLaunchRequest +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.ProcessEngineConnLaunchRequest +import com.webank.wedatasphere.linkis.storage.FSFactory +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import com.webank.wedatasphere.linkis.storage.utils.{FileSystemUtils, StorageUtils} + +import scala.collection.JavaConversions._ +import scala.collection.mutable + + +class BmlResourceLocalizationService extends ResourceLocalizationService { + + private implicit val fs: FileSystem = FSFactory.getFs(StorageUtils.FILE).asInstanceOf[FileSystem] + + fs.init(null) + + private val seperator = File.separator + + private val schema = StorageUtils.FILE_SCHEMA + + private var localDirsHandleService: LocalDirsHandleService = _ + + def setLocalDirsHandleService(localDirsHandleService: LocalDirsHandleService): Unit = this.localDirsHandleService = localDirsHandleService + + override def handleInitEngineConnResources(request: EngineConnLaunchRequest, engineConn: EngineConn): Unit = { + // TODO: engineType判断是否下载到本地 unzip + //engine_type resourceId version判断是否更新,或者重新下载,将path给到properties + request match { + case request: ProcessEngineConnLaunchRequest => + val files = request.bmlResources + val linkDirsP = new mutable.HashMap[String, String] + val user = request.user + val ticketId = request.ticketId + val workDir = createDirIfNotExit(localDirsHandleService.getEngineConnWorkDir(user, ticketId)) + val emHomeDir = createDirIfNotExit(localDirsHandleService.getEngineConnManagerHomeDir) + val logDirs = createDirIfNotExit(localDirsHandleService.getEngineConnLogDir(user, ticketId)) + val tmpDirs = createDirIfNotExit(localDirsHandleService.getEngineConnTmpDir(user, ticketId)) + files.foreach(downloadBmlResource(request, linkDirsP, _, workDir)) + engineConn.getEngineConnLaunchRunner.getEngineConnLaunch.setEngineConnManagerEnv(new EngineConnManagerEnv { + override val engineConnManagerHomeDir: String = emHomeDir + override val engineConnWorkDir: String = workDir + override val engineConnLogDirs: String = logDirs + override val engineConnTempDirs: String = tmpDirs + override val engineConnManagerHost: String = Utils.getComputerName + override val engineConnManagerPort: String = DataWorkCloudApplication.getApplicationContext.getEnvironment.getProperty("server.port") + override val linkDirs: Map[String, String] = linkDirsP.toMap + // TODO: 注册发现信息的配置化 + override val properties: Map[String, String] = Map("eureka.client.serviceUrl.defaultZone" -> ECM_EUREKA_DEFAULTZONE) + }) + case _ => + } + } + + + private val bmlResourceSuffix = ".zip" + + private def createDirIfNotExit(noSchemaPath: String): String = { + val fsPath = new FsPath(schema + noSchemaPath) + if (!fs.exists(fsPath)) { + FileSystemUtils.mkdirs(fs, fsPath, Utils.getJvmUser) + fs.setPermission(fsPath, "rwxrwx---") + } + noSchemaPath + } + + def downloadBmlResource(request: ProcessEngineConnLaunchRequest, linkDirs: mutable.HashMap[String, String], resource: BmlResource, workDir: String): Unit = { + val resourceId = resource.getResourceId + val version = resource.getVersion + val user = request.user + resource.getVisibility match { + case BmlResource.BmlResourceVisibility.Public => + val publicDir = localDirsHandleService.getEngineConnPublicDir + val bmlResourceDir = schema + Paths.get(publicDir, resourceId, version).toFile.getPath + val fsPath = new FsPath(bmlResourceDir) + if (!fs.exists(fsPath)) { + ECMUtils.downLoadBmlResourceToLocal(resource, user, fsPath.getPath) + val unzipDir = fsPath.getSchemaPath + File.separator + resource.getFileName.substring(0, resource.getFileName.lastIndexOf(".")) + FileSystemUtils.mkdirs(fs, new FsPath(unzipDir), Utils.getJvmUser) + ZipUtils.unzip(bmlResourceDir + File.separator + resource.getFileName, unzipDir) + fs.delete(new FsPath(bmlResourceDir + File.separator + resource.getFileName)) + } + //2.软连,并且添加到map + val dirAndFileList = fs.listPathWithError(fsPath) + dirAndFileList.getFsPaths.foreach { + case path: FsPath => + val name = new File(path.getPath).getName + linkDirs.put(path.getPath, workDir + seperator + name) + } + case BmlResource.BmlResourceVisibility.Private => + val fsPath = new FsPath(schema + workDir) + if (!fs.exists(fsPath)) { + FileSystemUtils.mkdirs(fs, fsPath, Utils.getJvmUser) + ECMUtils.downLoadBmlResourceToLocal(resource, user, fsPath.getPath) + ZipUtils.unzip(schema + workDir + File.separator + resource.getFileName, fsPath.getSchemaPath) + fs.delete(new FsPath(schema + workDir + File.separator + resource.getFileName)) + } + case BmlResource.BmlResourceVisibility.Label => + } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala new file mode 100644 index 0000000000..feb5cb1074 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMHealthService.scala @@ -0,0 +1,137 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.Date +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.core.report.ECMHealthReport +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.listener.{ECMClosedEvent, ECMReadyEvent} +import com.webank.wedatasphere.linkis.ecm.server.report.DefaultECMHealthReport +import com.webank.wedatasphere.linkis.ecm.server.service.{ECMHealthService, EngineConnListService} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.{NodeHealthy, NodeStatus} +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.{NodeHealthyInfo, NodeOverLoadInfo} +import com.webank.wedatasphere.linkis.manager.common.entity.resource.{CommonNodeResource, LoadInstanceResource} +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import org.springframework.beans.factory.annotation.Autowired + + +class DefaultECMHealthService extends ECMHealthService with ECMEventListener { + + val maxResource = new LoadInstanceResource(ECM_MAX_MEMORY_AVAILABLE, ECM_MAX_CORES_AVAILABLE, ECM_MAX_CREATE_INSTANCES) + val minResource = new LoadInstanceResource(ECM_PROTECTED_MEMORY, ECM_PROTECTED_CORES, ECM_PROTECTED_INSTANCES) + private val runtime: Runtime = Runtime.getRuntime + + private val future = Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = { + if (ECMApplication.isReady) { + reportHealth(getLastEMHealthReport) + } + } + }, ECM_HEALTH_REPORT_DELAY, ECM_HEALTH_REPORT_PERIOD, TimeUnit.SECONDS) + + @Autowired + private var engineConnListService: EngineConnListService = _ + + override def getLastEMHealthReport: ECMHealthReport = { + val report = new DefaultECMHealthReport + report.setNodeId(ECMApplication.getECMServiceInstance.toString) + report.setNodeStatus(NodeStatus.Running) + report.setTotalResource(maxResource) + report.setProtectedResource(minResource) + report.setUsedResource(engineConnListService.getUsedResources) + report.setReportTime(new Date().getTime) + report.setRunningEngineConns(ECMApplication.getContext.getECMMetrics.getRunningEngineConns) + val info = new NodeOverLoadInfo + info.setMaxMemory(runtime.maxMemory()) + info.setUsedMemory(runtime.totalMemory() - runtime.freeMemory()) + // TODO: 根据系统获取当前操作系统负载 + report.setOverload(info) + report + } + + // TODO: 可能还需要个判断health状态的方法 + + override def reportHealth(report: ECMHealthReport): Unit = { + val heartbeat: NodeHeartbeatMsg = transferECMHealthReportToNodeHeartbeatMsg(report) + Sender.getSender(MANAGER_SPRING_NAME).send(heartbeat) + } + + private def transferECMHealthReportToNodeHeartbeatMsg(report: ECMHealthReport) = { + val heartbeat = new NodeHeartbeatMsg + heartbeat.setOverLoadInfo(report.getOverload) + heartbeat.setStatus(report.getNodeStatus) + heartbeat.setServiceInstance(ECMApplication.getECMServiceInstance) + val resource = new CommonNodeResource + resource.setMaxResource(maxResource) + resource.setMinResource(minResource) + resource.setUsedResource(resource.getUsedResource) + heartbeat.setNodeResource(resource) + heartbeat.setHeartBeatMsg("") + val nodeHealthyInfo = new NodeHealthyInfo + nodeHealthyInfo.setMsg("") + nodeHealthyInfo.setNodeHealthy(NodeHealthy.Healthy) + heartbeat.setHealthyInfo(nodeHealthyInfo) + heartbeat + } + + override def generateHealthReport(reportTime: Long): ECMHealthReport = { + // TODO: 历史查询 + null + } + + private def emShutdownHealthReport(event: ECMClosedEvent): Unit = { + val report = getLastEMHealthReport + report.setNodeStatus(NodeStatus.ShuttingDown) + reportHealth(report) + } + + private def emReadyHealthReport(event: ECMReadyEvent): Unit = reportHealth(getLastEMHealthReport) + + + override def onEvent(event: ECMEvent): Unit = event match { + case event: ECMReadyEvent => + emReadyHealthReport(event) + case event: ECMClosedEvent => + cancelHealthReportThread(event) + emShutdownHealthReport(event) + presistenceLeftReports(event) + case _ => + } + + private def cancelHealthReportThread(event: ECMClosedEvent): Unit = { + + } + + private def presistenceLeftReports(event: ECMClosedEvent): Unit = { + // TODO: 持久化 剩余的reports + } + + @Receiver + override def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg = { + val hearlthReport = getLastEMHealthReport + transferECMHealthReportToNodeHeartbeatMsg(hearlthReport) + } + + + } diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala new file mode 100644 index 0000000000..9185b63055 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMMetricsService.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.service.ECMMetricsService + + +class DefaultECMMetricsService extends ECMMetricsService with ECMEventListener{ + override def onEvent(event: ECMEvent): Unit = ??? +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala new file mode 100644 index 0000000000..7607230a65 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultECMRegisterService.scala @@ -0,0 +1,99 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util +import java.util.Collections + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.listener.{ECMClosedEvent, ECMReadyEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.ECMRegisterService +import com.webank.wedatasphere.linkis.manager.common.entity.resource._ +import com.webank.wedatasphere.linkis.manager.common.protocol.em.{RegisterEMRequest, StopEMRequest} +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant +import com.webank.wedatasphere.linkis.rpc.Sender + + +class DefaultECMRegisterService extends ECMRegisterService with ECMEventListener with Logging { + + private implicit def readyEvent2RegisterECMRequest(event: ECMReadyEvent): RegisterEMRequest = { + val request = new RegisterEMRequest + val instance = Sender.getThisServiceInstance + request.setUser(Utils.getJvmUser) + request.setServiceInstance(instance) + request.setAlias(instance.getApplicationName) + request.setLabels(getLabelsFromArgs(event.params)) + request.setNodeResource(getEMRegiterResourceFromConfiguration) + request + } + + private def getLabelsFromArgs(params: Array[String]): util.Map[String, AnyRef] = { + import scala.collection.JavaConversions._ + val labelRegex = """label\.(.+)\.(.+)=(.+)""".r + val labels = new util.HashMap[String, AnyRef]() + // TODO: magic + labels += LabelKeyConstant.SERVER_ALIAS_KEY -> Collections.singletonMap("alias", ENGINE_CONN_MANAGER_SPRING_NAME) + // TODO: group by key + /* params.foreach { + case labelRegex(key, valueKey, valueContent) => labels += key -> (valueKey, valueContent) + case _ => + }*/ + labels + } + + private def getEMRegiterResourceFromConfiguration: NodeResource = { + val maxResource = new LoadInstanceResource(ECM_MAX_MEMORY_AVAILABLE, ECM_MAX_CORES_AVAILABLE, ECM_MAX_CREATE_INSTANCES) + val minResource = new LoadInstanceResource(ECM_PROTECTED_MEMORY, ECM_PROTECTED_CORES, ECM_PROTECTED_INSTANCES) + val nodeResource = new CommonNodeResource + nodeResource.setResourceType(ResourceType.LoadInstance) + nodeResource.setExpectedResource(Resource.getZeroResource(maxResource)) + nodeResource.setLeftResource(maxResource) + nodeResource.setLockedResource(Resource.getZeroResource(maxResource)) + nodeResource.setMaxResource(maxResource) + nodeResource.setMinResource(minResource) + nodeResource.setUsedResource(Resource.getZeroResource(maxResource)) + nodeResource + } + + override def onEvent(event: ECMEvent): Unit = event match { + case event: ECMReadyEvent => registerECM(event) + case event: ECMClosedEvent => unRegisterECM(event) + case _ => + } + + private implicit def closeEvent2StopECMRequest(event: ECMClosedEvent): StopEMRequest = { + val request = new StopEMRequest + val instance = Sender.getThisServiceInstance + request.setUser(Utils.getJvmUser) + request.setEm(instance) + request + } + + override def registerECM(request: RegisterEMRequest): Unit = { + info("start register ecm") + Sender.getSender(MANAGER_SPRING_NAME).send(request) + } + + override def unRegisterECM(request: StopEMRequest): Unit = { + info("start unRegister ecm") + Sender.getSender(MANAGER_SPRING_NAME).send(request) + } + +} + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java new file mode 100644 index 0000000000..bb139669a7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnKillService.java @@ -0,0 +1,139 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl; + +import com.webank.wedatasphere.linkis.common.ServiceInstance; +import com.webank.wedatasphere.linkis.common.utils.Utils; +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn; +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnKillService; +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnListService; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineStopRequest; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineStopResponse; +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineSuicideRequest; +import com.webank.wedatasphere.linkis.message.annotation.Receiver; +import com.webank.wedatasphere.linkis.rpc.Sender; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + + +public class DefaultEngineConnKillService implements EngineConnKillService { + + private static final Logger logger = LoggerFactory.getLogger(DefaultEngineConnKillService.class); + + private EngineConnListService engineConnListService; + + public void setEngineConnListService(EngineConnListService engineConnListService) { + this.engineConnListService = engineConnListService; + } + + @Override + @Receiver + public EngineStopResponse dealEngineConnStop(EngineStopRequest engineStopRequest) { + EngineConn engineConn = getEngineConnByServiceInstance(engineStopRequest.getServiceInstance()); + EngineStopResponse response = new EngineStopResponse(); + if (null != engineConn) { + if(!killEngineConnByPid(engineConn)) { + response.setStopStatus(false); + response.setMsg("Kill engine " + engineConn.getServiceInstance().toString() + " failed."); + } else { + response.setStopStatus(true); + response.setMsg("Kill engine " + engineConn.getServiceInstance().toString() + " succeed."); + } + } else { + logger.warn("Cannot find engineconn : " + engineStopRequest.getServiceInstance().toString() + " in this engineConnManager engineConn list, cannot kill."); + response.setStopStatus(false); + response.setMsg("EngineConn " + engineStopRequest.getServiceInstance().toString() + " was not found in this engineConnManager."); + } + if (!response.getStopStatus()) { + EngineSuicideRequest request = new EngineSuicideRequest(engineStopRequest.getServiceInstance(), engineStopRequest.getUser()); + try { + Sender.getSender(engineStopRequest.getServiceInstance()).send(request); + response.setStopStatus(true); + response.setMsg(response.getMsg() + " Now send suicide request to engine."); + } catch (Exception e) { + response.setMsg(response.getMsg() + " Sended suicide request to engine error, " + e.getMessage()); + } + } + return response; + } + + private EngineConn getEngineConnByServiceInstance(ServiceInstance serviceInstance) { + if (null == serviceInstance) { + return null; + } + List engineConnList = engineConnListService.getEngineConns(); + for (EngineConn engineConn : engineConnList) { + if (engineConn.getServiceInstance().equals(serviceInstance)) { + return engineConn; + } + } + return null; + } + + private boolean killEngineConnByPid(EngineConn engineConn) { + logger.info("try to kill {} toString with pid({}).", engineConn.getServiceInstance().toString(), engineConn.getPid()); + if (StringUtils.isNotBlank(engineConn.getPid())) { + String k15cmd = "sudo kill " + engineConn.getPid(); + String k9cmd = "sudo kill -9 " + engineConn.getPid(); + int tryNum = 1; + try { + while (isProcessAlive(engineConn.getPid()) && tryNum <= 3) { + logger.info("{} still alive with pid({}), use shell command to kill it. try {}++", engineConn.getServiceInstance().toString(), engineConn.getPid(), tryNum++); + if (tryNum < 3) { + Utils.exec(k15cmd.split(" "), 3000L); + } else { + Utils.exec(k9cmd.split(" "), 3000L); + } + Thread.sleep(3000); + } + } catch (InterruptedException e) { + logger.error("Interrupted while killing engine {} with pid({})." + engineConn.getServiceInstance().toString(), engineConn.getPid()); + } + if (isProcessAlive(engineConn.getPid())) { + return false; + } else { + return true; + } + } else { + logger.warn("cannot kill {} with empty pid.", engineConn.getServiceInstance().toString()); + return false; + } + } + + private boolean isProcessAlive(String pid) { + String findCmd = "\"ps -ef | grep " + pid + " | grep EngineConnServer | awk '{print \\\"exists_\\\"$2}' | grep " + pid + " \""; + List cmdList = new ArrayList<>(); + cmdList.add("sudo"); + cmdList.add("-S"); + cmdList.add("bash"); + cmdList.add("-c"); + cmdList.add(findCmd); + try { + // todo + String rs = Utils.exec(cmdList.toArray(new String[0]), 5000L); + return null != rs && rs.contains("exists_" + pid); + } catch (Exception e) { + logger.error("Method isProcessAlive failed, " + e.getMessage()); + } + return true; + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala new file mode 100644 index 0000000000..04d20229c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnListService.scala @@ -0,0 +1,124 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util +import java.util.concurrent.ConcurrentHashMap + +import com.google.common.collect.Interners +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.ecm.core.engineconn.{EngineConn, YarnEngineConn} +import com.webank.wedatasphere.linkis.ecm.core.launch.EngineConnLaunchRunner +import com.webank.wedatasphere.linkis.ecm.core.listener.{ECMEvent, ECMEventListener} +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.converter.ECMEngineConverter +import com.webank.wedatasphere.linkis.ecm.server.listener._ +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnListService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.resource.{Resource, ResourceType} + +import scala.collection.JavaConversions._ + + +class DefaultEngineConnListService extends EngineConnListService with ECMEventListener with Logging { + /** + * key:tickedId,value :engineConn + */ + private val engineConnMap = new ConcurrentHashMap[String, EngineConn] + + val lock = Interners.newWeakInterner[String] + + override def init(): Unit = {} + + override def getEngineConn(engineConnId: String): Option[EngineConn] = Option(engineConnMap.get(engineConnId)) + + override def getEngineConns: util.List[EngineConn] = engineConnMap.values().toList + + override def addEngineConn(engineConn: EngineConn): Unit = { + if (ECMApplication.isReady) + engineConnMap.put(engineConn.getTickedId, engineConn) + } + + override def killEngineConn(engineConnId: String): Unit = { + val conn = engineConnMap.remove(engineConnId) + if (conn != null) { + Utils.tryAndWarn{ + conn.close() + info(s"engineconn ${conn.getPid} was closed.") + } + } + } + + override def getUsedResources: Resource = engineConnMap.values().map(_.getResource.getMinResource).fold(Resource.initResource(ResourceType.Default))(_ + _) + + override def submit(runner: EngineConnLaunchRunner): Option[EngineConn] = ??? + + def updateYarnAppId(event: YarnAppIdCallbackEvent): Unit = { + updateYarnEngineConn(x => x.setApplicationId(event.protocol.applicationId), event.protocol.nodeId) + } + + def updateYarnEngineConn(implicit updateFunction: YarnEngineConn => Unit, nodeId: String): Unit = { + lock.intern(nodeId) synchronized { + engineConnMap.get(nodeId) match { + case e: YarnEngineConn => updateFunction(e) + case e: EngineConn => + engineConnMap.put(nodeId, ECMEngineConverter.engineConn2YarnEngineConn(e)) + } + } + } + + def updateEngineConn(updateFunction: EngineConn => Unit, nodeId: String): Unit = { + lock.intern(nodeId) synchronized { + engineConnMap.get(nodeId) match { + case e: EngineConn => updateFunction(e) + } + } + } + + def updateYarnInfo(event: YarnInfoCallbackEvent): Unit = { + updateYarnEngineConn(x => x.setApplicationURL(event.protocol.uri), event.protocol.nodeId) + } + + def updatePid(event: EngineConnPidCallbackEvent): Unit = { + updateEngineConn(x => { + x.setPid(event.protocol.pid) + x.setServiceInstance(event.protocol.serviceInstance) + }, event.protocol.ticketId) + } + + def updateEngineConnStatus(tickedId: String, updateStatus: NodeStatus): Unit = { + updateEngineConn(x => x.setStatus(updateStatus), tickedId) + } + + override def onEvent(event: ECMEvent): Unit = { + info(s"Deal event $event") + event match { + case event: ECMClosedEvent => shutdownEngineConns(event) + case event: YarnAppIdCallbackEvent => updateYarnAppId(event) + case event: YarnInfoCallbackEvent => updateYarnInfo(event) + case event: EngineConnPidCallbackEvent => updatePid(event) + case EngineConnAddEvent(engineConn) => addEngineConn(engineConn) + case EngineConnStatusChangeEvent(tickedId, updateStatus) => updateEngineConnStatus(tickedId, updateStatus) + case _ => + } + } + + private def shutdownEngineConns(event: ECMClosedEvent): Unit = { + engineConnMap.keys().foreach(killEngineConn) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala new file mode 100644 index 0000000000..1f0a6b3002 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnPidCallbackService.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnPidCallbackEvent +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnPidCallbackService +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.message.annotation.Receiver + + +class DefaultEngineConnPidCallbackService extends EngineConnPidCallbackService with Logging { + + @Receiver + override def dealPid(protocol: ResponseEngineConnPid): Unit = { + //1.设置pid + //2.设置serviceInstance + //3.状态为running + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnPidCallbackEvent(protocol)) + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala new file mode 100644 index 0000000000..bea04016bd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultEngineConnStatusCallbackService.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.MANAGER_SPRING_NAME +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnStatusChangeEvent +import com.webank.wedatasphere.linkis.ecm.server.service.EngineConnStatusCallbackService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus.{Failed, Running} +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineConnStatusCallback, EngineConnStatusCallbackToAM} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import org.springframework.stereotype.Service + + +@Service +class DefaultEngineConnStatusCallbackService extends EngineConnStatusCallbackService with Logging { + + @Receiver + override def dealEngineConnStatusCallback(protocol: EngineConnStatusCallback): Unit = { + info(s"Start to deal EngineConnStatusCallback $protocol") + + if (NodeStatus.isAvailable(protocol.status)) { + + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(protocol.ticketId, Running)) + } else { + + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(protocol.serviceInstance, + protocol.status, protocol.initErrorMsg)) + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(protocol.ticketId, Failed)) + } + + info(s"Finished to deal EngineConnStatusCallback $protocol") + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala new file mode 100644 index 0000000000..039a58f84e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultLocalDirsHandleService.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.io.File +import java.nio.file.Paths + +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration._ +import com.webank.wedatasphere.linkis.ecm.server.service.LocalDirsHandleService + + +class DefaultLocalDirsHandleService extends LocalDirsHandleService { + + // TODO: 检测当前磁盘的健康状态,如果目录满了,需要上报am + + override def cleanup(): Unit = ??? + + + override def getEngineConnManagerHomeDir: String = ECM_HOME_DIR + + override def getEngineConnWorkDir(user: String, ticketId: String): String = new FsPath(Paths.get(ENGINECONN_ROOT_DIR, user, "workDir", ticketId).toFile.getPath).getPath + + override def getEngineConnPublicDir: String = ENGINECONN_PUBLIC_DIR + + override def getEngineConnLogDir(user: String, ticketId: String): String = s"${getEngineConnWorkDir(user, ticketId)}${File.separator}logs" + + override def getEngineConnTmpDir(user: String, ticketId: String): String = s"${getEngineConnWorkDir(user, ticketId)}${File.separator}tmp" + + +} + + diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala new file mode 100644 index 0000000000..381a5276f6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/DefaultYarnCallbackService.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.listener.{YarnAppIdCallbackEvent, YarnInfoCallbackEvent} +import com.webank.wedatasphere.linkis.ecm.server.service.YarnCallbackService +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.protocol.callback.{YarnAPPIdCallbackProtocol, YarnInfoCallbackProtocol} + + +class DefaultYarnCallbackService extends YarnCallbackService { + + @Receiver + override def dealApplicationId(protocol: YarnAPPIdCallbackProtocol): Unit = { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(YarnAppIdCallbackEvent(protocol)) + } + + @Receiver + override def dealApplicationURI(protocol: YarnInfoCallbackProtocol): Unit = { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(YarnInfoCallbackEvent(protocol)) + } +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala new file mode 100644 index 0000000000..8dfcbedc9d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/LinuxProcessEngineConnLaunchService.scala @@ -0,0 +1,64 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import com.webank.wedatasphere.linkis.ecm.core.launch.{DiscoveryMsgGenerator, EngineConnLaunch, EurekaDiscoveryMsgGenerator} +import com.webank.wedatasphere.linkis.ecm.linux.launch.LinuxProcessEngineConnLaunch +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.{ENGINECONN_SPRING_NAME, _} +import com.webank.wedatasphere.linkis.manager.common.entity.node.EngineNode +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.entity.{EngineConnBuildRequest, EngineConnLaunchRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.message.conf.MessageSchedulerConf._ +import com.webank.wedatasphere.linkis.rpc.Sender + +import scala.concurrent.duration.Duration + + +class LinuxProcessEngineConnLaunchService extends ProcessEngineConnLaunchService { + + /** + * launchEngine启动一个引擎的方法 + * + * @param engineConnBuildRequest 封装了引擎启动的参数 + */ + @Receiver + def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest, smc: ServiceMethodContext): EngineNode = { + Sender.getSender(ENGINECONN_SPRING_NAME).ask(engineConnBuildRequest) match { + case request: EngineConnLaunchRequest if ENGINECONN_CREATE_DURATION._1 != 0L => + launchEngineConn(request, ENGINECONN_CREATE_DURATION._1) + case request: EngineConnLaunchRequest => + launchEngineConn(request, smc.getAttribute(DURATION_KEY).asInstanceOf[Duration]._1) + } + } + + override def launchEngineConn(engineConnBuildRequest: EngineConnBuildRequest): EngineNode = { + Sender.getSender(ENGINECONN_SPRING_NAME).ask(engineConnBuildRequest) match { + case request: EngineConnLaunchRequest => + launchEngineConn(request, ENGINECONN_CREATE_DURATION._1) + } + } + + def createDiscoveryMsgGenerator: DiscoveryMsgGenerator = new EurekaDiscoveryMsgGenerator + + override def createEngineConnLaunch: EngineConnLaunch = { + val launch = new LinuxProcessEngineConnLaunch + launch.setDiscoveryMsgGenerator(createDiscoveryMsgGenerator) + launch + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala new file mode 100644 index 0000000000..852499e754 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/service/impl/ProcessEngineConnLaunchService.scala @@ -0,0 +1,86 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.service.impl + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.ecm.core.engineconn.EngineConn +import com.webank.wedatasphere.linkis.ecm.core.launch.ProcessEngineConnLaunch +import com.webank.wedatasphere.linkis.ecm.server.ECMApplication +import com.webank.wedatasphere.linkis.ecm.server.conf.ECMConfiguration.MANAGER_SPRING_NAME +import com.webank.wedatasphere.linkis.ecm.server.exception.ECMErrorException +import com.webank.wedatasphere.linkis.ecm.server.listener.EngineConnStatusChangeEvent +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus._ +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallbackToAM +import com.webank.wedatasphere.linkis.rpc.Sender +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.exception.ExceptionUtils + +import scala.concurrent.duration.Duration +import scala.concurrent.{Future, TimeoutException} + + +abstract class ProcessEngineConnLaunchService extends AbstractEngineConnLaunchService { + + override def afterLaunch(conn: EngineConn, duration: Long): Unit = { + conn.getEngineConnLaunchRunner.getEngineConnLaunch match { + case launch: ProcessEngineConnLaunch => try { + processMonitorThread(conn, launch, duration) + } catch { + case e: ECMErrorException => + warn("EngineConn init failed", e) + val logPath = conn.getEngineConnManagerEnv.engineConnWorkDir + "/logs" + Sender.getSender(MANAGER_SPRING_NAME).send(EngineConnStatusCallbackToAM(conn.getServiceInstance, + NodeStatus.ShuttingDown, "Failed to start EngineConn, reason: " + ExceptionUtils.getRootCauseMessage(e) + s"You can go to this path($logPath) to find the reason or ask the administrator for help")) + } + case _ => + } + } + + private def processMonitorThread(engineConn: EngineConn, launch: ProcessEngineConnLaunch, timeout: Long): Unit = { + val isCompleted: EngineConn => Boolean = engineConn => engineConn.getStatus == Success || engineConn.getStatus == Failed + val tickedId = engineConn.getTickedId + Future { + val iterator = IOUtils.lineIterator(launch.getProcessInputStream, "utf-8") + while (!isCompleted(engineConn) && iterator.hasNext) { + println(s"${engineConn.getTickedId}:${iterator.next()}") + } + val exitCode = Option(launch.processWaitFor) + if (exitCode.exists(_ != 0)) { + // TODO: 错误日志获取 + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(tickedId, ShuttingDown)) + } else { + ECMApplication.getContext.getECMSyncListenerBus.postToAll(EngineConnStatusChangeEvent(tickedId, Success)) + } + } + Utils.tryThrow(Utils.waitUntil(() => engineConn.getStatus != Starting, Duration(timeout, TimeUnit.MILLISECONDS))) { + case e: TimeoutException => + throw new ECMErrorException(10000, s"wait for $engineConn initial timeout.") + case e: InterruptedException => //比如被ms cancel + throw new ECMErrorException(10000, s"wait for $engineConn initial interrupted.") + case t: Throwable => + error(s"unexpected error, now shutdown it.") + throw t + } + if (engineConn.getStatus == ShuttingDown) { + throw new ECMErrorException(10000, s"Failed to init $engineConn, status shutting down") + } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala new file mode 100644 index 0000000000..21e0b74ff5 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/spring/ECMSpringConfiguration.scala @@ -0,0 +1,118 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.spring + +import com.webank.wedatasphere.linkis.ecm.core.listener.ECMEventListener +import com.webank.wedatasphere.linkis.ecm.server.context.{DefaultECMContext, ECMContext} +import com.webank.wedatasphere.linkis.ecm.server.service._ +import com.webank.wedatasphere.linkis.ecm.server.service.impl._ +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.context.annotation.{Bean, Configuration} + + +@Configuration +class ECMSpringConfiguration { + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnManagerContext: ECMContext = { + new DefaultECMContext + } + + @Bean + @ConditionalOnMissingBean + def getDefaultYarnCallbackService: YarnCallbackService = { + new DefaultYarnCallbackService + } + + @Bean + @ConditionalOnMissingBean + def getBmlResourceLocalizationService(context: ECMContext, localDirsHandleService: LocalDirsHandleService): ResourceLocalizationService = { + val service: BmlResourceLocalizationService = new BmlResourceLocalizationService + service.setLocalDirsHandleService(localDirsHandleService) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultLogCallbackService: LogCallbackService = { + null + } + + @Bean + @ConditionalOnMissingBean + def getDefaultlocalDirsHandleService: LocalDirsHandleService = { + new DefaultLocalDirsHandleService + } + + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnPidCallbackService: EngineConnPidCallbackService = { + new DefaultEngineConnPidCallbackService + } + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnListService(context: ECMContext): EngineConnListService = { + implicit val service: DefaultEngineConnListService = new DefaultEngineConnListService + registerSyncListener(context) + service + } + + @Bean + @ConditionalOnMissingBean + def getLinuxProcessEngineConnLaunchService(resourceLocalizationService: ResourceLocalizationService): EngineConnLaunchService = { + val service = new LinuxProcessEngineConnLaunchService + service.setResourceLocalizationService(resourceLocalizationService) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultECMRegisterService(context: ECMContext): ECMRegisterService = { + implicit val service: DefaultECMRegisterService = new DefaultECMRegisterService + registerSyncListener(context) + service + } + + + @Bean + @ConditionalOnMissingBean + def getDefaultECMHealthService(context: ECMContext): ECMHealthService = { + implicit val service: DefaultECMHealthService = new DefaultECMHealthService + registerSyncListener(context) + service + } + + @Bean + @ConditionalOnMissingBean + def getDefaultEngineConnKillService(engineConnListService: EngineConnListService): EngineConnKillService = { + val service = new DefaultEngineConnKillService + service.setEngineConnListService(engineConnListService) + service + } + + private def registerSyncListener(context: ECMContext)(implicit listener: ECMEventListener): Unit = { + context.getECMSyncListenerBus.addListener(listener) + } + + private def registerASyncListener(context: ECMContext)(implicit listener: ECMEventListener): Unit = { + context.getECMAsyncListenerBus.addListener(listener) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala new file mode 100644 index 0000000000..0c41ac14bf --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/linkis-engineconn-manager-server/src/main/scala/com/webank/wedatasphere/linkis/ecm/server/util/ECMUtils.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ecm.server.util + +import java.io.{File, InputStream} +import java.util + +import com.webank.wedatasphere.linkis.bml.client.{BmlClient, BmlClientFactory} +import com.webank.wedatasphere.linkis.bml.protocol.BmlDownloadResponse +import com.webank.wedatasphere.linkis.ecm.server.exception.ECMErrorException +import com.webank.wedatasphere.linkis.manager.common.protocol.bml.BmlResource +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import org.apache.commons.io.{FileUtils, IOUtils} + +import scala.collection.JavaConversions._ + + +object ECMUtils { + + private def download(resource: BmlResource, userName: String): util.Map[String, Object] = { + val client: BmlClient = createBMLClient(userName) + var response: BmlDownloadResponse = null + if (resource.getVersion == null) { + response = client.downloadShareResource(userName, resource.getResourceId) + } else { + response = client.downloadShareResource(userName, resource.getResourceId, resource.getVersion) + } + if (!response.isSuccess) throw new ECMErrorException(911115, "下载失败") + val map = new util.HashMap[String, Object] + map += "path" -> response.fullFilePath + map += "is" -> response.inputStream + } + + def downLoadBmlResourceToLocal(resource: BmlResource, userName: String, path: String)(implicit fs: FileSystem): Unit = { + val is = download(resource, userName).get("is").asInstanceOf[InputStream] + val os = FileUtils.openOutputStream(new File(path + File.separator + resource.getFileName)) + IOUtils.copy(is, os) + IOUtils.closeQuietly(os) + IOUtils.closeQuietly(is) + } + + private def createBMLClient(userName: String): BmlClient = { + if (userName == null) + BmlClientFactory.createBmlClient() + else + BmlClientFactory.createBmlClient(userName) + } + + + private val address = Sender.getThisInstance.substring(0, Sender.getThisInstance.lastIndexOf(":")) + + def getInstanceByPort(port: String): String = address + ":" + port + +} diff --git a/linkis-computation-governance/linkis-engineconn-manager/pom.xml b/linkis-computation-governance/linkis-engineconn-manager/pom.xml new file mode 100644 index 0000000000..91420a63c0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn-manager/pom.xml @@ -0,0 +1,36 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-engineconn-manager + pom + + linkis-engineconn-manager-core + linkis-engineconn-manager-server + linkis-engineconn-linux-launch + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml new file mode 100644 index 0000000000..444957637e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/pom.xml @@ -0,0 +1,128 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-computation-engineconn + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-accessible-executor + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-resource-executor + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-callback-service + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-cs-engine-support + ${linkis.version} + + + reflections + org.reflections + + + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + com.google.guava + guava + ${guava.version} + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala new file mode 100644 index 0000000000..cc4661aaf7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/conf/ComputationExecutorConf.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{ByteType, CommonVars} + + +object ComputationExecutorConf { + + val ENGINECONN_RESULT_SET_STORE_PATH = CommonVars("wds.linkis.engineconn.resultSet.default.store.path", "hdfs:///tmp") + + val ENGINE_RESULT_SET_MAX_CACHE = CommonVars("wds.linkis.engine.resultSet.cache.max", new ByteType("0k")) + + val ENGINE_DEFAULT_LIMIT = CommonVars("wds.linkis.engine.default.limit", 5000) + + val ENGINE_LOCK_DEFAULT_EXPIRE_TIME = CommonVars("wds.linkis.engine.lock.expire.time", 2 * 60 * 1000) + + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala new file mode 100644 index 0000000000..dc07740049 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSEnginePreExecuteHook.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.cs.client.utils.ContextServiceUtils +import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationExecutorHook +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest + + +class CSEnginePreExecuteHook extends ComputationExecutorHook with Logging { + + private val csResourceParser: CSResourceParser = new CSResourceParser + + override def getHookName: String = "ContextServicePreHook" + + override def beforeExecutorExecute(engineExecutionContext: EngineExecutionContext, engineCreationContext: EngineCreationContext, code: String): String = { + val props = engineExecutionContext.getProperties + if (null != props && props.containsKey(CSCommonUtils.CONTEXT_ID_STR)) { + var parsedCode = code + val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap (props) + val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap (props) + engineExecutionContext.addProperty (CSCommonUtils.CONTEXT_ID_STR, contextIDValueStr) + engineExecutionContext.addProperty (CSCommonUtils.NODE_NAME_STR, nodeNameStr) + info (s"Start to call cs engine pre hook,contextID is $contextIDValueStr, nodeNameStr is $nodeNameStr") + parsedCode = csResourceParser.parse (props, parsedCode, contextIDValueStr, nodeNameStr) + info (s"Finished to call cs engine pre hook,contextID is $contextIDValueStr, nodeNameStr is $nodeNameStr") + parsedCode + } else { + code + } + } + + +} diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala similarity index 86% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala index df09dfc170..fb70c01b93 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSResourceParser.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSResourceParser.scala @@ -11,23 +11,18 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.cs - +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs import java.util import java.util.regex.Pattern import com.webank.wedatasphere.linkis.cs.client.service.CSResourceService -import com.webank.wedatasphere.linkis.engine.PropertiesExecuteRequest import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions._ import scala.collection.mutable.ArrayBuffer -/** - * @author peacewong - * @date 2020/3/5 19:42 - */ + class CSResourceParser { private val pb = Pattern.compile("cs://[^\\s\"]+[$\\s]{0,1}", Pattern.CASE_INSENSITIVE) @@ -41,7 +36,7 @@ class CSResourceParser { bmlResourceNames.toArray } - def parse(executeRequest: PropertiesExecuteRequest, code: String, contextIDValueStr: String, nodeNameStr: String): String = { + def parse(props: util.Map[String, Object], code: String, contextIDValueStr: String, nodeNameStr: String): String = { //TODO getBMLResource peaceWong val bmlResourceList = CSResourceService.getInstance().getUpstreamBMLResource(contextIDValueStr, nodeNameStr) @@ -66,7 +61,7 @@ class CSResourceParser { } } - executeRequest.properties.put("resources", parsedResources) + props.put("resources", parsedResources) StringUtils.replaceEach(code, preFixNames.toArray, parsedNames.toArray) } diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala similarity index 92% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala index e6c4dadc87..e2ff4593c6 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/cs/CSTableRegister.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/cs/CSTableRegister.scala @@ -11,10 +11,9 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.cs +package com.webank.wedatasphere.linkis.engineconn.computation.executor.cs import java.util.Date - import com.webank.wedatasphere.linkis.common.io.resultset.ResultSetWriter import com.webank.wedatasphere.linkis.common.io.{MetaData, Record} import com.webank.wedatasphere.linkis.common.utils.Logging @@ -24,22 +23,19 @@ import com.webank.wedatasphere.linkis.cs.common.entity.enumeration.{ContextScope import com.webank.wedatasphere.linkis.cs.common.entity.metadata.{CSColumn, CSTable} import com.webank.wedatasphere.linkis.cs.common.entity.source.CommonContextKey import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils -import com.webank.wedatasphere.linkis.engine.execute.EngineExecutorContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext import com.webank.wedatasphere.linkis.storage.domain.Column import com.webank.wedatasphere.linkis.storage.utils.StorageUtils import org.apache.commons.lang.StringUtils -/** - * @author peacewong - * @date 2020/3/13 16:29 - */ + object CSTableRegister extends Logging{ - def registerTempTable(engineExecutorContext: EngineExecutorContext, + def registerTempTable(engineExecutionContext: EngineExecutionContext, writer: ResultSetWriter[_ <: MetaData, _ <: Record], alias: String, columns: Array[Column]): Unit = { - val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap(engineExecutorContext.getProperties) - val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap(engineExecutorContext.getProperties) + val contextIDValueStr = ContextServiceUtils.getContextIDStrByMap(engineExecutionContext.getProperties) + val nodeNameStr = ContextServiceUtils.getNodeNameStrByMap(engineExecutionContext.getProperties) if (StringUtils.isNotBlank(contextIDValueStr) && StringUtils.isNotBlank(nodeNameStr)) { info(s"Start to register TempTable nodeName:$nodeNameStr") diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala new file mode 100644 index 0000000000..ef1e0cf3dc --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/CommonEngineConnTask.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +class CommonEngineConnTask(val taskId: String, var taskSupportRetry: Boolean = false) extends EngineConnTask { + + private var code: String = _ + private var prop: util.Map[String, Object] = _ + private var status: ExecutionNodeStatus = ExecutionNodeStatus.Inited + private var labels: Array[Label[_]] = new Array[Label[_]](0) + private var serviceInstance: ServiceInstance = _ + + override def getTaskId: String = taskId + + override def isTaskSupportRetry: Boolean = taskSupportRetry + + override def getCode: String = code + + override def setCode(code: String): Unit = this.code = code + + override def getProperties: util.Map[String, Object] = prop + + override def setProperties(properties: util.Map[String, Object]): Unit = this.prop = properties + + override def data(key: String, value: Object): Unit = this.prop.put(key, value) + + override def getStatus: ExecutionNodeStatus = status + + override def setStatus(status: ExecutionNodeStatus): Unit = this.status = status + + override def getLables: Array[Label[_]] = labels + + override def setLabels(labels: Array[Label[_]]): Unit = this.labels = labels + + override def getCallbackServiceInstance(): ServiceInstance = serviceInstance + + override def setCallbackServiceInstance(serviceInstance: ServiceInstance): Unit = this.serviceInstance = serviceInstance +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala new file mode 100644 index 0000000000..3f5e957789 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/EngineConnTask.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineConnTask { + + def getTaskId: String + + def isTaskSupportRetry: Boolean + + def getCode: String + + def setCode(code: String): Unit + + def getProperties: util.Map[String, Object] + + def setProperties(properties: util.Map[String, Object]) + + def data(key: String, value: Object): Unit + + def getStatus: ExecutionNodeStatus + + def setStatus(taskStatus: ExecutionNodeStatus): Unit + + + def getLables: Array[Label[_]] + + def setLabels(labels: Array[Label[_]]): Unit + + def getCallbackServiceInstance(): ServiceInstance + + def setCallbackServiceInstance(serviceInstance: ServiceInstance): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala new file mode 100644 index 0000000000..dd150e5fe0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/entity/TaskStatus.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.entity + + +object TaskStatus extends Enumeration { + + type TaskStatus = Value + val PENDING = Value(0) + val RUNNING = Value(1) + val SUCCESS = Value(2) + val ERROR = Value(3) + val CANCEL = Value(4) + + def isCompleted(status: TaskStatus): Boolean = { + if (status == PENDING || status == RUNNING) false + else true + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala new file mode 100644 index 0000000000..32b23d104c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationEngineConnExecution.scala @@ -0,0 +1,84 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.common.execution.EngineExecution +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, ResourceExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper + + +class ComputationEngineConnExecution extends EngineExecution with Logging { + + private val executorManager: ExecutorManager = ExecutorManager.getInstance() + + /** + * 创建出默认的Executor + * + * @param engineCreationContext + * @param engineConn + */ + override def execute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + Utils.tryCatch{ + init(engineCreationContext) + val defaultExecutor = executorManager.getDefaultExecutor.asInstanceOf[ComputationExecutor] + reportUsedResource(defaultExecutor, engineCreationContext) + reportLabel(defaultExecutor.getExecutorLabels()) + info(s"Engine Executor ${defaultExecutor.getId()} started.") + info("Debug: engineCreationContext: " + BDPJettyServerHelper.gson.toJson(engineCreationContext)) + }{ + t => + error(s"Init executor error. ", t) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INIT_EXECUTOR_FAILED, "Init executor failed. ", t) + } + } + + private def init(engineCreationContext: EngineCreationContext): Unit = { + // msContext.getPublisher.publish(RequestTaskExecute) + val listenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext + listenerBusContext.getEngineConnAsyncListenerBus.start() + } + + private def reportUsedResource(executor: Executor, engineCreationContext: EngineCreationContext): Unit = { + Utils.tryCatch( + executor match { + case resourceExecutor: ResourceExecutor => + ManagerService.getManagerService.reportUsedResource(ResourceUsedProtocol(Sender.getThisServiceInstance, resourceExecutor.getCurrentNodeResource(), engineCreationContext.getTicketId)) + case _ => + info("do not to report usedResource") + } + ) { + t => error("ReportUsedResource error. cause: " + t.getCause) + } + } + + private def reportLabel(labels: util.List[Label[_]]): Unit = { + ManagerService.getManagerService.labelReport(labels) + info("Reported label to am.") + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala new file mode 100644 index 0000000000..c10fcf5f7b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ComputationExecutor.scala @@ -0,0 +1,271 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.util.concurrent.TimeUnit + +import com.google.common.cache.{Cache, CacheBuilder} +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.common.conf.{EngineConnConf, EngineConnConstant} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.EngineConnTask +import com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationExecutorHook +import com.webank.wedatasphere.linkis.engineconn.computation.executor.parser.CodeParser +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{LabelExecutor, ResourceExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{EngineConcurrentInfo, RequestTask} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.ExecutorFactory +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.scheduler.executer._ +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.exception.ExceptionUtils + + +abstract class ComputationExecutor(val outputPrintLimit: Int = 1000) extends AccessibleExecutor with ResourceExecutor with LabelExecutor with Logging { + + private val listenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext + + // private val taskMap: util.Map[String, EngineConnTask] = new ConcurrentHashMap[String, EngineConnTask](8) + private val taskCache: Cache[String, EngineConnTask] = CacheBuilder.newBuilder().expireAfterAccess(EngineConnConf.ENGINE_TASK_EXPIRE_TIME.getValue, TimeUnit.MILLISECONDS) + .maximumSize(EngineConnConstant.MAX_TASK_NUM).build() + + private var engineInitialized: Boolean = false + + private var codeParser: Option[CodeParser] = None + + private var runningTasks: Int = 0 + + private var pendingTasks: Int = 0 + + private var succeedTasks: Int = 0 + + private var failedTasks: Int = 0 + + private var lastTask: EngineConnTask = null + + final override def tryReady: Boolean = { + transition(NodeStatus.Unlock) + if (!engineInitialized) { + engineInitialized = true + } + true + } + + + override def init: Unit = { + info(s"executor($getId()) is ready ") + tryReady + } + + def tryShutdown(): Boolean = { + this.ensureAvailable(transition(NodeStatus.ShuttingDown)) + close() + true + } + + def tryFailed(): Boolean = { + this.whenStatus(NodeStatus.ShuttingDown, transition(NodeStatus.Failed)) + true + } + + + def getSucceedNum = succeedTasks + + def getFailedNum = failedTasks + + def getRunningTask: Int = runningTasks + + private def getExecutorConcurrentInfo: EngineConcurrentInfo = EngineConcurrentInfo(runningTasks, pendingTasks, succeedTasks, failedTasks) + + def isEngineInitialized = engineInitialized + + protected def callback(): Unit = {} + + override def close(): Unit = { + if (null != lastTask) synchronized { + killTask(lastTask.getTaskId) + } else { + killTask("By close") + } + super.close() + } + + // override def getName: String = ComputationExecutorConf.DEFAULT_COMPUTATION_NAME + + protected def ensureOp[A](f: => A): A = if (!this.engineInitialized) + f + else ensureIdle(f) + + def execute(engineConnTask: EngineConnTask): ExecuteResponse = { + + runningTasks += 1 + + taskCache.put(engineConnTask.getTaskId, engineConnTask) + lastTask = engineConnTask + + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Running) + + ensureOp { + val engineExecutionContext = createEngineExecutionContext(engineConnTask) + var hookedCode = engineConnTask.getCode + Utils.tryCatch { + val engineCreationContext = EngineConnManager.getEngineConnManager.getEngineConn().getEngineCreationContext + ComputationExecutorHook.getComputationExecutorHooks.foreach(hook => { + hookedCode = hook.beforeExecutorExecute(engineExecutionContext, engineCreationContext, hookedCode) + }) + } { + case e: Throwable => logger.info("failed to do with hook", e) + } + if (hookedCode.length > 100) { + info(s"hooked after code: ${hookedCode.substring(0, 100)} ....") + } else { + info(s"hooked after code: $hookedCode ") + } + val localPath = System.getenv(EngineConnConf.ENGINE_CONN_LOCAL_LOG_DIRS_KEY.getValue) + engineExecutionContext.appendStdout(s"EngineConn local log path : ${DataWorkCloudApplication.getServiceInstance.toString} ${localPath}") + var response: ExecuteResponse = null + val incomplete = new StringBuilder + val codes = Utils.tryCatch(getCodeParser().map(_.parse(hookedCode, engineExecutionContext)).getOrElse(Array(hookedCode))) { e => + info("Your code will be submitted in overall mode") + Array(hookedCode) + } + engineExecutionContext.setTotalParagraph(codes.length) + codes.indices.foreach({ + index => + if (ExecutionNodeStatus.Cancelled == engineConnTask.getStatus) return ErrorExecuteResponse("Job is killed by user!", null) + val code = codes(index) + engineExecutionContext.setCurrentParagraph(index + 1) + response = Utils.tryCatch(if (incomplete.nonEmpty) executeCompletely(engineExecutionContext, code, incomplete.toString()) + else executeLine(engineExecutionContext, code) + ) { + t => ErrorExecuteResponse(ExceptionUtils.getRootCauseMessage(t), t) + } + info(s"Finished to execute task ${engineConnTask.getTaskId}") + incomplete ++= code + response match { + case e: ErrorExecuteResponse => + failedTasks += 1 + error("execute code failed!", e.t) + return response + case SuccessExecuteResponse() => + engineExecutionContext.appendStdout("\n") + incomplete.setLength(0) + case e: OutputExecuteResponse => + incomplete.setLength(0) + val output = if (StringUtils.isNotEmpty(e.getOutput) && e.getOutput.length > outputPrintLimit) + e.getOutput.substring(0, outputPrintLimit) else e.getOutput + engineExecutionContext.appendStdout(output) + if (StringUtils.isNotBlank(e.getOutput)) engineExecutionContext.sendResultSet(e) + case _: IncompleteExecuteResponse => + incomplete ++= incompleteSplitter + } + }) + Utils.tryCatch(engineExecutionContext.close()) { + t => + response = ErrorExecuteResponse("send resultSet to entrance failed!", t) + failedTasks += 1 + } + runningTasks -= 1 + lastTask = null + response match { + case _: OutputExecuteResponse => + succeedTasks += 1 + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Succeed) + SuccessExecuteResponse() + case s: SuccessExecuteResponse => + succeedTasks += 1 + transformTaskStatus(engineConnTask, ExecutionNodeStatus.Succeed) + s + case _ => response + } + } + + + } + + def setCodeParser(codeParser: CodeParser) = this.codeParser = Some(codeParser) + + def getCodeParser(): Option[CodeParser] = this.codeParser + + def executeLine(engineExecutorContext: EngineExecutionContext, code: String): ExecuteResponse + + protected def incompleteSplitter = "\n" + + def executeCompletely(engineExecutorContext: EngineExecutionContext, code: String, completedLine: String): ExecuteResponse + + def progress(): Float + + def getProgressInfo: Array[JobProgressInfo] + + protected def createEngineExecutionContext(engineConnTask: EngineConnTask): EngineExecutionContext = { + val userCreator = ExecutorFactory.parseUserWithCreator(engineConnTask.getLables) + + val engineExecutionContext = if (null != userCreator && StringUtils.isNotBlank(userCreator.user)) { + new EngineExecutionContext(this, userCreator.user) + } else { + new EngineExecutionContext(this) + } + if (engineConnTask.getProperties.containsKey(RequestTask.RESULT_SET_STORE_PATH)) { + engineExecutionContext.setStorePath(engineConnTask.getProperties.get(RequestTask.RESULT_SET_STORE_PATH).toString) + } + engineExecutionContext.setJobId(engineConnTask.getTaskId) + engineExecutionContext.getProperties.putAll(engineConnTask.getProperties) + engineExecutionContext.setLabels(engineConnTask.getLables) + engineExecutionContext + } + + def killTask(taskId: String): Unit = { + Utils.tryAndWarn { + val task = taskCache.getIfPresent(taskId) + task.setStatus(ExecutionNodeStatus.Cancelled) + if (null != task) { + transformTaskStatus(task, ExecutionNodeStatus.Cancelled) + } + } + } + + def transformTaskStatus(task: EngineConnTask, newStatus: ExecutionNodeStatus) = { + val oriStatus = task.getStatus + oriStatus match { + case ExecutionNodeStatus.Scheduled => + if (task.getStatus != newStatus) { + task.setStatus(newStatus) + } + case ExecutionNodeStatus.Running => + if (newStatus == ExecutionNodeStatus.Succeed || newStatus == ExecutionNodeStatus.Failed || newStatus == ExecutionNodeStatus.Cancelled) { + task.setStatus(newStatus) + } else { + error(s"Task status change error. task: ${task}, newStatus : ${newStatus}") + } + case _ => + error(s"Task status change error. task: ${task}, newStatus : ${newStatus}") + } + if (oriStatus != newStatus) { + listenerBusContext.getEngineConnSyncListenerBus.postToAll(TaskStatusChangedEvent(task.getTaskId, oriStatus, newStatus)) + } + } + + def getTaskById(taskId: String): EngineConnTask = { + taskCache.getIfPresent(taskId) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala new file mode 100644 index 0000000000..c8bfe2c597 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/ConcurrentComputationExecutor.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.EngineConnTask +import com.webank.wedatasphere.linkis.engineconn.executor.entity.ConcurrentExecutor +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteResponse + + +abstract class ConcurrentComputationExecutor(override val outputPrintLimit: Int = 1000) extends ComputationExecutor(outputPrintLimit) with ConcurrentExecutor { + + override def execute(engineConnTask: EngineConnTask): ExecuteResponse = { + if (getRunningTask >= getConcurrentLimit) synchronized { + if (getRunningTask >= getConcurrentLimit) { + info(s"running task($getRunningTask) > concurrent limit $getConcurrentLimit, now to mark engine to busy ") + transition(NodeStatus.Busy) + } + } + val response = super.execute(engineConnTask) + if (getStatus == NodeStatus.Busy && getConcurrentLimit > getRunningTask) synchronized { + if (getStatus == NodeStatus.Busy && getConcurrentLimit > getRunningTask) { + info(s"running task($getRunningTask) < concurrent limit $getConcurrentLimit, now to mark engine to Unlock ") + transition(NodeStatus.Unlock) + } + } + response + } + + protected override def ensureOp[A](f: => A): A = if (!isEngineInitialized) + f + else ensureIdle(f, false) +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala new file mode 100644 index 0000000000..5e268f682b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/execute/EngineExecutionContext.scala @@ -0,0 +1,217 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.execute + +import java.io.File +import java.util +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.io.resultset.{ResultSet, ResultSetWriter} +import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.cs.client.utils.ContextServiceUtils +import com.webank.wedatasphere.linkis.cs.storage.CSTableResultSetWriter +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{TaskLogUpdateEvent, TaskProgressUpdateEvent, TaskResultCreateEvent, TaskResultSizeCreatedEvent} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.conf.ComputationExecutorConf +import com.webank.wedatasphere.linkis.engineconn.executor.listener.{EngineConnAsyncListenerBus, EngineConnSyncListenerBus, ExecutorListenerBusContext} +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.EngineConnExecutorErrorException +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.scheduler.executer.{AliasOutputExecuteResponse, OutputExecuteResponse} +import com.webank.wedatasphere.linkis.storage.resultset.table.TableResultSet +import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetWriter} +import com.webank.wedatasphere.linkis.storage.{LineMetaData, LineRecord} +import org.apache.commons.io.IOUtils +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.time.DateFormatUtils + +import scala.collection.mutable.ArrayBuffer + + +class EngineExecutionContext(executor: ComputationExecutor, executorUser: String = Utils.getJvmUser) extends Logging { + + private val resultSetFactory = ResultSetFactory.getInstance + + private val resultSetWriters = ArrayBuffer[ResultSetWriter[_ <: MetaData, _ <: Record]]() + + private var defaultResultSetWriter: ResultSetWriter[_ <: MetaData, _ <: Record] = _ + + private var resultSize = 0 + + private var interrupted = false + + private var jobId: Option[String] = None + private val aliasNum = new AtomicInteger(0) + protected var storePath: Option[String] = None + + private val properties: java.util.Map[String, Object] = new util.HashMap[String, Object]() + + private var labels: Array[Label[_]] = new Array[Label[_]](0) + + private var totalParagraph = 0 + private var currentParagraph = 0 + + def kill(): Unit = interrupted = true + + def isKilled: Boolean = interrupted + + def getTotalParagraph: Int = totalParagraph + + def setTotalParagraph(totalParagraph: Int): Unit = this.totalParagraph = totalParagraph + + def getCurrentParagraph: Int = currentParagraph + + def setCurrentParagraph(currentParagraph: Int): Unit = this.currentParagraph = currentParagraph + + def pushProgress(progress: Float, progressInfo: Array[JobProgressInfo]): Unit = { + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + listenerBus.postToAll(TaskProgressUpdateEvent(jId, progress, progressInfo)) + }) + } + + def sendResultSet(resultSetWriter: ResultSetWriter[_ <: MetaData, _ <: Record]): Unit = { + info("Start to send res to entrance") + val fileName = new File(resultSetWriter.toFSPath.getPath).getName + val index = if (fileName.indexOf(".") < 0) fileName.length else fileName.indexOf(".") + val alias = if (fileName.startsWith("_")) fileName.substring(1, index) else fileName.substring(0, fileName.indexOf("_")) + Utils.tryFinally(sendResultSet(resultSetWriter.toString(), alias)) { + IOUtils.closeQuietly(resultSetWriter) + resultSetWriters synchronized resultSetWriters -= resultSetWriter + } + } + + def sendResultSet(output: String): Unit = sendResultSet(output, "_" + aliasNum.getAndIncrement()) + + def appendTextResultSet(output: String): Unit = { + if (defaultResultSetWriter == null) aliasNum synchronized { + if (defaultResultSetWriter == null) { + defaultResultSetWriter = createDefaultResultSetWriter(ResultSetFactory.TEXT_TYPE) + defaultResultSetWriter.addMetaData(new LineMetaData()) + resultSetWriters += defaultResultSetWriter + } + } + defaultResultSetWriter.addRecord(new LineRecord(output)) + } + + private def sendResultSet(output: String, alias: String): Unit = { + if (StringUtils.isEmpty(output)) return + if (resultSetFactory.isResultSetPath(output) || resultSetFactory.isResultSet(output)) { + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + //TODO peacewong executor.getEngineServerContext().getEngineAsyncListenerBus().post(ResultSetCreatedEvent(jId, output, alias)) + listenerBus.postToAll(TaskResultCreateEvent(jId, output, alias)) + resultSize += 1 + }) + } else throw new EngineConnExecutorErrorException(50050, "unknown resultSet: " + output) + } + + def setJobId(jobId: String) = this.jobId = Option(jobId) + + def getJobId = jobId + + def setStorePath(storePath: String) = this.storePath = Option(storePath) + + def getLables: Array[Label[_]] = labels + + def setLabels(labels: Array[Label[_]]): Unit = this.labels = labels + + def sendResultSet(outputExecuteResponse: OutputExecuteResponse): Unit = outputExecuteResponse match { + case AliasOutputExecuteResponse(alias, output) => sendResultSet(output, alias) + case output: OutputExecuteResponse => sendResultSet(output.getOutput, "_" + aliasNum.getAndIncrement()) + } + + def getProperties: java.util.Map[String, Object] = properties + + def addProperty(key: String, value: String): Unit = properties.put(key, value) + + protected def getDefaultStorePath: String = { + val path = ComputationExecutorConf.ENGINECONN_RESULT_SET_STORE_PATH.getValue + (if (path.endsWith("/")) path else path + "/") + Utils.getJvmUser + "/" + + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + "/" + getJobId.get + "/" + System.nanoTime + } + + def createDefaultResultSetWriter(): ResultSetWriter[_ <: MetaData, _ <: Record] = { + // createResultSetWriter(resultSetFactory.getResultSetByType(engine.getDefaultResultSetType)) + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetFactory.getResultSetType(0))) // todo check + } + + def createDefaultResultSetWriter(alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetFactory.getResultSetType(0)), alias) // todo check + + def createResultSetWriter(resultSetType: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetType), null) + + def createResultSetWriter(resultSet: ResultSet[_ <: MetaData, _ <: Record]): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSet, null) + + def createResultSetWriter(resultSetType: String, alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = + createResultSetWriter(resultSetFactory.getResultSetByType(resultSetType), alias) + + def createResultSetWriter(resultSet: ResultSet[_ <: MetaData, _ <: Record], alias: String): ResultSetWriter[_ <: MetaData, _ <: Record] = { + val filePath = storePath.getOrElse(getDefaultStorePath) + val fileName = if (StringUtils.isEmpty(alias)) "_" + aliasNum.getAndIncrement() else alias + "_" + aliasNum.getAndIncrement() + val resultSetPath = resultSet.getResultSetPath(new FsPath(filePath), fileName) + //update by peaceWong 20200402 + val resultSetWriter = resultSet match { + case result: TableResultSet => + val contextIDStr = ContextServiceUtils.getContextIDStrByMap(getProperties) + val nodeName = ContextServiceUtils.getNodeNameStrByMap(getProperties) + if (StringUtils.isNotBlank(contextIDStr) && StringUtils.isNotBlank(nodeName)) { + val csWriter = new CSTableResultSetWriter(result, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, contextIDStr, nodeName, alias) + csWriter.setProxyUser(executorUser) + csWriter + } else { + ResultSetWriter.getResultSetWriter(resultSet, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, executorUser) + } + case _ => ResultSetWriter.getResultSetWriter(resultSet, ComputationExecutorConf.ENGINE_RESULT_SET_MAX_CACHE.getValue.toLong, resultSetPath, executorUser) + } + //update by peaceWong 20200402 end + resultSetWriters synchronized resultSetWriters += resultSetWriter + resultSetWriter + } + + def appendStdout(log: String): Unit = if (!executor.isEngineInitialized) { + executor.info(log) + } else { + val listenerBus = getEngineSyncListenerBus + // jobId.foreach(jId => listenerBus.post(TaskLogUpdateEvent(jId, log))) + jobId.foreach(jId => listenerBus.postToAll(TaskLogUpdateEvent(jId, log))) + } + + def sendProgress(progress: Float, progressInfos: Array[JobProgressInfo]): Unit = { + if (executor.isEngineInitialized) { + val listenerBus = getEngineSyncListenerBus + // jobId.foreach(jId => listenerBus.post(TaskProgressUpdateEvent(jId, progress, progressInfos))) + jobId.foreach(jId => listenerBus.postToAll(TaskProgressUpdateEvent(jId, progress, progressInfos))) + } + } + + def close(): Unit = { + resultSetWriters.toArray.foreach(sendResultSet) + val listenerBus = getEngineSyncListenerBus + jobId.foreach(jId => { + listenerBus.postToAll(TaskResultSizeCreatedEvent(jId, resultSize)) + }) + resultSetWriters.clear() + } + + private def getEngineAsyncListenerBus: EngineConnAsyncListenerBus = { + ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + } + + private def getEngineSyncListenerBus: EngineConnSyncListenerBus = { + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnSyncListenerBus + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala new file mode 100644 index 0000000000..6c594899e6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationEngineConnHook.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.hook + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.conf.DWCArgumentsParser +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.callback.service.{EngineConnAfterStartCallback, EngineConnPidCallback} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.common.hook.EngineConnHook +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnStatusCallback +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration +import org.apache.commons.lang.StringUtils +import org.apache.commons.lang.exception.ExceptionUtils + + +class ComputationEngineConnHook extends EngineConnHook with Logging { + + override def beforeCreateEngineConn(engineCreationContext: EngineCreationContext): Unit = { + info("<----------Start Spring app---------->") + val parser = DWCArgumentsParser.parse(engineCreationContext.getArgs) + DWCArgumentsParser.setDWCOptionMap(parser.getDWCConfMap) + val existsExcludePackages = ServerConfiguration.BDP_SERVER_EXCLUDE_PACKAGES.getValue + if (!StringUtils.isEmpty(existsExcludePackages)) + DataWorkCloudApplication.setProperty(ServerConfiguration.BDP_SERVER_EXCLUDE_PACKAGES.key, existsExcludePackages) + // 加载spring类 + DataWorkCloudApplication.main(DWCArgumentsParser.formatSpringOptions(parser.getSpringConfMap)) + + val engineConnPidCallBack = new EngineConnPidCallback(engineCreationContext.getEMInstance) + Utils.tryAndError(engineConnPidCallBack.callback()) + info("<----------Spring app init success---------->") + } + + + override def beforeExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = {} + + override def afterExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = {} + + override def afterEngineServerStartFailed(engineCreationContext: EngineCreationContext, throwable: Throwable): Unit = { + + val engineConnAfterStartCallback = new EngineConnAfterStartCallback(engineCreationContext.getEMInstance) + engineConnAfterStartCallback.callback(EngineConnStatusCallback(Sender.getThisServiceInstance, + engineCreationContext.getTicketId, NodeStatus.ShuttingDown, ExceptionUtils.getRootCauseMessage(throwable))) + error("init engineConn failed! now exit", throwable) + ShutdownHook.getShutdownHook.notifyError(throwable) + } + + override def afterEngineServerStartSuccess(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + val engineConnAfterStartCallback = new EngineConnAfterStartCallback(engineCreationContext.getEMInstance) + engineConnAfterStartCallback.callback(EngineConnStatusCallback(Sender.getThisServiceInstance, + engineCreationContext.getTicketId, NodeStatus.Unlock, "success")) + warn("init engineConn success!") + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala new file mode 100644 index 0000000000..90a47ceffd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/hook/ComputationExecutorHook.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.hook + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.ExecutorFactory +import org.reflections.Reflections + +import scala.collection.JavaConverters.asScalaSetConverter +import scala.collection.mutable.ArrayBuffer + + +trait ComputationExecutorHook { + + def getHookName(): String + + def beforeExecutorExecute(engineExecutionContext: EngineExecutionContext, engineCreationContext: EngineCreationContext, codeBeforeHook: String): String = codeBeforeHook + +// def afterExecutorExecute(engineExecutionContext: EngineExecutionContext, code: String): Unit +} + +object ComputationExecutorHook extends Logging { + + private lazy val computationExecutorHooks: Array[ComputationExecutorHook] = initComputationExecutorHook + + private def initComputationExecutorHook: Array[ComputationExecutorHook] = { + val hooks = new ArrayBuffer[ComputationExecutorHook] + Utils.tryCatch { + val reflections = new Reflections("com.webank.wedatasphere.linkis.engineconn.computation", classOf[ComputationExecutorHook]) + val allSubClass = reflections.getSubTypesOf(classOf[ComputationExecutorHook]) + allSubClass.asScala.foreach(l => { + hooks += l.newInstance + }) + } { + t: Throwable => + error(t.getMessage) + } + hooks.toArray + } + + def getComputationExecutorHooks = computationExecutorHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala new file mode 100644 index 0000000000..8bce49bf30 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/ResultSetListener.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{TaskResultCreateEvent, TaskResultSizeCreatedEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait ResultSetListener extends EngineConnSyncListener { + + def onResultSetCreated(taskResultCreateEvent: TaskResultCreateEvent): Unit + + def onResultSizeCreated(taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala new file mode 100644 index 0000000000..4c34719fb6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskProgressListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskProgressUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait TaskProgressListener extends EngineConnSyncListener { + + def onProgressUpdate(taskProgressUpdateEvent: TaskProgressUpdateEvent) + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala new file mode 100644 index 0000000000..a2db53e4df --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/listener/TaskStatusListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + + +trait TaskStatusListener extends EngineConnSyncListener { + + def onTaskStatusChanged(taskStatusChangedEvent: TaskStatusChangedEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala new file mode 100644 index 0000000000..2f9af2483f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/parser/CodeParser.scala @@ -0,0 +1,235 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.parser + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.computation.executor.conf.ComputationExecutorConf +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.parser.CodeType.CodeType +import org.apache.commons.lang.StringUtils +import org.slf4j.{Logger, LoggerFactory} + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + + +trait CodeParser { + + def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] + +} + +abstract class SingleCodeParser extends CodeParser { + val codeType: CodeType + + def canParse(codeType: String): Boolean = { + CodeType.getType(codeType) == this.codeType + } +} + +abstract class CombinedEngineCodeParser extends CodeParser { + val parsers: Array[SingleCodeParser] + + def getCodeType(code: String, engineExecutorContext: EngineExecutionContext): String + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + val codeType = getCodeType(code, engineExecutorContext) + parsers.find(_.canParse(codeType)) match { + case Some(parser) => parser.parse(code, engineExecutorContext) + case None => Array(code) + } + } +} + +class ScalaCodeParser extends SingleCodeParser with Logging { + + override val codeType: CodeType = CodeType.Scala + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val codeBuffer = new ArrayBuffer[String]() + val statementBuffer = new ArrayBuffer[String]() + code.split("\n").foreach { + case "" => + case l if l.startsWith(" ") || l.startsWith("\t") => if (!l.trim.startsWith("//")) statementBuffer.append(l) + case l if l.startsWith("@") => statementBuffer.append(l) + case l if StringUtils.isNotBlank(l) => + if (l.trim.startsWith("}")) { + statementBuffer.append(l) + } else { + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + statementBuffer.clear() + //statementBuffer.append("%scala") + statementBuffer.append(l) + } + case _ => + } + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + codeBuffer.toArray + } +} + +class PythonCodeParser extends SingleCodeParser { + + override val codeType: CodeType = CodeType.Python + val openBrackets = Array("{", "(", "[") + val closeBrackets = Array("}", ")", "]") + val LOG: Logger = LoggerFactory.getLogger(getClass) + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val bracketStack = new mutable.Stack[String] + val codeBuffer = new ArrayBuffer[String]() + val statementBuffer = new ArrayBuffer[String]() + var notDoc = true + //quotationMarks is used to optimize the three quotes problem(quotationMarks用来优化三引号问题) + var quotationMarks: Boolean = false + code.split("\n").foreach { + case "" => + case l if l.trim.contains("\"\"\"") || l.trim.contains("""'''""") => quotationMarks = !quotationMarks + statementBuffer.append(l) + recordBrackets(bracketStack, l) + case l if quotationMarks => statementBuffer.append(l) + //shanhuang 用于修复python的引号问题 + //recordBrackets(bracketStack, l) + case l if notDoc && l.startsWith("#") => + case l if StringUtils.isNotBlank(statementBuffer.last) && statementBuffer.last.endsWith("""\""") => + statementBuffer.append(l) + case l if notDoc && l.startsWith(" ") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("\t") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("@") => + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("else") => //LOG.info("I am else") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && l.startsWith("elif") => //LOG.info("I am elif") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case l if notDoc && StringUtils.isNotBlank(l) => + if (statementBuffer.nonEmpty && bracketStack.isEmpty) { + codeBuffer.append(statementBuffer.mkString("\n")) + statementBuffer.clear() + } + // statementBuffer.append("%python") + statementBuffer.append(l) + recordBrackets(bracketStack, l.trim) + case _ => + } + if (statementBuffer.nonEmpty) codeBuffer.append(statementBuffer.mkString("\n")) + codeBuffer.toArray + } + + def recordBrackets(bracketStack: mutable.Stack[String], l: String): Unit = { + val real = l.replace("\"\"\"", "").replace("'''", "").trim + if (StringUtils.endsWithAny(real, openBrackets)) { + for (i <- (0 to real.length - 1).reverse) { + val token = real.substring(i, i + 1) + if (openBrackets.contains(token)) { + bracketStack.push(token) + } + } + } + if (StringUtils.startsWithAny(real, closeBrackets)) { + for (i <- 0 to real.length - 1) { + val token = real.substring(i, i + 1) + if (closeBrackets.contains(token)) { + bracketStack.pop() + } + } + } + } + +} + + +object Main { + def main(args: Array[String]): Unit = { + val codeParser = new PythonCodeParser + val code = "if True: \n print 1 \nelif N=123: \n print 456 \nelse: \n print 789" + println(code) + val arrCodes = codeParser.parse(code, null) + print(arrCodes.mkString("||\n")) + } +} + +class SQLCodeParser extends SingleCodeParser { + + override val codeType: CodeType = CodeType.SQL + + val separator = ";" + + val defaultLimit: Int = ComputationExecutorConf.ENGINE_DEFAULT_LIMIT.getValue + + override def parse(code: String, engineExecutorContext: EngineExecutionContext): Array[String] = { + //val realCode = StringUtils.substringAfter(code, "\n") + val codeBuffer = new ArrayBuffer[String]() + + def appendStatement(sqlStatement: String): Unit = { + codeBuffer.append(sqlStatement) + } + + if (StringUtils.contains(code, separator)) { + StringUtils.split(code, ";").foreach { + case s if StringUtils.isBlank(s) => + case s if isSelectCmdNoLimit(s) => appendStatement(s); + case s => appendStatement(s); + } + } else { + code match { + case s if StringUtils.isBlank(s) => + case s if isSelectCmdNoLimit(s) => appendStatement(s); + case s => appendStatement(s); + } + } + codeBuffer.toArray + } + + def isSelectCmdNoLimit(cmd: String): Boolean = { + var code = cmd.trim + if (!cmd.split("\\s+")(0).equalsIgnoreCase("select")) return false + if (code.contains("limit")) code = code.substring(code.lastIndexOf("limit")).trim + else if (code.contains("LIMIT")) code = code.substring(code.lastIndexOf("LIMIT")).trim.toLowerCase + else return true + val hasLimit = code.matches("limit\\s+\\d+\\s*;?") + if (hasLimit) { + if (code.indexOf(";") > 0) code = code.substring(5, code.length - 1).trim + else code = code.substring(5).trim + val limitNum = code.toInt + if (limitNum > defaultLimit) throw new IllegalArgumentException("We at most allowed to limit " + defaultLimit + ", but your SQL has been over the max rows.") + } + !hasLimit + } +} + +object CodeType extends Enumeration { + type CodeType = Value + val Python, SQL, Scala, Shell, Other = Value + + def getType(codeType: String): CodeType = codeType.toLowerCase() match { + case "python" | "pyspark" | "py" => Python + case "sql" | "hql" => SQL + case "scala" => Scala + case "shell" => Shell + case _ => Other + } +} + diff --git a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala similarity index 86% rename from ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala rename to linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala index ab1897422b..42d229ee9d 100644 --- a/ujes/engine/src/main/scala/com/webank/wedatasphere/linkis/engine/rs/RsOutputStream.scala +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/rs/RsOutputStream.scala @@ -14,22 +14,19 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.rs +package com.webank.wedatasphere.linkis.engineconn.computation.executor.rs import java.io.OutputStream import com.webank.wedatasphere.linkis.common.io.resultset.ResultSetWriter import com.webank.wedatasphere.linkis.common.io.{MetaData, Record} import com.webank.wedatasphere.linkis.common.utils.Logging -import com.webank.wedatasphere.linkis.engine.execute.EngineExecutorContext +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.EngineExecutionContext import com.webank.wedatasphere.linkis.storage.LineRecord import scala.collection.mutable.ArrayBuffer -/** - * Created by enjoyyin on 2018/11/28. - */ class RsOutputStream extends OutputStream with Logging{ private val line = ArrayBuffer[Byte]() private var isReady = false @@ -47,8 +44,8 @@ class RsOutputStream extends OutputStream with Logging{ } } - def reset(engineExecutorContext: EngineExecutorContext) = { - writer = engineExecutorContext.createDefaultResultSetWriter() + def reset(engineExecutionContext: EngineExecutionContext) = { + writer = engineExecutionContext.createDefaultResultSetWriter() writer.addMetaData(null) } diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala new file mode 100644 index 0000000000..aa45ed2a4e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionService.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.service + +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteResponse + + +trait TaskExecutionService { + + def execute(requestTask: RequestTask, smc: ServiceMethodContext): ExecuteResponse + +// def taskStatus(taskID: String): ResponseTaskStatus + + def taskProgress(taskID: String): ResponseTaskProgress + + def taskLog(taskID: String): ResponseTaskLog + + def killTask(taskID: String): Unit + + /*def pauseTask(taskID: String): Unit + + def resumeTask(taskID: String): Unit*/ + + + def dealRequestTaskStatus(requestTaskStatus: RequestTaskStatus): ResponseTaskStatus + + def dealRequestTaskPause(requestTaskPause: RequestTaskPause): Unit + + def dealRequestTaskKill(requestTaskKill: RequestTaskKill): Unit + + def dealRequestTaskResume(requestTaskResume: RequestTaskResume): Unit + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala new file mode 100644 index 0000000000..1de9a72089 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/service/TaskExecutionServiceImpl.scala @@ -0,0 +1,349 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.service + +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.{ExecutorService, Executors, Future, TimeUnit} + +import com.google.common.cache.{Cache, CacheBuilder} +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.LogListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event._ +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.log.LogHelper +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.LockService +import com.webank.wedatasphere.linkis.engineconn.common.conf.{EngineConnConf, EngineConnConstant} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.entity.{CommonEngineConnTask, EngineConnTask} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.ComputationExecutor +import com.webank.wedatasphere.linkis.engineconn.computation.executor.listener.{ResultSetListener, TaskProgressListener, TaskStatusListener} +import com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis.{ComputationEngineUtils, ComputaionEngineContant} +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{ErrorExecuteResponse, ExecuteResponse, IncompleteExecuteResponse, SubmitResponse} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import javax.annotation.PostConstruct +import org.apache.commons.lang.StringUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Component + +import scala.collection.JavaConverters._ + + +@Component +class TaskExecutionServiceImpl extends TaskExecutionService with Logging with ResultSetListener with LogListener with TaskProgressListener with TaskStatusListener { + + private val executorManager = ExecutorManager.getInstance() + private val taskExecutedNum = new AtomicInteger(0) + private var lastTask: EngineConnTask = _ + private var executorService: ExecutorService = _ + private var lastTaskFuture: Future[_] = _ + + @Autowired + private var lockService: LockService = _ + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + private val syncListenerBus = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnSyncListenerBus + private val taskIdCache: Cache[String, ComputationExecutor] = CacheBuilder.newBuilder().expireAfterAccess(EngineConnConf.ENGINE_TASK_EXPIRE_TIME.getValue, TimeUnit.MILLISECONDS) + .maximumSize(EngineConnConstant.MAX_TASK_NUM).build() + + @PostConstruct + def init(): Unit = { + LogHelper.setLogListener(this) + syncListenerBus.addListener(this) + executorService = Executors.newSingleThreadExecutor() + } + + private def sendToEntrance(task: EngineConnTask, msg: RequestProtocol): Unit = synchronized { + Utils.tryCatch { + var sender : Sender = null + if (null != task && null != task.getCallbackServiceInstance()) { + sender = Sender.getSender(task.getCallbackServiceInstance()) + sender.send(msg) + } else { + // todo + debug("SendtoEntrance error, cannot find entrance instance.") + } + }{ + t => + val errorMsg = s"SendToEntrance error. $msg" + t.getCause + error(errorMsg, t) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.SEND_TO_ENTRANCE_ERROR, errorMsg) + } + } + + @Receiver + override def execute(requestTask: RequestTask, smc: ServiceMethodContext): ExecuteResponse = { + // smc // todo get sender + // check lock + if (StringUtils.isBlank(requestTask.getLock)) { + error(s"Invalid lock : ${requestTask.getLock} , requestTask : " + BDPJettyServerHelper.gson.toJson(requestTask)) + return ErrorExecuteResponse(s"Invalid lock : ${requestTask.getLock}.", new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_PARAMS, "Invalid lock or code(请获取到锁后再提交任务.)")) + } + if (!lockService.isLockExist(requestTask.getLock)) { + error(s"Lock ${requestTask.getLock} not exist, cannot execute.") + return ErrorExecuteResponse("Lock not exixt", new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_LOCK, "Lock : " + requestTask.getLock + " not exist(您的锁无效,请重新获取后再提交).")) + } + + if (StringUtils.isBlank(requestTask.getCode)) { + return IncompleteExecuteResponse("Your code is incomplete, it may be that only comments are selected for execution(您的代码不完整,可能是仅仅选中了注释进行执行)") + } + + // 获取任务类型和任务代码,运行任务 + val taskId: Int = taskExecutedNum.incrementAndGet() + val retryAble: Boolean = { + val retry = requestTask.getProperties.getOrDefault(ComputaionEngineContant.RETRYABLE_TYPE_NAME, null) + if (null != retry) retry.asInstanceOf[Boolean] + else false + } + val task = new CommonEngineConnTask(String.valueOf(taskId), retryAble) + task.setCode(requestTask.getCode) + task.setProperties(requestTask.getProperties) + task.data(ComputaionEngineContant.LOCK_TYPE_NAME, requestTask.getLock) + task.setStatus(ExecutionNodeStatus.Scheduled) + val labels = requestTask.getLabels.asScala.toArray + task.setLabels(labels) + val entranceServerInstance = RPCUtils.getServiceInstanceFromSender(smc.getSender) + task.setCallbackServiceInstance(entranceServerInstance) + val executor = executorManager.getExecutorByLabels(labels) + executor match { + case computationExecutor: ComputationExecutor => + taskIdCache.put(task.getTaskId, computationExecutor) + submitTask(task, computationExecutor) + case o => + val msg = "Invalid compuatitionExecutor : " + ComputationEngineUtils.GSON.toJson(o) + ", labels : " + ComputationEngineUtils.GSON.toJson(labels) + ", requestTask : " + ComputationEngineUtils.GSON.toJson(requestTask) + error(msg) + ErrorExecuteResponse("Invalid computationExecutor(生成无效的计算引擎,请联系管理员).", + new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_ENGINE_TYPE, msg)) + } + + } + + +// override def taskStatus(taskID: String): ResponseTaskStatus = { +// val task = taskIdCache.get(taskID) +// ResponseTaskStatus(taskID, task.getStatus.id) +// } + + private def submitTask(task: CommonEngineConnTask, computationExecutor: ComputationExecutor) = { + val runTask = new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val response = computationExecutor.execute(task) + response match { + case ErrorExecuteResponse(message, throwable) => + sendToEntrance(task, ResponseTaskError(task.getTaskId, message)) + error(message, throwable) + computationExecutor.transformTaskStatus(task, ExecutionNodeStatus.Failed) + case _ => + } + } + } + lastTask = task + lastTaskFuture = executorService.submit(runTask) + info(s"Task ${task.getTaskId} was submited.") + SubmitResponse(task.getTaskId) + } + + override def taskProgress(taskID: String): ResponseTaskProgress = { + var response = ResponseTaskProgress(taskID, -1, null) + if (StringUtils.isBlank(taskID)) response + val executor = taskIdCache.getIfPresent(taskID) + if (null != executor) { + val task = executor.getTaskById(taskID) + if (null != task) { + if (ExecutionNodeStatus.isCompleted(task.getStatus)) { + response = ResponseTaskProgress(taskID, 1.0f, null) + } else { + response = ResponseTaskProgress(taskID, executor.progress(), executor.getProgressInfo) + } + } else { + response = ResponseTaskProgress(taskID, -1, null) + } + } else { + error(s"Executor of taskId : $taskID is not cached.") + } + response + } + + override def taskLog(taskID: String): ResponseTaskLog = { + // todo check + null + } + +// override def pauseTask(taskID: String): Unit = { +// val task = taskIdCache.get(taskID) +// // todo +// } + + override def killTask(taskID: String): Unit = { + val executor = taskIdCache.getIfPresent(taskID) + if (null != executor) { + executor.killTask(taskID) + } else { + error(s"Executor of taskId : $taskID is not cached.") + } + Utils.tryAndWarn (Thread.sleep(50)) + if (null != lastTask && lastTask.getTaskId.equalsIgnoreCase(taskID)) { + if (null != lastTaskFuture && !lastTaskFuture.isDone) { + Utils.tryAndWarn(lastTaskFuture.cancel(true)) + } + } + } + + /*override def resumeTask(taskID: String): Unit = { + // todo + }*/ + + @Receiver + override def dealRequestTaskStatus(requestTaskStatus: RequestTaskStatus): ResponseTaskStatus = { + val task = getTaskByTaskId(requestTaskStatus.execId) + if (null != task) { + ResponseTaskStatus(task.getTaskId, task.getStatus) + } else { + val msg = "Task null! requestTaskStatus: " + ComputationEngineUtils.GSON.toJson(requestTaskStatus) + error(msg) + ResponseTaskStatus(requestTaskStatus.execId, ExecutionNodeStatus.Cancelled) + } + } + + @Receiver + override def dealRequestTaskPause(requestTaskPause: RequestTaskPause): Unit = { + info(s"Pause is Not supported for task : " + requestTaskPause.execId ) + } + + @Receiver + override def dealRequestTaskKill(requestTaskKill: RequestTaskKill): Unit = { + val executor = taskIdCache.getIfPresent(requestTaskKill.execId) + if (null != executor) { + executor.killTask(requestTaskKill.execId) + info(s"TaskId : ${requestTaskKill.execId} was killed by user.") + } else { + error(s"Invalid executor : null for taskId : ${requestTaskKill.execId}") + } + } + + @Receiver + override def dealRequestTaskResume(requestTaskResume: RequestTaskResume): Unit = { + info(s"Resume is Not support for task : " + requestTaskResume.execId ) + } + + override def onEvent(event: EngineConnSyncEvent): Unit = event match { + case taskStatusChangedEvent: TaskStatusChangedEvent => onTaskStatusChanged(taskStatusChangedEvent) + case taskProgressUpdateEvent: TaskProgressUpdateEvent => onProgressUpdate(taskProgressUpdateEvent) + case logUpdateEvent: TaskLogUpdateEvent => onLogUpdate(logUpdateEvent) + case taskResultCreateEvent: TaskResultCreateEvent => onResultSetCreated(taskResultCreateEvent) + case taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent => onResultSizeCreated(taskResultSizeCreatedEvent) + case _ => + warn("Unknown event : " + BDPJettyServerHelper.gson.toJson(event)) + } + + override def onLogUpdate(logUpdateEvent: TaskLogUpdateEvent): Unit = { + if (EngineConnConf.ENGINE_PUSH_LOG_TO_ENTRANCE.getValue) { + if (null != logUpdateEvent && StringUtils.isNotBlank(logUpdateEvent.taskId)) { + val task = getTaskByTaskId(logUpdateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskLog(logUpdateEvent.taskId, logUpdateEvent.log)) + } else { + error("Task cannot null! logupdateEvent: " + ComputationEngineUtils.GSON.toJson(logUpdateEvent)) + } + } else { + val executor = ExecutorManager.getInstance().getDefaultExecutor + executor match { + case computationExecutor: ComputationExecutor => + sendToEntrance(lastTask, ResponseTaskLog(lastTask.getTaskId, logUpdateEvent.log)) + case _ => + error("OnLogUpdate error. Invalid ComputationExecutor : " + ComputationEngineUtils.GSON.toJson(executor)) + } + } + + } + } + + override def onTaskStatusChanged(taskStatusChangedEvent: TaskStatusChangedEvent): Unit = { + val task = getTaskByTaskId(taskStatusChangedEvent.taskId) + if (null != task) { + if (ExecutionNodeStatus.isCompleted(taskStatusChangedEvent.toStatus)) { + lastTask = task + LogHelper.pushAllRemainLogs() + } + sendToEntrance(task, ResponseTaskStatus(taskStatusChangedEvent.taskId, taskStatusChangedEvent.toStatus)) + } else { + error("Task cannot null! taskStatusChangedEvent: " + ComputationEngineUtils.GSON.toJson(taskStatusChangedEvent)) + } + } + + override def onProgressUpdate(taskProgressUpdateEvent: TaskProgressUpdateEvent): Unit = { + if (EngineConnConf.ENGINE_PUSH_LOG_TO_ENTRANCE.getValue) { + val task = getTaskByTaskId(taskProgressUpdateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskProgress(taskProgressUpdateEvent.taskId, taskProgressUpdateEvent.progress, taskProgressUpdateEvent.progressInfo)) + } else { + error("Task cannot null! taskProgressUpdateEvent : " + ComputationEngineUtils.GSON.toJson(taskProgressUpdateEvent)) + } + } + } + + override def onResultSetCreated(taskResultCreateEvent: TaskResultCreateEvent): Unit = { + info(s"start to deal result event ${taskResultCreateEvent.taskId}") + val task = getTaskByTaskId(taskResultCreateEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskResultSet( + taskResultCreateEvent.taskId, + taskResultCreateEvent.resStr, + taskResultCreateEvent.alias + )) + } else { + error("Task cannot null! taskResultCreateEvent: " + ComputationEngineUtils.GSON.toJson(taskResultCreateEvent)) + } + info(s"Finished to deal result event ${taskResultCreateEvent.taskId}") + } + + def getTaskByTaskId(taskId: String): EngineConnTask = { + if (StringUtils.isBlank(taskId)) return null + val executor = taskIdCache.getIfPresent(taskId) + if (null != executor) { + executor.getTaskById(taskId) + } else { + error(s"Executor of taskId : $taskId is not cached.") + null + } + } + + override def onResultSizeCreated(taskResultSizeCreatedEvent: TaskResultSizeCreatedEvent): Unit = { + val task = getTaskByTaskId(taskResultSizeCreatedEvent.taskId) + if (null != task) { + sendToEntrance(task, ResponseTaskResultSize( + taskResultSizeCreatedEvent.taskId, + taskResultSizeCreatedEvent.resultSize + )) + } else { + error("Task cannot null! taskResultSizeCreatedEvent: " + ComputationEngineUtils.GSON.toJson(taskResultSizeCreatedEvent)) + } + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala new file mode 100644 index 0000000000..40eefeff1d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputaionEngineContant.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis + + +object ComputaionEngineContant { + + def RETRYABLE_TYPE_NAME = "taskRetryable" + + def LOCK_TYPE_NAME = "lock" +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala new file mode 100644 index 0000000000..049bca958b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-computation-engineconn/src/main/scala/com/webank/wedatasphere/linkis/engineconn/computation/executor/utlis/ComputationEngineUtils.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.computation.executor.utlis + +import com.google.gson.{Gson, GsonBuilder} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper + + +object ComputationEngineUtils { + + def GSON: Gson = BDPJettyServerHelper.gson + + def GSON_PRETTY: Gson = new GsonBuilder().setPrettyPrinting().create() + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml new file mode 100644 index 0000000000..1b707e875c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/pom.xml @@ -0,0 +1,91 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-common + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-label-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala new file mode 100644 index 0000000000..52dc90ed39 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConf.scala @@ -0,0 +1,45 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.conf + +import com.webank.wedatasphere.linkis.common.conf.CommonVars + + +object EngineConnConf { + + val ENGINE_EXECUTIONS = CommonVars("wds.linkis.engine.connector.executions", "com.webank.wedatasphere.linkis.engineconn.computation.executor.execute.ComputationEngineConnExecution") + + val ENGINE_CONN_HOOKS = CommonVars("wds.linkis.engine.connector.hooks", "com.webank.wedatasphere.linkis.engineconn.computation.executor.hook.ComputationEngineConnHook") + + + val ENGINE_LAUNCH_CMD_PARAMS_USER_KEY = CommonVars("wds.linkis.engine.launch.cmd.params.user.key", "user") + + val ENGINE_SUPPORT_PARALLELISM = CommonVars("wds.linkis.engine.parallelism.support.enabled", false) + + val ENGINE_PUSH_LOG_TO_ENTRANCE = CommonVars("wds.linkis.engine.push.log.enable", true) + + val ENGINECONN_PLUGIN_CLAZZ = CommonVars("wds.linkis.engineconn.plugin.default.clazz", "com.webank.wedatasphere.linkis.engineplugin.hive.HiveEngineConnPlugin") + + + val ENGINE_TASK_EXPIRE_TIME = CommonVars("wds.linkis.engine.task.expire.time", 1000 * 3600 * 24) + + val ENGINE_LOCK_REFRESH_TIME = CommonVars("wds.linkis.engine.lock.refresh.time", 1000 * 60 * 3) + + val ENGINE_CONN_LOCALPATH_PWD_KEY = CommonVars("wds.linkis.engine.localpath.pwd.key", "PWD") + + val ENGINE_CONN_LOCAL_LOG_DIRS_KEY = CommonVars("wds.linkis.engine.logs.dir.key", "LOG_DIRS") +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala new file mode 100644 index 0000000000..b5f7d6a8fb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/conf/EngineConnConstant.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.conf + + +object EngineConnConstant { + + val MAX_TASK_NUM = 10000 + + val SPRING_CONF_MAP_NAME = "SpringConfMap" + + val MAX_EXECUTOR_ID_NAME = "MaxExecutorId" +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala new file mode 100644 index 0000000000..281a3de469 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/creation/EngineCreationContext.scala @@ -0,0 +1,103 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.creation + +import java.util + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + +trait EngineCreationContext { + + def getUser: String + + def setUser(user: String): Unit + + def getTicketId: String + + def setTicketId(ticketId: String): Unit + + def getLabels(): util.List[Label[_]] + + def setLabels(labels: util.List[Label[_]]): Unit + + def getEMInstance: ServiceInstance + + def setEMInstance(instance: ServiceInstance): Unit + + def getOptions: util.Map[String, String] + + def setOptions(options: util.Map[String, String]) + + def getExecutorId: Int + + def setExecutorId(id: Int) + + def setArgs(args: Array[String]) + + def getArgs: Array[String] +} + +class DefaultEngineCreationContext extends EngineCreationContext { + + private var user: String = _ + + private var ticketId: String = _ + + private var labels: util.List[Label[_]] = _ + + private var options: util.Map[String, String] = _ + + private var emInstance: ServiceInstance = _ + + private var executorId: Int = 0 + + private var args: Array[String] = null + + override def getTicketId: String = this.ticketId + + override def setTicketId(ticketId: String): Unit = this.ticketId = ticketId + + override def getLabels(): util.List[Label[_]] = this.labels + + override def setLabels(labels: util.List[Label[_]]): Unit = this.labels = labels + + override def getEMInstance: ServiceInstance = this.emInstance + + override def setEMInstance(instance: ServiceInstance): Unit = this.emInstance = instance + + override def getOptions: util.Map[String, String] = this.options + + override def setOptions(options: util.Map[String, String]): Unit = this.options = options + + override def getUser: String = user + + override def setUser(user: String): Unit = this.user = user + + override def getExecutorId: Int = executorId + + override def setExecutorId(id: Int): Unit = executorId = id + + override def setArgs(args: Array[String]): Unit = this.args = args + + override def getArgs: Array[String] = args + + + override def toString = s"DefaultEngineCreationContext(user-$user, ticketID-$ticketId, emInstance-$emInstance)" +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala new file mode 100644 index 0000000000..c97339e101 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/engineconn/EngineConn.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.engineconn + +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext + + +trait EngineConn { + + /** + * 底层engine的类型比如:Spark、hive + * + * @return + */ + def getEngineType(): String + + def setEngineType(engineType: String): Unit + + /** + * 底层计算存储Engine的具体连接信息,比如SparkSession,hive的sessionState + * + * @return + */ + def getEngine(): Any + + def setEngine(engine: Any): Unit + + def getEngineCreationContext: EngineCreationContext + + +} + +class DefaultEngineConn(engineCreationContext: EngineCreationContext) extends EngineConn { + + var engineType: String = "spark" + + var engine: Any = null + + + /** + * 底层engine的类型比如:Spark、hive + * + * @return + */ + override def getEngineType(): String = engineType + + override def setEngineType(engineType: String): Unit = this.engineType = engineType + + /** + * 底层计算存储Engine的具体连接信息,比如SparkSession,hive的sessionState + * + * @return + */ + override def getEngine(): Any = engine + + override def setEngine(engine: Any): Unit = this.engine = engine + + override def getEngineCreationContext: EngineCreationContext = engineCreationContext + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala new file mode 100644 index 0000000000..51fa841b5f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/exception/EngineConnException.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class EngineTypeVersionNotMatchException(msg: String) extends ErrorException(40010, msg) + + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala new file mode 100644 index 0000000000..b6e6252140 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/execution/EngineExecution.scala @@ -0,0 +1,56 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.execution + +import com.webank.wedatasphere.linkis.common.exception.FatalException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import org.apache.commons.lang.StringUtils + + +trait EngineExecution { + + def execute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit +} + +object EngineExecution extends Logging { + + + private val engineExecutions = initEngineExecutions + + private def initEngineExecutions: Array[EngineExecution] = { + + val executions = EngineConnConf.ENGINE_EXECUTIONS.getValue + if (StringUtils.isNotBlank(executions)) { + val clazzArr = executions.split(",") + if (null != clazzArr && !clazzArr.isEmpty) { + clazzArr.map { clazz => + Utils.getClassInstance[EngineExecution](clazz) + } + } else { + throw new FatalException(0, "ENGINE_EXECUTIONS must be set") + } + } else { + throw new FatalException(0, "ENGINE_EXECUTIONS must be set") + } + + } + + def getEngineExecutions: Array[EngineExecution] = engineExecutions +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala new file mode 100644 index 0000000000..dab0149ed9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-common/src/main/scala/com/webank/wedatasphere/linkis/engineconn/common/hook/EngineConnHook.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.common.hook + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import org.apache.commons.lang.StringUtils + + +trait EngineConnHook { + + def beforeCreateEngineConn(engineCreationContext: EngineCreationContext): Unit + + /*def afterCreateEngineConn(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit*/ + + def beforeExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit + + def afterExecutionExecute(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit + + def afterEngineServerStartFailed(engineCreationContext: EngineCreationContext, throwable: Throwable): Unit = { + + } + + def afterEngineServerStartSuccess(engineCreationContext: EngineCreationContext, engineConn: EngineConn): Unit = { + + } + +} + +object EngineConnHook extends Logging { + + private val engineConnHooks = initEngineConnHooks + + private def initEngineConnHooks: Array[EngineConnHook] = { + + val hooks = EngineConnConf.ENGINE_CONN_HOOKS.getValue + if (StringUtils.isNotBlank(hooks)) { + val clazzArr = hooks.split(",") + if (null != clazzArr && clazzArr.nonEmpty) { + clazzArr.map { clazz => + Utils.tryAndWarn(Utils.getClassInstance[EngineConnHook](clazz)) + }.filter(_ != null) + } else { + Array.empty + } + } else { + Array.empty + } + + } + + def getEngineConnHooks: Array[EngineConnHook] = engineConnHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml new file mode 100644 index 0000000000..cbdca0a76b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/pom.xml @@ -0,0 +1,84 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-core + + + + com.webank.wedatasphere.linkis + linkis-engineconn-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-plugin-core + ${linkis.version} + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala new file mode 100644 index 0000000000..5b7b72cc86 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/EngineConnObject.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.conf.EngineConnConf +import com.webank.wedatasphere.linkis.engineconn.common.creation.{DefaultEngineCreationContext, EngineCreationContext} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.EngineConnPlugin + +object EngineConnObject extends Logging { + + private val engineConnPlugin: EngineConnPlugin = Utils.tryCatch { + Utils.getClassInstance[EngineConnPlugin](EngineConnConf.ENGINECONN_PLUGIN_CLAZZ.getValue) + } { case t: Throwable => + error("Failed to create engineConnPlugin: " + EngineConnConf.ENGINECONN_PLUGIN_CLAZZ.getValue, t) + System.exit(1) + null + } + private var engineCreationContext: EngineCreationContext = _ + private var ready = false + + def isReady: Boolean = isReady + + def setReady: Unit = this.ready = true + + def getEngineConnPlugin: EngineConnPlugin = engineConnPlugin + + def getEngineCreationContext: EngineCreationContext = this.engineCreationContext + + def setEngineCreationContext( engineCreationContext: EngineCreationContext): Unit = this.engineCreationContext = engineCreationContext + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala new file mode 100644 index 0000000000..6f417954ab --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/engineconn/EngineConnManager.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.engineconn + +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.common.engineconn.EngineConn +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject + +trait EngineConnManager { + + def createEngineConn(engineCreationContext: EngineCreationContext): EngineConn + + def getEngineConn(): EngineConn + + +} + +object EngineConnManager { + val engineConnManager: EngineConnManager = new DefaultEngineConnManager + + def getEngineConnManager = engineConnManager +} + +class DefaultEngineConnManager extends EngineConnManager { + + private var engineConn: EngineConn = _ + + override def createEngineConn(engineCreationContext: EngineCreationContext): EngineConn = { + this.engineConn = EngineConnObject.getEngineConnPlugin.getEngineConnFactory.createEngineConn(engineCreationContext) + this.engineConn + } + + override def getEngineConn(): EngineConn = this.engineConn + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala new file mode 100644 index 0000000000..a6ac558c79 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/executor/ExecutorManager.scala @@ -0,0 +1,174 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.executor + +import java.util +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.EngineCreationContext +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.util.EngineConnUtils +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, LabelExecutor} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.EngineConnPlugin +import com.webank.wedatasphere.linkis.manager.engineplugin.common.creation.{MultiExecutorEngineConnFactory, SingleExecutorEngineConnFactory} +import com.webank.wedatasphere.linkis.manager.engineplugin.common.exception.{EngineConnPluginErrorCode, EngineConnPluginErrorException} +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.EngineRunTypeLabel + +import scala.collection.JavaConverters._ + +trait ExecutorManager { + + def getDefaultExecutor: Executor + + def getExecutorByLabels(labels: Array[Label[_]]): Executor + + def createExecutor(engineCreationContext: EngineCreationContext, labels: Array[Label[_]]): Executor + + def getAllExecutorsMap(): util.Map[String, Executor] + + def generateId(): Int + +} + +class ExecutorManagerImpl extends ExecutorManager with Logging { + + private val executors: util.Map[String, Executor] = new ConcurrentHashMap[String, Executor](2) + private val GSON = EngineConnUtils.GSON + private var defaultExecutor: Executor = _ + + private val idCreator = new AtomicInteger() + + override def getDefaultExecutor: Executor = { + if (null == defaultExecutor || defaultExecutor.isClosed()) { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + if (null == engineConn) { + error("Create default executor failed., engineConn not ready") + return null + } + Utils.tryCatch { + createExecutor(engineConn.getEngineCreationContext, null) + } { + case t: Throwable => + error("Create default executor failed. Now will try again once.", t) + createExecutor(engineConn.getEngineCreationContext, null) + } + } + defaultExecutor + } + + override def createExecutor(engineCreationContext: EngineCreationContext, labels: Array[Label[_]]): Executor = { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + val enginePlugin: EngineConnPlugin = EngineConnObject.getEngineConnPlugin + val isDefault: Boolean = if (null == labels || labels.isEmpty || null == defaultExecutor || defaultExecutor.isClosed()) true else false + var runType: String = null + if (!isDefault) { + runType = getRunTypeFromLables(labels) + if (null == runType) { + val msg = "Invalid RunType label. labels : " + GSON.toJson(labels) + error(msg) + throw new EngineConnPluginErrorException(EngineConnPluginErrorCode.INVALID_LABELS, msg) + } + } + val executor: Executor = { + enginePlugin.getEngineConnFactory match { + case engineConnFactory: SingleExecutorEngineConnFactory => + engineConnFactory.createExecutor(engineCreationContext, engineConn) + case engineConnFactory: MultiExecutorEngineConnFactory => + val executorFactories = engineConnFactory.getExecutorFactories + val chooseExecutorFactory = if (isDefault) { + info("use default executor") + Some(engineConnFactory.getDefaultExecutorFactory) + } else { + executorFactories.find(e => e.canCreate(labels)) + } + if (chooseExecutorFactory.isEmpty) { + val msg = if (null == labels) { + "Cannot get default executorFactory. EngineCreation labels: " + GSON.toJson(engineCreationContext.getLabels()) + } else { + "Cannot get valid executorFactory. EngineCreation labels: " + GSON.toJson(labels) + } + error(msg) + throw new EngineConnPluginErrorException(EngineConnPluginErrorCode.INVALID_LABELS, msg) + } else { + chooseExecutorFactory.get.createExecutor(engineCreationContext, engineConn, labels) + } + case o => + error("Invalid ExecutorFactory " + GSON.toJson(o)) + null + } + } + info(s"Finished create executor ${executor.getId()}") + executor.init() + info(s"Finished init executor ${executor.getId()}") + executor match { + case labelExecutor: LabelExecutor => + runType = getRunTypeFromLables(labelExecutor.getExecutorLabels().asScala.toArray) + case _ => + } + executors.put(runType, executor) + if (isDefault) { + defaultExecutor = executor + } + executor + } + + override def generateId(): Int = idCreator.getAndIncrement() + + override def getExecutorByLabels(labels: Array[Label[_]]): Executor = { + var runType: String = null + labels.foreach(l => l match { + case label: EngineRunTypeLabel => + runType = label.getRunType + case _ => + }) + if (null == runType) { + error("Invalid RunType Label. labels: " + GSON.toJson(labels)) + return null + } + if (!executors.containsKey(runType)) { + val engineConn = EngineConnManager.getEngineConnManager.getEngineConn() + createExecutor(engineConn.getEngineCreationContext, labels) + } + executors.get(runType) + } + + override def getAllExecutorsMap(): util.Map[String, Executor] = executors + + private def getRunTypeFromLables(labels: Array[Label[_]]): String = { + + labels.foreach { + case label: EngineRunTypeLabel => + return label.getRunType + case _ => + } + null + } +} + +object ExecutorManager { + + private val executorManager: ExecutorManager = new ExecutorManagerImpl + Utils.getClassInstance[ExecutorManager](EngineConnExecutorConfiguration.EXECUTOR_MANAGER_SERVICE_CLAZZ.getValue) + + def getInstance(): ExecutorManager = executorManager + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala new file mode 100644 index 0000000000..9e226fe3ec --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/hook/ShutdownHook.scala @@ -0,0 +1,98 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.hook + +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock + +import com.webank.wedatasphere.linkis.common.utils.Logging + +class ShutdownHook extends Logging { + + var exitCode = 0 + + private val lock = new ReentrantLock() + private val condition = lock.newCondition() + + // Guarded by "lock" + private var error: Throwable = null + + // Guarded by "lock" + private var stopped: Boolean = false + + def notifyError(e: Throwable): Unit = { + lock.lock() + try { + setExitCode(1) + error = e + error("process exit reason: ", e) + condition.signalAll() + } finally { + lock.unlock() + } + } + + def notifyStop(): Unit = { + lock.lock() + try { + setExitCode(0) + stopped = true + condition.signalAll() + } finally { + lock.unlock() + } + } + + /** + * Return `true` if it's stopped; or throw the reported error if `notifyError` has been called; or + * `false` if the waiting time detectably elapsed before return from the method. + */ + def waitForStopOrError(timeout: Long = -1): Boolean = { + lock.lock() + try { + if (timeout < 0) { + while (!stopped && error == null) { + condition.await() + } + } else { + var nanos = TimeUnit.MILLISECONDS.toNanos(timeout) + while (!stopped && error == null && nanos > 0) { + nanos = condition.awaitNanos(nanos) + } + } + // If already had error, then throw it + if (error != null) throw error + // already stopped or timeout + stopped + } finally { + lock.unlock() + } + } + + def setExitCode(exitCode: Int): Unit = this.exitCode = exitCode + + def getExitCode(): Int = exitCode + +} + +object ShutdownHook { + + private val shutdownHook = new ShutdownHook + + def getShutdownHook: ShutdownHook = shutdownHook + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala new file mode 100644 index 0000000000..e1d4e5ba83 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/core/util/EngineConnUtils.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.core.util + +import com.google.gson.Gson + +object EngineConnUtils { + + val GSON = new Gson() + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml new file mode 100644 index 0000000000..1b6b563f61 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/pom.xml @@ -0,0 +1,99 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-accessible-executor + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + reflections + org.reflections + + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-launch + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + + + reflections + org.reflections + + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java new file mode 100644 index 0000000000..c60eacd8c0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/AbstractLogCache.java @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.common.log.LogUtils; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.LogEvent; + +public abstract class AbstractLogCache implements LogCache { + protected String generateLog(LogEvent event) { + if (event.getLevel() == Level.INFO) { + return LogUtils.generateInfo(event.getMessage().toString()); + } else if (event.getLevel() == Level.WARN) { + return LogUtils.generateWarn(event.getMessage().toString()); + } else if (event.getLevel() == Level.ERROR) { + return LogUtils.generateERROR(event.getMessage().toString()); + } else if (event.getLevel() == Level.FATAL) { + return LogUtils.generateSystemError(event.getMessage().toString()); + } + return ""; + } +} diff --git a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java similarity index 86% rename from ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java rename to linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java index 63b67fba23..4000f33e51 100644 --- a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/LogCache.java +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogCache.java @@ -14,26 +14,24 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.log; +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; import java.util.List; -/** - * created by enjoyyin on 2018/11/27 - * Description: - */ public interface LogCache { /** * Store logs in the cache for subsequent delivery * 将日志存储到缓存当中,用于后续的发送 + * * @param log 日志信息 */ void cacheLog(String log); /** * Get the log of the number of num(获取num数目的日志) - * @param num The number of logs you want to get(希望获取的日志的数量) + * + * @param num The number of logs you want to get(希望获取的日志的数量) * @return Log List Collection(日志List集合) */ List getLog(int num); @@ -41,6 +39,7 @@ public interface LogCache { /** * Take all the logs in the log cache for the engine to take out all the logs after performing a task * 将日志缓存中的所有日志都取出,用于engine执行完一个任务之后将日志全部取出 + * * @return */ List getRemain(); diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java new file mode 100644 index 0000000000..4058910ad9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/MountLogCache.java @@ -0,0 +1,126 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class MountLogCache extends AbstractLogCache { + + private static final Logger logger = LoggerFactory.getLogger(MountLogCache.class); + + class CircularQueue { + + private int max; + private String[] elements; + private int front, rear, count; + + CircularQueue() { + this((Integer) AccessibleExecutorConfiguration.ENGINECONN_LOG_CACHE_NUM().getValue()); + } + + CircularQueue(int max) { + this.max = max; + this.elements = new String[max]; + } + + public boolean isEmpty() { + return count == 0; + } + + public synchronized void enqueue(String value) { + if (count == max) { + logger.warn("Queue is full, log: {} needs to be dropped", value); + } else { + rear = (rear + 1) % max; + elements[rear] = value; + count++; + } + } + + public String dequeue() { + if (count == 0) { + logger.debug("Queue is empty, nothing to get"); + return null; + } else { + front = (front + 1) % max; + count--; + return elements[front]; + } + } + + public List dequeue(int num) { + List list = new ArrayList<>(); + int index = 0; + while (index < num) { + String tempLog = dequeue(); + if (StringUtils.isNotEmpty(tempLog)) { + list.add(tempLog); + } else if (tempLog == null) { + break; + } + index++; + } + return list; + } + + public synchronized List getRemain() { + List list = new ArrayList<>(); + while (!isEmpty()) { + list.add(dequeue()); + } + return list; + } + + public int size() { + return count; + } + } + + + private CircularQueue logs; + + + public MountLogCache(int loopMax) { + this.logs = new CircularQueue(loopMax); + } + + @Override + public void cacheLog(String log) { + logs.enqueue(log); + } + + @Override + public List getLog(int num) { + return logs.dequeue(num); + } + + @Override + public synchronized List getRemain() { + return logs.getRemain(); + } + + @Override + public int size() { + return logs.size(); + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java new file mode 100644 index 0000000000..ec6069cc7d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/SendAppender.java @@ -0,0 +1,142 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; + +import com.webank.wedatasphere.linkis.common.utils.Utils; +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration; +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent; +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject; +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListenerBus; +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@Plugin(name = "Send", category = "Core", elementType = "appender", printObject = true) +public class SendAppender extends AbstractAppender { + + /** + * @fields serialVersionUID + */ + private static final long serialVersionUID = -830237775522429777L; + + private static EngineConnSyncListenerBus engineConnSyncListenerBus = ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnSyncListenerBus(); + + private LogCache logCache; + private static final Logger logger = LoggerFactory.getLogger(SendAppender.class); + + private static final String IGNORE_WORDS = AccessibleExecutorConfiguration.ENGINECONN_IGNORE_WORDS().getValue(); + + private static final String[] IGNORE_WORD_ARR = IGNORE_WORDS.split(","); + + private static final String PASS_WORDS = AccessibleExecutorConfiguration.ENGINECONN_PASS_WORDS().getValue(); + + private static final String[] PASS_WORDS_ARR = PASS_WORDS.split(","); + + + class SendThread implements Runnable { + @Override + public void run() { + if (engineConnSyncListenerBus == null) { + //ignore + } else { + if (logCache == null) { + logger.warn("logCache is null"); + return; + } + List logs = logCache.getRemain(); + if (logs.size() > 0) { + StringBuilder sb = new StringBuilder(); + for (String log : logs) { + sb.append(log).append("\n"); + } + if (EngineConnObject.isReady()) { + engineConnSyncListenerBus.postToAll(new TaskLogUpdateEvent(null, sb.toString())); + } + } + } + } + } + + + public SendAppender(final String name, final Filter filter, final Layout extends Serializable> layout, + final boolean ignoreExceptions) { + super(name, filter, layout, ignoreExceptions); + this.logCache = LogHelper.logCache(); + SendThread thread = new SendThread(); + Utils.defaultScheduler().scheduleAtFixedRate(thread, 10, (Integer) AccessibleExecutorConfiguration.ENGINECONN_LOG_SEND_TIME_INTERVAL().getValue(), TimeUnit.MILLISECONDS); + } + + + + @Override + public void append(LogEvent event) { + if (engineConnSyncListenerBus == null) { + return; + } + String logStr = new String(getLayout().toByteArray(event)); + if (event.getLevel().intLevel() == Level.INFO.intLevel()) { + boolean flag = false; + for (String ignoreLog : IGNORE_WORD_ARR) { + if (logStr.contains(ignoreLog)) { + flag = true; + break; + } + } + for (String word : PASS_WORDS_ARR) { + if (logStr.contains(word)) { + flag = false; + break; + } + } + if (!flag) { + logCache.cacheLog(logStr); + } + } else { + logCache.cacheLog(logStr); + } + } + + @PluginFactory + public static SendAppender createAppender(@PluginAttribute("name") String name, + @PluginElement("Filter") final Filter filter, + @PluginElement("Layout") Layout extends Serializable> layout, + @PluginAttribute("ignoreExceptions") boolean ignoreExceptions) { + if (name == null) { + LOGGER.error("No name provided for SendAppender"); + return null; + } + if (layout == null) { + layout = PatternLayout.createDefaultLayout(); + } + return new SendAppender(name, filter, layout, ignoreExceptions); + } + +} \ No newline at end of file diff --git a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java similarity index 84% rename from ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java rename to linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java index 0da73e4a42..68ff59454c 100644 --- a/ujes/engine/src/main/java/com/webank/wedatasphere/linkis/engine/log/TimeLogCache.java +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/java/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/TimeLogCache.java @@ -14,17 +14,14 @@ * limitations under the License. */ -package com.webank.wedatasphere.linkis.engine.log; - -import org.apache.logging.log4j.core.LogEvent; +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log; import java.util.List; /** - * created by enjoyyin on 2018/11/27 * Description: Cache with time as storage unit(以时间作为存储单位的缓存方式) */ -public class TimeLogCache extends AbstractLogCache{ +public class TimeLogCache extends AbstractLogCache { @Override public void cacheLog(String log) { diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala new file mode 100644 index 0000000000..88a9d378e7 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorConfiguration.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + +object AccessibleExecutorConfiguration { + + val ENGINECONN_LOG_CACHE_NUM = CommonVars("wds.linkis.engineconn.log.cache.default", 500) + + + val ENGINECONN_IGNORE_WORDS = CommonVars("wds.linkis.engineconn.ignore.words", "org.apache.spark.deploy.yarn.Client") + + val ENGINECONN_PASS_WORDS = CommonVars("wds.linkis.engineconn.pass.words", "org.apache.hadoop.hive.ql.exec.Task") + + val ENGINECONN_LOG_NUM_SEND_ONCE = CommonVars("wds.linkis.engineconn.log.send.once", 100) + + val ENGINECONN_LOG_SEND_TIME_INTERVAL = CommonVars("wds.linkis.engineconn.log.send.time.interval", 3) + + + val ENGINECONN_MAX_FREE_TIME = CommonVars("wds.linkis.engineconn.max.free.time", new TimeType("1h")) + + + val ENGINECONN_SUPPORT_PARALLELISM = CommonVars("wds.linkis.engineconn.support.parallelism", false) + + + val ENGINECONN_HEARTBEAT_TIME = CommonVars("wds.linkis.engineconn.heartbeat.time", new TimeType("3m")) + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala new file mode 100644 index 0000000000..2a0f157730 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/conf/AccessibleExecutorSpringConfiguration.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.info.{DefaultNodeOverLoadInfoManager, NodeOverLoadInfoManager} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.{EngineConnConcurrentLockService, EngineConnTimedLockService, LockService} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.context.annotation.{Bean, Configuration} + +@Configuration +class AccessibleExecutorSpringConfiguration extends Logging { + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus + + @Bean(Array("lockService")) + @ConditionalOnMissingBean + def createLockManager(): LockService = { + + val lockService = if (AccessibleExecutorConfiguration.ENGINECONN_SUPPORT_PARALLELISM.getValue) new EngineConnConcurrentLockService + else new EngineConnTimedLockService + asyncListenerBusContext.addListener(lockService) + lockService + } + + @Bean + @ConditionalOnMissingBean(Array(classOf[NodeOverLoadInfoManager])) + def createNodeOverLoadInfoManager(): NodeOverLoadInfoManager = { + + new DefaultNodeOverLoadInfoManager + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala new file mode 100644 index 0000000000..277ad5eafb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/AccessibleExecutor.scala @@ -0,0 +1,90 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.ExecutorStatusChangedEvent +import com.webank.wedatasphere.linkis.engineconn.executor.entity.SensibleExecutor +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException + +abstract class AccessibleExecutor extends SensibleExecutor { + + private var isExecutorClosed = false + + def isIdle = NodeStatus.isIdle(getStatus) + + def isBusy = NodeStatus.isLocked(getStatus) + + def whenBusy[A](f: => A) = whenStatus(NodeStatus.Busy, f) + + def whenIdle[A](f: => A) = whenStatus(NodeStatus.Idle, f) + + def whenStatus[A](_status: NodeStatus, f: => A) = if (getStatus == _status) f + + def ensureBusy[A](f: => A): A = { + lastActivityTime = System.currentTimeMillis + if (isBusy) synchronized { + if (isBusy) return f + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + def ensureIdle[A](f: => A): A = ensureIdle(f, true) + + def ensureIdle[A](f: => A, transitionState: Boolean): A = { + if (isIdle) synchronized { + if (isIdle) { + if (transitionState) transition(NodeStatus.Busy) + return Utils.tryFinally(f) { + if (transitionState) transition(NodeStatus.Idle) + callback() + } + } + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + + def ensureAvailable[A](f: => A): A = { + if (NodeStatus.isAvailable(getStatus)) synchronized { + if (NodeStatus.isAvailable(getStatus)) return Utils.tryFinally(f)(callback()) + } + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + def whenAvailable[A](f: => A): A = { + if (NodeStatus.isAvailable(getStatus)) return Utils.tryFinally(f)(callback()) + throw new SchedulerErrorException(20001, "%s is in status %s." format(toString, getStatus)) + } + + protected def callback(): Unit + + def supportCallBackLogs(): Boolean + + protected override def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit = { + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorStatusChangedEvent(this, fromStatus, toStatus)) + } + + override def close(): Unit = { + isExecutorClosed = true + super.close() + } + + override def isClosed(): Boolean = isExecutorClosed +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala new file mode 100644 index 0000000000..3633d4039a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/entity/ExecutorStatusInfo.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.{NodeHealthyInfo, NodeOverLoadInfo} + +import scala.beans.BeanProperty + +class ExecutorStatusInfo { + + @BeanProperty + var status: NodeStatus = NodeStatus.Starting + + @BeanProperty + var healthyInfo: NodeHealthyInfo = null + + @BeanProperty + var overLoadInfo: NodeOverLoadInfo = null + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala new file mode 100644 index 0000000000..8238ef8d57 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHealthyInfoManager.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeHealthy +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeHealthyInfo +import org.springframework.stereotype.Component + +trait NodeHealthyInfoManager { + + def getNodeHealthyInfo(): NodeHealthyInfo + + +} + + +@Component +class DefaultNodeHealthyInfoManager extends NodeHealthyInfoManager with Logging { + + override def getNodeHealthyInfo(): NodeHealthyInfo = { + val nodeHealthyInfo = new NodeHealthyInfo + nodeHealthyInfo.setMsg("") + nodeHealthyInfo.setNodeHealthy(NodeHealthy.Healthy) + nodeHealthyInfo + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala new file mode 100644 index 0000000000..f99cd8f836 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeHeartbeatMsgManager.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +trait NodeHeartbeatMsgManager { + + def getHeartBeatMsg(): String + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala new file mode 100644 index 0000000000..ed8b256785 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/info/NodeOverLoadInfoManager.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.info + +import com.webank.wedatasphere.linkis.common.utils.{Logging, OverloadUtils} +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeOverLoadInfo +import org.springframework.stereotype.Component + +trait NodeOverLoadInfoManager { + // TODO linkis/windows/docker overload + def getNodeOverLoadInfo: NodeOverLoadInfo + +} + +//@ConditionalOnMissingBean(name=Array("nodeOverLoadInfoManager")) +@Component +class DefaultNodeOverLoadInfoManager extends NodeOverLoadInfoManager with Logging { + + override def getNodeOverLoadInfo: NodeOverLoadInfo = { + val nodeOverLoadInfo = new NodeOverLoadInfo + nodeOverLoadInfo.setMaxMemory(OverloadUtils.getProcessMaxMemory) + nodeOverLoadInfo.setUsedMemory(OverloadUtils.getProcessUsedMemory) + nodeOverLoadInfo.setSystemCPUUsed(OverloadUtils.getSystemCPUUsed) + nodeOverLoadInfo.setSystemLeftMemory(OverloadUtils.getSystemFreeMemory) + nodeOverLoadInfo + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala new file mode 100644 index 0000000000..b5b6b27546 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorLockListener.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorLockEvent, ExecutorUnLockEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait ExecutorLockListener extends EngineConnAsyncListener { + + def onAddLock(addLockEvent: ExecutorLockEvent): Unit + + def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + case addLockEvent: ExecutorLockEvent => onAddLock(addLockEvent) + case releaseLockEvent: ExecutorUnLockEvent => onReleaseLock(releaseLockEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala new file mode 100644 index 0000000000..22139eecb2 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/ExecutorStatusListener.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorCompletedEvent, ExecutorCreateEvent, ExecutorStatusChangedEvent} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait ExecutorStatusListener extends EngineConnAsyncListener { + + def onExecutorCreated(executorCreateEvent: ExecutorCreateEvent): Unit + + def onExecutorCompleted(executorCompletedEvent: ExecutorCompletedEvent): Unit + + def onExecutorStatusChanged(executorStatusChangedEvent: ExecutorStatusChangedEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + case executorCreateEvent: ExecutorCreateEvent => onExecutorCreated(executorCreateEvent) + case executorCompletedEvent: ExecutorCompletedEvent => onExecutorCompleted(executorCompletedEvent) + case executorStatusChangedEvent: ExecutorStatusChangedEvent => onExecutorStatusChanged(executorStatusChangedEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + + } + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala new file mode 100644 index 0000000000..6d15d9ff65 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/LogListener.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnSyncListener + +trait LogListener extends EngineConnSyncListener { + + def onLogUpdate(logUpdateEvent: TaskLogUpdateEvent) + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala new file mode 100644 index 0000000000..d6244d49c9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/NodeHealthyListener.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.Event +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.NodeHealthyUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.EngineConnAsyncListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait NodeHealthyListener extends EngineConnAsyncListener { + + + def onNodeHealthyUpdate(nodeHealthyUpdateEvent: NodeHealthyUpdateEvent): Unit + + override def onEvent(event: EngineConnAsyncEvent): Unit = event match { + + case nodeHealthyUpdateEvent: NodeHealthyUpdateEvent => onNodeHealthyUpdate(nodeHealthyUpdateEvent) + case _ => + } + + override def onEventError(event: Event, t: Throwable): Unit = { + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala new file mode 100644 index 0000000000..b60c4a4d4b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/AccessibleExecutorConnAsyncEvent.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.entity.metrics.NodeHealthyInfo + +trait AccessibleExecutorConnAsyncEvent extends EngineConnAsyncEvent { + +} + +case class ExecutorCreateEvent(executor: Executor) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorCompletedEvent(executor: Executor, message: String) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorStatusChangedEvent(executor: Executor, fromStatus: NodeStatus, toStatus: NodeStatus) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorLockEvent(executor: Executor, lock: String) extends AccessibleExecutorConnAsyncEvent + +case class ExecutorUnLockEvent(executor: Executor, lock: String) extends AccessibleExecutorConnAsyncEvent + +case class NodeHealthyUpdateEvent(nodeHealthyInfo: NodeHealthyInfo) extends AccessibleExecutorConnAsyncEvent + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala new file mode 100644 index 0000000000..5623ed7551 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/LogUpdateEvent.scala @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +case class LogUpdateEvent(taskId: String, log: String) extends EngineConnSyncEvent diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala new file mode 100644 index 0000000000..92b3d66126 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/listener/event/TaskEvent.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event + +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo + +trait TaskEvent extends EngineConnSyncEvent { + +} + +case class TaskProgressUpdateEvent(taskId: String, progress: Float, progressInfo: Array[JobProgressInfo]) extends TaskEvent + +case class TaskLogUpdateEvent(taskId: String, log: String) extends TaskEvent + +case class TaskStatusChangedEvent(taskId: String, fromStatus: ExecutionNodeStatus, toStatus: ExecutionNodeStatus) extends TaskEvent + +case class TaskResultCreateEvent(taskId: String, resStr: String, alias: String) extends TaskEvent + +case class TaskResultSizeCreatedEvent(taskId: String, resultSize: Int) extends TaskEvent \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala new file mode 100644 index 0000000000..ae0b60471b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/EngineConnTimedLock.scala @@ -0,0 +1,157 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock + +import java.util.concurrent.{ScheduledFuture, ScheduledThreadPoolExecutor, Semaphore, TimeUnit} + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.ExecutorUnLockEvent +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus + +class EngineConnTimedLock(private var timeout: Long) extends TimedLock with Logging { + + var lock = new Semaphore(1) + val releaseScheduler = new ScheduledThreadPoolExecutor(1) + var releaseTask: ScheduledFuture[_] = null + var lastLockTime: Long = 0 + var lockedBy: AccessibleExecutor = null + + override def acquire(executor: AccessibleExecutor): Unit = { + lock.acquire() + lastLockTime = System.currentTimeMillis() + lockedBy = executor + scheduleTimeout + } + + override def tryAcquire(executor: AccessibleExecutor): Boolean = { + if (null == executor) return false + val succeed = lock.tryAcquire() + debug("try to lock for succeed is " + succeed.toString) + if (succeed) { + lastLockTime = System.currentTimeMillis() + lockedBy = executor + debug("try to lock for add time out task ! Locked by thread : " + lockedBy.getId) + scheduleTimeout + } + succeed + } + + // Unlock callback is not called in release method, because release method is called actively + override def release(): Unit = { + debug("try to release for lock," + lockedBy + ",current thread " + Thread.currentThread().getName) + if (lockedBy != null) { + //&& lockedBy == Thread.currentThread() Inconsistent thread(线程不一致) + debug("try to release for lockedBy and thread ") + if (releaseTask != null) { + releaseTask.cancel(true) + releaseTask = null + releaseScheduler.purge() + } + debug("try to release for lock release success") + lockedBy = null + } + resetLock() + } + + private def resetLock(): Unit = { + lock.release() + lock = new Semaphore(1) + } + + override def forceRelease(): Unit = { + if (isAcquired()) { + if (releaseTask != null) { + releaseTask.cancel(true) + releaseTask = null + releaseScheduler.purge() + } + lock.release() + lockedBy = null + } + resetLock() + } + + private def scheduleTimeout: Unit = { + synchronized { + if (null == releaseTask || releaseTask.isDone) { + releaseTask = releaseScheduler.schedule(new Runnable { + override def run(): Unit = { + synchronized { + if (isExpired()) { + lock.release() + // unlockCallback depends on lockedBy, so lockedBy cannot be set null before unlockCallback + unlockCallback(lock.toString) + info(s"Lock : [${lock.toString} was released due to timeout." ) + resetLock() + } + } + } + }, timeout, TimeUnit.MILLISECONDS) + } + } + } + + override def isAcquired(): Boolean = { + lock.availablePermits() < 1 + } + + override def isExpired(): Boolean = { + if (lastLockTime == 0) return false + System.currentTimeMillis() - lastLockTime > timeout + } + + + override def numOfPending(): Int = { + lock.getQueueLength + } + + override def renew(): Boolean = { + if (lockedBy != null && lockedBy == Thread.currentThread()) { + if (isAcquired && releaseTask != null) { + if (releaseTask.cancel(false)) { + releaseScheduler.purge() + scheduleTimeout + lastLockTime = System.currentTimeMillis() + return true + } + } + } + false + } + + override def resetTimeout(timeout: Long): Unit = synchronized { + if (isAcquired()) { + if (null != releaseTask && !isExpired()) { + releaseTask.cancel(true) + this.timeout = timeout + } + scheduleTimeout + } else { + error("Lock is not acquired, so cannot be reset-Timeout") + } + } + + private def unlockCallback(lockStr: String): Unit = { + if (null != lockedBy) { + lockedBy.transition(NodeStatus.Unlock) + } + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorUnLockEvent(null, lockStr.toString)) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala new file mode 100644 index 0000000000..8ecdb30ffd --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/lock/TimedLock.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor + +trait TimedLock { + + @throws[Exception] + def acquire(executor: AccessibleExecutor): Unit + + def tryAcquire(executor: AccessibleExecutor): Boolean + + @throws[Exception] + def release(): Unit + + @throws[Exception] + def forceRelease(): Unit + + def numOfPending(): Int + + def isAcquired(): Boolean + + def isExpired(): Boolean + + @throws[Exception] + def renew(): Boolean + + def resetTimeout(timeout: Long): Unit +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala new file mode 100644 index 0000000000..e6590c35c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/log/LogHelper.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.log + +import java.util + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.LogListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.TaskLogUpdateEvent +import org.slf4j.LoggerFactory + +object LogHelper { + private val logger = LoggerFactory.getLogger(getClass) + val logCache = new MountLogCache(AccessibleExecutorConfiguration.ENGINECONN_LOG_CACHE_NUM.getValue) + + private var logListener: LogListener = _ + + def setLogListener(logListener: LogListener): Unit = this.logListener = logListener + + def pushAllRemainLogs(): Unit = { +// logger.info(s"start to push all remain logs") + Thread.sleep(30) + //logCache.synchronized{ + if (logListener == null) { + logger.warn("logListener is null, can not push remain logs") + //return + } else { + var logs: util.List[String] = null + logCache.synchronized { + logs = logCache.getRemain + } + if (logs != null && logs.size > 0) { + val sb: StringBuilder = new StringBuilder + import scala.collection.JavaConversions._ + logs map (log => log + "\n") foreach sb.append + logger.info(s"remain logs is ${sb.toString()}") + logListener.onLogUpdate(TaskLogUpdateEvent(null, sb.toString)) + } + } + logger.info("end to push all remain logs") + // } + // if (sendAppender == null){ + // logger.error("SendAppender has not been initialized") + // }else{ + // val logCache = sendAppender.getLogCache + // val logListener = SendAppender.getLogListener + // logCache.synchronized{ + // val logs: util.List[String] = logCache.getRemain + // if (logs.size > 0) { + // val sb: StringBuilder = new StringBuilder + // import scala.collection.JavaConversions._ + // logs map (log => log + "\n") foreach sb.append + // logListener.onLogUpdate(null, sb.toString) + // } + // } + // } + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala new file mode 100644 index 0000000000..66bb93b6fa --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/AccessibleService.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.ExecutorStatusListener +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineSuicideRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext + +trait AccessibleService extends ExecutorStatusListener { + + def stopExecutor: Unit + + def pauseExecutor: Unit + + def reStartExecutor: Boolean + + def dealEngineStopRequest(engineSuicideRequest: EngineSuicideRequest, smc: ServiceMethodContext): Unit + + + /** + * service 需要加定时任务判断Executor是否空闲很久,然后调用该方法进行释放 + */ + def requestManagerReleaseExecutor(msg: String): Unit + + + def dealRequestNodeStatus(requestNodeStatus: RequestNodeStatus): ResponseNodeStatus + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala new file mode 100644 index 0000000000..adf6dc19ad --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultAccessibleService.scala @@ -0,0 +1,177 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorCompletedEvent, ExecutorCreateEvent, ExecutorStatusChangedEvent} +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, SensibleExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.{EngineConnReleaseRequest, EngineSuicideRequest} +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.rpc.Sender +import javax.annotation.PostConstruct +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import scala.collection.JavaConverters._ + + +@Service +class DefaultAccessibleService extends AccessibleService with Logging { + + @Autowired + private var executorHeartbeatService: ExecutorHeartbeatService = _ + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + + @Receiver + override def dealEngineStopRequest(engineSuicideRequest: EngineSuicideRequest, smc: ServiceMethodContext): Unit = { + // todo check user + if (DataWorkCloudApplication.getServiceInstance.equals(engineSuicideRequest.getServiceInstance)) { + stopEngine() + info(s"engine will suiside now.") + ShutdownHook.getShutdownHook.notifyStop() + } else { + if (null != engineSuicideRequest.getServiceInstance) { + error(s"Invalid serviceInstance : ${engineSuicideRequest.getServiceInstance.toString}, will not suicide.") + } else { + error("Invalid empty serviceInstance.") + } + } + } + + private def executorShutDownHook(): Unit = { + var executor: Executor = ExecutorManager.getInstance().getDefaultExecutor + if (null != executor) { + executor.asInstanceOf[SensibleExecutor].transition(NodeStatus.ShuttingDown) + } else { + executor = SensibleExecutor.getDefaultErrorSensibleExecutor() + } + executorHeartbeatService.reportHeartBeatMsg(executor) + info("Reported status shuttingDown to manager.") + } + + override def stopExecutor: Unit = { + // todo + } + + + override def pauseExecutor: Unit = { + + } + + override def reStartExecutor: Boolean = { + true + } + + /** + * Service启动后则启动定时任务 空闲释放 + */ + @PostConstruct + private def init(): Unit = { + val context = EngineConnObject.getEngineCreationContext + val maxFreeTimeVar = AccessibleExecutorConfiguration.ENGINECONN_MAX_FREE_TIME.getValue(context.getOptions) + val maxFreeTimeStr = maxFreeTimeVar.toString + val maxFreeTime = maxFreeTimeVar.toLong + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val executor = ExecutorManager.getInstance().getDefaultExecutor + if (null == executor || !executor.isInstanceOf[AccessibleExecutor]) { + warn("Default is not AccessibleExecutor,do noting") + return + } + info("maxFreeTimeMills is " + maxFreeTime) + val accessibleExecutor = ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[AccessibleExecutor] + if (NodeStatus.isCompleted(accessibleExecutor.getStatus)) { + error(s"${accessibleExecutor.getId()} has completed with status ${accessibleExecutor.getStatus}, now stop it.") + ShutdownHook.getShutdownHook.notifyStop() + } else if (accessibleExecutor.getStatus == NodeStatus.ShuttingDown) { + warn(s"${accessibleExecutor.getId()} is ShuttingDown...") + ShutdownHook.getShutdownHook.notifyStop() + } else if (maxFreeTime > 0 && NodeStatus.isIdle(accessibleExecutor.getStatus) && System.currentTimeMillis - accessibleExecutor.getLastActivityTime > maxFreeTime) { + warn(s"${accessibleExecutor.getId()} has not been used for $maxFreeTimeStr, now try to shutdown it.") + requestManagerReleaseExecutor(" idle release") + } + } + }, 10 * 60 * 1000, AccessibleExecutorConfiguration.ENGINECONN_HEARTBEAT_TIME.getValue.toLong, TimeUnit.MILLISECONDS) + asyncListenerBusContext.addListener(this) + Utils.addShutdownHook(executorShutDownHook()) + } + + private def stopEngine(): Unit = { + Utils.tryAndWarn { + ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[SensibleExecutor].transition(NodeStatus.ShuttingDown) + val executors = ExecutorManager.getInstance().getAllExecutorsMap() + executors.asScala.map{ + kv => kv._2.tryShutdown() + } + executors.clear() + } + } + + /** + * service 需要加定时任务判断Executor是否空闲很久,然后调用该方法进行释放 + */ + + override def requestManagerReleaseExecutor(msg: String): Unit = { + val engineReleaseRequest = new EngineConnReleaseRequest(Sender.getThisServiceInstance, Utils.getJvmUser, msg, EngineConnManager.getEngineConnManager.getEngineConn().getEngineCreationContext.getTicketId) + ManagerService.getManagerService.requestReleaseEngineConn(engineReleaseRequest) + } + + @Receiver + override def dealRequestNodeStatus(requestNodeStatus: RequestNodeStatus): ResponseNodeStatus = { + val status = ExecutorManager.getInstance().getDefaultExecutor match { + case executor: SensibleExecutor => + executor.getStatus + case _ => NodeStatus.Starting + } + val responseNodeStatus = new ResponseNodeStatus + responseNodeStatus.setNodeStatus(status) + responseNodeStatus + } + + override def onExecutorCreated(executorCreateEvent: ExecutorCreateEvent): Unit = { + + } + + override def onExecutorCompleted(executorCompletedEvent: ExecutorCompletedEvent): Unit = { + + } + + override def onExecutorStatusChanged(executorStatusChangedEvent: ExecutorStatusChangedEvent): Unit = { + if (!ExecutorManager.getInstance().getDefaultExecutor.isInstanceOf[AccessibleExecutor]) { + warn("Default is not AccessibleExecutor,do noting") + return + } + val executor = ExecutorManager.getInstance().getDefaultExecutor.asInstanceOf[AccessibleExecutor] + executorHeartbeatService.reportHeartBeatMsg(executor) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala new file mode 100644 index 0000000000..f135cae735 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultExecutorHeartbeatService.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.info.{NodeHealthyInfoManager, NodeHeartbeatMsgManager, NodeOverLoadInfoManager} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.NodeHealthyListener +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.NodeHealthyUpdateEvent +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.entity.{Executor, ResourceExecutor, SensibleExecutor} +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.rpc.Sender +import javax.annotation.PostConstruct +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +@Service +class DefaultExecutorHeartbeatService extends ExecutorHeartbeatService with NodeHealthyListener with Logging { + + + @Autowired + private var nodeHealthyInfoManager: NodeHealthyInfoManager = _ + + @Autowired + private var nodeOverLoadInfoManager: NodeOverLoadInfoManager = _ + + @Autowired(required = false) + private var nodeHeartbeatMsgManager: NodeHeartbeatMsgManager = _ + + private val asyncListenerBusContext = ExecutorListenerBusContext.getExecutorListenerBusContext.getEngineConnAsyncListenerBus + + @PostConstruct + private def init(): Unit = { + asyncListenerBusContext.addListener(this) + val heartbeatTime = AccessibleExecutorConfiguration.ENGINECONN_HEARTBEAT_TIME.getValue.toLong + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = Utils.tryAndWarn { + val executor = ExecutorManager.getInstance().getDefaultExecutor + reportHeartBeatMsg(executor) + } + }, 3 * 60 * 1000, heartbeatTime, TimeUnit.MILLISECONDS) + } + + /** + * 定时上报心跳信息,依据Executor不同进行实现 + * + * @param executor + */ + override def reportHeartBeatMsg(executor: Executor): Unit = { + ManagerService.getManagerService.heartbeatReport(generateHeartBeatMsg(executor)) + } + + + @Receiver + override def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg = { + val executor = ExecutorManager.getInstance().getDefaultExecutor + generateHeartBeatMsg(executor) + } + + + override def onNodeHealthyUpdate(nodeHealthyUpdateEvent: NodeHealthyUpdateEvent): Unit = { + warn(s"node healthy update, tiger heartbeatReport") + val executor = ExecutorManager.getInstance().getDefaultExecutor + reportHeartBeatMsg(executor) + } + + override def generateHeartBeatMsg(executor: Executor): NodeHeartbeatMsg = { + val nodeHeartbeatMsg = new NodeHeartbeatMsg + + nodeHeartbeatMsg.setServiceInstance(Sender.getThisServiceInstance) + nodeHeartbeatMsg.setOverLoadInfo(nodeOverLoadInfoManager.getNodeOverLoadInfo) + nodeHeartbeatMsg.setHealthyInfo(nodeHealthyInfoManager.getNodeHealthyInfo()) + executor match { + case sensibleExecutor: SensibleExecutor => + nodeHeartbeatMsg.setStatus(sensibleExecutor.getStatus) + case _ => + } + executor match { + case resourceExecutor: ResourceExecutor => + nodeHeartbeatMsg.setNodeResource(resourceExecutor.getCurrentNodeResource()) + case _ => + } + if (null != nodeHeartbeatMsgManager) { + nodeHeartbeatMsg.setHeartBeatMsg(nodeHeartbeatMsgManager.getHeartBeatMsg()) + } + nodeHeartbeatMsg + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala new file mode 100644 index 0000000000..7500d9f22b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/DefaultManagerService.scala @@ -0,0 +1,67 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import java.util + +import com.webank.wedatasphere.linkis.engineconn.executor.service.ManagerService +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnReleaseRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.label.LabelReportRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.rpc.Sender + +class DefaultManagerService extends ManagerService { + + + protected def getManagerSender: Sender = { + Sender.getSender(GovernanceCommonConf.MANAGER_SPRING_NAME.getValue) + } + + protected def getEngineConnManagerSender: Sender = { + Sender.getSender(GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue) + } + + + override def labelReport(labels: util.List[Label[_]]): Unit = { + val labelReportRequest = LabelReportRequest(labels, Sender.getThisServiceInstance) + getManagerSender.send(labelReportRequest) + } + + + override def statusReport(status: NodeStatus): Unit = { + val responseNodeStatus = new ResponseNodeStatus + responseNodeStatus.setNodeStatus(status) + getManagerSender.send(responseNodeStatus) + } + + override def requestReleaseEngineConn(engineConnReleaseRequest: EngineConnReleaseRequest): Unit = { + getManagerSender.send(engineConnReleaseRequest) + } + + override def heartbeatReport(nodeHeartbeatMsg: NodeHeartbeatMsg): Unit = { + getManagerSender.send(nodeHeartbeatMsg) + } + + override def reportUsedResource(resourceUsedProtocol: ResourceUsedProtocol): Unit = { + getManagerSender.send(resourceUsedProtocol) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala new file mode 100644 index 0000000000..e12c0650ce --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/EngineConnTimedLockService.scala @@ -0,0 +1,202 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.conf.AccessibleExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.entity.AccessibleExecutor +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.event.{ExecutorLockEvent, ExecutorUnLockEvent} +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.lock.EngineConnTimedLock +import com.webank.wedatasphere.linkis.engineconn.core.executor.ExecutorManager +import com.webank.wedatasphere.linkis.engineconn.executor.listener.ExecutorListenerBusContext +import com.webank.wedatasphere.linkis.governance.common.exception.engineconn.{EngineConnExecutorErrorCode, EngineConnExecutorErrorException} +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineLockType +import com.webank.wedatasphere.linkis.manager.common.protocol.{RequestEngineLock, RequestEngineUnlock, ResponseEngineLock, ResponseEngineUnlock} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + + +class EngineConnTimedLockService extends LockService with Logging { + + private var engineConnLock: EngineConnTimedLock = null + private var lockString: String = null + private var lockType: EngineLockType = EngineLockType.Timed + + + private def isSupportParallelism: Boolean = AccessibleExecutorConfiguration.ENGINECONN_SUPPORT_PARALLELISM.getValue + + /** + * + * + * @param lock + * @return + */ + override def isLockExist(lock: String = null): Boolean = synchronized { + if (isSupportParallelism) true + else if (null != engineConnLock && engineConnLock.isAcquired()) { + if (StringUtils.isNotBlank(lock)) { + if (lock.equals(lockString)) true + else false + } else { + false + } + } else { + false + } + + } + + /** + * Try to lock an Executor in the ExecutorManager. If the lock is successful, it will return the Executor ID as the ID. + * 尝试去锁住ExecutorManager里的一个Executor,如果锁成功的话,将返回Executor ID作为标识 + * + * @return + */ + @throws[EngineConnExecutorErrorException] + override def tryLock(requestEngineLock: RequestEngineLock): Option[String] = synchronized { + if (null != engineConnLock && engineConnLock.isAcquired()) return None + this.lockType = requestEngineLock.lockType + lockType match { + case EngineLockType.Always => + timedLock(-1) + case EngineLockType.Timed => + timedLock(requestEngineLock.timeout) + case o: Any => + error("Invalid lockType : " + BDPJettyServerHelper.gson.toJson(o)) + return Some(null) + } + + } + + private def timedLock(timeout: Long): Option[String] = { + + // Lock is binded to engineconn, so choose default executor + ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + debug("try to lock for executor state is " + accessibleExecutor.getStatus) + debug("try to lock for executor id is " + accessibleExecutor.getId) + if (null == engineConnLock) { + engineConnLock = new EngineConnTimedLock(timeout) + debug("try to lock for executor get new lock " + engineConnLock) + } + if (engineConnLock.tryAcquire(accessibleExecutor)) { + debug("try to lock for tryAcquire is true ") + this.lockString = engineConnLock.lock.toString + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorLockEvent(accessibleExecutor, lockString)) + accessibleExecutor.transition(NodeStatus.Idle) + Some(lockString) + } else None + case _ => + val msg = s"Invalid executor or not instance of SensibleEngine." + error(msg) + throw new EngineConnExecutorErrorException(EngineConnExecutorErrorCode.INVALID_ENGINE_TYPE, msg) + } + } + + /** + * Unlock(解锁) + * + * @param lock + */ + override def unlock(lock: String): Boolean = synchronized { + info("try to unlock for lockEntity is " + engineConnLock.toString + ",and lock is " + lock + ",acquired is " + engineConnLock.isAcquired().toString) + if (isLockExist(lock)) { + info(s"try to unlock lockEntity : lockString=${lockString},lockedBy=${engineConnLock.lockedBy.getId()}") + engineConnLock.release() + this.lockString = null + ExecutorListenerBusContext.getExecutorListenerBusContext().getEngineConnAsyncListenerBus.post(ExecutorUnLockEvent(null, lock)) + ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + accessibleExecutor.transition(NodeStatus.Unlock) + case _ => + val msg = s"Invalid executor or not instance of SensibleEngine." + error(msg) + } + true + } else { + false + } + } + + @Receiver + override def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock = { + if (StringUtils.isBlank(requestEngineUnlock.lock)) { + error("Invalid requestEngineUnlock: ") + ResponseEngineUnlock(false) + } else { + ResponseEngineUnlock(unlock(requestEngineUnlock.lock)) + } + } + + override def onAddLock(addLockEvent: ExecutorLockEvent): Unit = { + + } + + override def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit = { + + } + + + @Receiver + override def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + super.requestLock(requestEngineLock) + } +} + +class EngineConnConcurrentLockService extends LockService { + + override def isLockExist(lock: String): Boolean = true + + override def tryLock(requestEngineLock: RequestEngineLock): Option[String] = { + /*ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + // Concurrent Engine don't change status when get lock, status will change in other rules +// accessibleExecutor.transition(NodeStatus.Idle) + case _ => + }*/ + Some("lock") + } + + /** + * Unlock(解锁) + * + * @param lock + */ + override def unlock(lock: String): Boolean = { + /*ExecutorManager.getInstance().getDefaultExecutor match { + case accessibleExecutor: AccessibleExecutor => + accessibleExecutor.transition(NodeStatus.Unlock) + case _ => + }*/ + true + } + + @Receiver + override def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock = ResponseEngineUnlock(true) + + override def onAddLock(addLockEvent: ExecutorLockEvent): Unit = {} + + override def onReleaseLock(releaseLockEvent: ExecutorUnLockEvent): Unit = {} + + @Receiver + override def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + super.requestLock(requestEngineLock) + } + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala new file mode 100644 index 0000000000..21a16cc922 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/ExecutorHeartbeatService.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{NodeHeartbeatMsg, NodeHeartbeatRequest} + +trait ExecutorHeartbeatService { + + /** + * 定时上报心跳信息,依据Executor不同进行实现 + * + * @param executor + */ + def reportHeartBeatMsg(executor: Executor): Unit + + def generateHeartBeatMsg(executor: Executor): NodeHeartbeatMsg + + + def dealNodeHeartbeatRequest(nodeHeartbeatRequest: NodeHeartbeatRequest): NodeHeartbeatMsg + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala new file mode 100644 index 0000000000..9f82f1345e --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LockService.scala @@ -0,0 +1,61 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.listener.ExecutorLockListener +import com.webank.wedatasphere.linkis.manager.common.protocol.{RequestEngineLock, RequestEngineUnlock, ResponseEngineLock, ResponseEngineUnlock} +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + +trait LockService extends ExecutorLockListener with Logging { + + def isLockExist(lock: String): Boolean + + def tryLock(requestEngineLock: RequestEngineLock): Option[String] + + /** + * Unlock(解锁) + * + * @param lock + */ + def unlock(lock: String): Boolean + + def requestLock(requestEngineLock: RequestEngineLock): ResponseEngineLock = { + var response: ResponseEngineLock = null + tryLock(requestEngineLock) match { + case Some(lockStr) => + // Engine can be locked + if (!StringUtils.isBlank(lockStr)) { + // lock success + response = ResponseEngineLock(true, lockStr, s"Lock for ${requestEngineLock.timeout} ms") + } else { + // lock failed + response = ResponseEngineLock(false, lockStr, "lock str is blank") + } + case None => + // Engine is busy + response = ResponseEngineLock(false, null, "Engine is busy.") + } + info ("RequestLock : " + BDPJettyServerHelper.gson.toJson(requestEngineLock) + "\nResponseLock : " + BDPJettyServerHelper.gson.toJson(response)) + response + } + + def requestUnLock(requestEngineUnlock: RequestEngineUnlock): ResponseEngineUnlock + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala new file mode 100644 index 0000000000..18e2e84969 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/service/LogService.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.service + +import com.webank.wedatasphere.linkis.engineconn.acessible.executor.log.LogCache + +trait LogService { + + + def getLogCache(): LogCache + + def sendLog(): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala new file mode 100644 index 0000000000..9c7e4b4654 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/accessible-executor/src/main/scala/com/webank/wedatasphere/linkis/engineconn/acessible/executor/utils/AccessableExecutorUtils.scala @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.acessible.executor.utils + +object AccessibleExecutorUtils { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml new file mode 100644 index 0000000000..bff3c83f7d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/pom.xml @@ -0,0 +1,83 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-callback-service + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-message-scheduler + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala new file mode 100644 index 0000000000..2d4cd3f14b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnAfterStartCallback.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import com.webank.wedatasphere.linkis.common.ServiceInstance + +class EngineConnAfterStartCallback(emInstance: ServiceInstance) extends AbstractEngineConnStartUpCallback(emInstance) { + + override def callback(): Unit = { + + } +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala new file mode 100644 index 0000000000..a19be12c8a --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnCallback.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.protocol.message.RequestProtocol +import com.webank.wedatasphere.linkis.rpc.Sender + +trait EngineConnCallback { + + protected def getEMSender: Sender + + def callback(): Unit + +} + +abstract class AbstractEngineConnStartUpCallback(emInstance: ServiceInstance) extends EngineConnCallback { + + override protected def getEMSender: Sender = { + Sender.getSender(emInstance) + } + + + def callback(protocol: RequestProtocol): Unit = { + getEMSender.send(protocol) + } +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala new file mode 100644 index 0000000000..31f8a3a2d1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnPidCallback.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +import java.lang.management.ManagementFactory + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.governance.common.protocol.task.ResponseEngineConnPid +import com.webank.wedatasphere.linkis.rpc.Sender + + +class EngineConnPidCallback(emInstance: ServiceInstance) extends AbstractEngineConnStartUpCallback(emInstance) { + + override def callback(): Unit = { + val pid = ManagementFactory.getRuntimeMXBean.getName.split("@")(0) + val instance = Sender.getThisServiceInstance + val context = EngineConnObject.getEngineCreationContext + callback(ResponseEngineConnPid(instance, pid, context.getTicketId)) + } + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala new file mode 100644 index 0000000000..318615644f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/callback-service/src/main/scala/com/webank/wedatasphere/linkis/engineconn/callback/service/EngineConnTimedCallback.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.callback.service + +/** + * 常规callBack + */ +trait EngineConnTimedCallback extends EngineConnCallback { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml new file mode 100644 index 0000000000..a2f59278e9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/pom.xml @@ -0,0 +1,89 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-executor-core + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + com.webank.wedatasphere.linkis + linkis-manager-common + ${linkis.version} + + + + com.webank.wedatasphere.linkis + linkis-engineconn-common + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala new file mode 100644 index 0000000000..88ab804753 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/conf/EngineConnExecutorConfiguration.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + +object EngineConnExecutorConfiguration { + + + val TMP_PATH = CommonVars("wds.linkis.dataworkclod.engine.tmp.path", "file:///tmp/") + + val ENGINE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.engine.application.name", "") + + val ENGINE_LOG_PREFIX = CommonVars("wds.linkis.log4j2.prefix", "/appcom/logs/linkis/" + ENGINE_SPRING_APPLICATION_NAME.getValue) + + val CLEAR_LOG = CommonVars("wds.linkis.log.clear", false) + + + val ENGINE_IGNORE_WORDS = CommonVars("wds.linkis.engine.ignore.words", "org.apache.spark.deploy.yarn.Client") + + val ENGINE_PASS_WORDS = CommonVars("wds.linkis.engine.pass.words", "org.apache.hadoop.hive.ql.exec.Task") + + + + + val ENTRANCE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.entrance.application.name", "linkis-cg-entrance") + + val ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY = CommonVars("wds.linkis.engine.listener.async.queue.size.max", 300) + + val ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX = CommonVars("wds.linkis.engine.listener.async.consumer.thread.max", 5) + + val ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX = CommonVars("wds.linkis.engine.listener.async.consumer.freetime.max", new TimeType("5000ms")) + + // todo better to rename + val EXECUTOR_MANAGER_SERVICE_CLAZZ = CommonVars("wds.linkis.engineconn.executor.manager.service.clazz", "com.webank.wedatasphere.linkis.engineconn.acessible.executor.service.DefaultManagerService") + + /*val EXECUTOR_MANAGER_CLAZZ = CommonVars("wds.linkis.engineconn.executor.manager.claazz", "")*/ + + val DEFAULT_EXECUTOR_NAME = CommonVars("wds.linkis.engineconn.executor.default.name", "ComputationExecutor") +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala new file mode 100644 index 0000000000..f9e0619b97 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/Executor.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.common.utils.Logging + +trait Executor extends Logging { + + def getId(): String + + def init(): Unit + + def tryReady(): Boolean + + def tryShutdown(): Boolean + + def tryFailed(): Boolean + + /** + * 仅用于Kill Executor + * EngineConn kill 在AccessibleService + */ + def close(): Unit = { + warn(s"executor ${getId()} exit by close") + } + + def isClosed(): Boolean + +} + +trait ConcurrentExecutor extends Executor { + + def getConcurrentLimit: Int + + def killAll(): Unit + +} + diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala new file mode 100644 index 0000000000..e95bdd6cb9 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/LabelExecutor.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import java.util + +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait LabelExecutor extends Executor { + + def getExecutorLabels(): util.List[Label[_]] + + def setExecutorLabels(labels: util.List[Label[_]]): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala new file mode 100644 index 0000000000..8ec322dab6 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/ResourceExecutor.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.resource.NodeResource + +trait ResourceExecutor extends Executor { + + + def requestExpectedResource(expectedResource: NodeResource): NodeResource + + def getCurrentNodeResource(): NodeResource + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala new file mode 100644 index 0000000000..83ee4d39c1 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/SensibleExecutor.scala @@ -0,0 +1,80 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus + +import scala.beans.BeanProperty + +trait SensibleExecutor extends Executor { + + protected var status: NodeStatus = NodeStatus.Starting + + @BeanProperty + var lastActivityTime = System.currentTimeMillis + + def getStatus: NodeStatus = status + + protected def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit + + def transition(toStatus: NodeStatus) = this synchronized { + lastActivityTime = System.currentTimeMillis + this.status match { + case NodeStatus.Failed | NodeStatus.Success => + warn(s"$toString attempt to change status ${this.status} => $toStatus, ignore it.") + case NodeStatus.ShuttingDown => + toStatus match { + case NodeStatus.Failed | NodeStatus.Success => + val oldState = status + this.status = toStatus + onStatusChanged(oldState, toStatus) + case _ => warn(s"$toString attempt to change a Executor.ShuttingDown session to $toStatus, ignore it.") + } + case _ => + + } + info(s"$toString change status ${status} => $toStatus.") + val oldState = status + this.status = toStatus + onStatusChanged(oldState, toStatus) + } + +} + +object SensibleExecutor { + + lazy val defaultErrorSensibleExecutor: SensibleExecutor = new SensibleExecutor { + override def getStatus: NodeStatus = NodeStatus.ShuttingDown + + override protected def onStatusChanged(fromStatus: NodeStatus, toStatus: NodeStatus): Unit = {} + + override def getId(): String = "0" + + override def init(): Unit = {} + + override def tryReady(): Boolean = false + + override def tryShutdown(): Boolean = true + + override def tryFailed(): Boolean = true + + override def isClosed(): Boolean = true + } + + def getDefaultErrorSensibleExecutor(): SensibleExecutor = defaultErrorSensibleExecutor + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala new file mode 100644 index 0000000000..368ad78027 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/entity/YarnExecutor.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.entity + +import scala.beans.BeanProperty + +trait YarnExecutor extends Executor { + + @BeanProperty + var applicationId: String + + @BeanProperty + var applicationURL: String + + @BeanProperty + var yarnMode: String + + @BeanProperty + var queue: String + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala new file mode 100644 index 0000000000..5d68f71eef --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListener.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.EventListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +trait EngineConnAsyncListener extends EventListener { + + def onEvent(event: EngineConnAsyncEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala new file mode 100644 index 0000000000..160f4b7a1c --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnAsyncListenerBus.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerEventBus +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnAsyncEvent + +class EngineConnAsyncListenerBus(eventQueueCapacity: Int, name: String, + listenerConsumerThreadSize: Int, + listenerThreadMaxFreeTime: Long) + extends ListenerEventBus[EngineConnAsyncListener, EngineConnAsyncEvent](eventQueueCapacity, name)(listenerConsumerThreadSize, listenerThreadMaxFreeTime) { + + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: EngineConnAsyncListener, event: EngineConnAsyncEvent): Unit = { + listener.onEvent(event) + } + +} + +object EngineConnAsyncListenerBus { + + def NAME: String = "EngineServerAsyncListenerBus" + + lazy val getInstance = new EngineConnAsyncListenerBus( + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY.getValue, + NAME, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX.getValue, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX.getValue.toLong) + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala new file mode 100644 index 0000000000..e40263eeae --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListener.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.EventListener +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +trait EngineConnSyncListener extends EventListener { + + def onEvent(event: EngineConnSyncEvent): Unit + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala new file mode 100644 index 0000000000..9a147375f0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/EngineConnSyncListenerBus.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.common.listener.ListenerBus +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.executor.listener.event.EngineConnSyncEvent + +class EngineConnSyncListenerBus extends ListenerBus[EngineConnSyncListener, EngineConnSyncEvent] with Logging { + + /** + * Post an event to the specified listener. `onPostEvent` is guaranteed to be called in the same + * thread for all listeners. + */ + override protected def doPostEvent(listener: EngineConnSyncListener, event: EngineConnSyncEvent): Unit = { + debug(s"$listener start to deal event $event") + listener.onEvent(event) + debug(s"$listener Finished to deal event $event") + } +} + +object EngineConnSyncListenerBus { + + def NAME: String = "EngineServerSyncListenerBus" + + lazy val getInstance = new EngineConnSyncListenerBus() + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala new file mode 100644 index 0000000000..cfb2837210 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/ExecutorListenerBusContext.scala @@ -0,0 +1,45 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener + +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration + +class ExecutorListenerBusContext { + + private val engineConnAsyncListenerBus: EngineConnAsyncListenerBus = new EngineConnAsyncListenerBus( + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_QUEUE_CAPACITY.getValue, + "EngineConn-Asyn-Thread", + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_MAX.getValue, + EngineConnExecutorConfiguration.ENGINE_SERVER_LISTENER_ASYNC_CONSUMER_THREAD_FREE_TIME_MAX.getValue.toLong + ) + + private val engineConnSyncListenerBus: EngineConnSyncListenerBus = new EngineConnSyncListenerBus + + def getEngineConnAsyncListenerBus: EngineConnAsyncListenerBus = { + engineConnAsyncListenerBus + } + + def getEngineConnSyncListenerBus: EngineConnSyncListenerBus = engineConnSyncListenerBus + +} + +object ExecutorListenerBusContext { + + private val executorListenerBusContext = new ExecutorListenerBusContext + + def getExecutorListenerBusContext() = executorListenerBusContext +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala new file mode 100644 index 0000000000..6161fa2212 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnAsyncEvent.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener.event + +import com.webank.wedatasphere.linkis.common.listener.Event + +trait EngineConnAsyncEvent extends Event { + + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala new file mode 100644 index 0000000000..4c9a56801b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/listener/event/EngineConnSyncEvent.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.listener.event + +import com.webank.wedatasphere.linkis.common.listener.Event + +trait EngineConnSyncEvent extends Event { + +} diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala new file mode 100644 index 0000000000..30ae088f6d --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/LabelService.scala @@ -0,0 +1,53 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.service + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.engineconn.executor.entity.Executor +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait LabelService { + + /*def labelUpdate(labelUpdateRequest: LabelUpdateRequest): Unit*/ + + def labelReport(labels: util.List[Label[_]], executor: Executor): Unit + +} + +class DefaultLabelService extends LabelService with Logging { + + + /*override def labelUpdate(labelUpdateRequest: LabelUpdateRequest): Unit = ???*/ + + override def labelReport(labels: util.List[Label[_]], executor: Executor): Unit = { + info(s"executor ${executor.getId()} prepare to report Labels ") + ManagerService.getManagerService.labelReport(labels) + info(s"executor ${executor.getId()} end to report Labels ") + } + + +} + +object LabelService { + + private val labelService = new DefaultLabelService + + def getLabelService: LabelService = this.labelService + +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala new file mode 100644 index 0000000000..a79ae003eb --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/executor-core/src/main/scala/com/webank/wedatasphere/linkis/engineconn/executor/service/ManagerService.scala @@ -0,0 +1,46 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.engineconn.executor.service + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.engineconn.executor.conf.EngineConnExecutorConfiguration +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.engine.EngineConnReleaseRequest +import com.webank.wedatasphere.linkis.manager.common.protocol.node.NodeHeartbeatMsg +import com.webank.wedatasphere.linkis.manager.common.protocol.resource.ResourceUsedProtocol +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +trait ManagerService { + + def labelReport(labels: java.util.List[Label[_]]): Unit + + def statusReport(status: NodeStatus): Unit + + def requestReleaseEngineConn(engineConnReleaseRequest: EngineConnReleaseRequest): Unit + + def heartbeatReport(nodeHeartbeatMsg: NodeHeartbeatMsg): Unit + + def reportUsedResource(resourceUsedProtocol: ResourceUsedProtocol): Unit + +} + +object ManagerService { + + private val managerService: ManagerService = Utils.getClassInstance[ManagerService](EngineConnExecutorConfiguration.EXECUTOR_MANAGER_SERVICE_CLAZZ.getValue) + + def getManagerService = managerService +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml new file mode 100644 index 0000000000..383a4f6d4b --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-executor/resource-executor/pom.xml @@ -0,0 +1,70 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + 4.0.0 + + linkis-resource-executor + + + + com.webank.wedatasphere.linkis + linkis-executor-core + ${linkis.version} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml new file mode 100644 index 0000000000..df14b7a979 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/pom.xml @@ -0,0 +1,72 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../../pom.xml + + 4.0.0 + + linkis-engineconn-launch + + + + + com.webank.wedatasphere.linkis + linkis-engineconn-core + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala new file mode 100644 index 0000000000..4b8fb5de9f --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-launch/src/main/scala/com/webank/wedatasphere/linkis/engineconn/launch/EngineConnServer.scala @@ -0,0 +1,98 @@ +package com.webank.wedatasphere.linkis.engineconn.launch + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.engineconn.common.creation.{DefaultEngineCreationContext, EngineCreationContext} +import com.webank.wedatasphere.linkis.engineconn.common.execution.EngineExecution +import com.webank.wedatasphere.linkis.engineconn.common.hook.EngineConnHook +import com.webank.wedatasphere.linkis.engineconn.core.EngineConnObject +import com.webank.wedatasphere.linkis.engineconn.core.engineconn.EngineConnManager +import com.webank.wedatasphere.linkis.engineconn.core.util.EngineConnUtils +import com.webank.wedatasphere.linkis.engineconn.core.hook.ShutdownHook +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.utils.EngineConnArgumentsParser +import com.webank.wedatasphere.linkis.manager.engineplugin.common.launch.process.Environment +import com.webank.wedatasphere.linkis.manager.label.builder.factory.{LabelBuilderFactory, StdLabelBuilderFactory} +import com.webank.wedatasphere.linkis.manager.label.entity.Label + +import scala.collection.JavaConversions._ +import scala.collection.mutable.ArrayBuffer + + +object EngineConnServer extends Logging { + + + private val engineCreationContext: EngineCreationContext = new DefaultEngineCreationContext + private val labelBuilderFactory: LabelBuilderFactory = new StdLabelBuilderFactory + + var isReady = false + + def main(args: Array[String]): Unit = { + info("<<---------------------EngineConnServer Start --------------------->>") + + Utils.tryCatch { + // 1. 封装EngineCreationContext + init(args) + info("Finished to create EngineCreationContext") + EngineConnHook.getEngineConnHooks.foreach(_.beforeCreateEngineConn(getEngineCreationContext)) + info("Finished to execute hook of beforeCreateEngineConn") + //2. 创建EngineConn + val engineConn = getEngineConnManager.createEngineConn(getEngineCreationContext) + info(s"Finished to create engineConn that type is ${engineConn.getEngineType()}") + EngineConnHook.getEngineConnHooks.foreach(_.beforeExecutionExecute(getEngineCreationContext, engineConn)) + info("Finished to execute hook of beforeExecutionExecute") + //3. 注册的executions 执行 + getEngineExecutions.foreach(_.execute(getEngineCreationContext, engineConn)) + EngineConnObject.setReady + info("Finished to execute executions") + EngineConnHook.getEngineConnHooks.foreach(_.afterExecutionExecute(getEngineCreationContext, engineConn)) + info("Finished to execute hook of afterExecutionExecute") + EngineConnHook.getEngineConnHooks.foreach(_.afterEngineServerStartSuccess(getEngineCreationContext, engineConn)) + } { t => + EngineConnHook.getEngineConnHooks.foreach(_.afterEngineServerStartFailed(getEngineCreationContext, t)) + } + + //4. 等待Executions执行完毕 + ShutdownHook.getShutdownHook.waitForStopOrError() + info("<<---------------------EngineConnServer Exit --------------------->>") + System.exit(ShutdownHook.getShutdownHook.getExitCode()) + } + + /** + * + * @param args + */ + private def init(args: Array[String]): Unit = { + val arguments = EngineConnArgumentsParser.getEngineConnArgumentsParser.parseToObj(args) + val engineConf = arguments.getEngineConnConfMap + this.engineCreationContext.setUser(engineConf.getOrElse("user", Utils.getJvmUser)) + this.engineCreationContext.setTicketId(engineConf.getOrElse("ticketId", "")) + val host = CommonVars(Environment.ECM_HOST.toString, "127.0.0.1").getValue + val port = CommonVars(Environment.ECM_PORT.toString, "80").getValue + this.engineCreationContext.setEMInstance(ServiceInstance(GovernanceCommonConf.ENGINE_CONN_MANAGER_SPRING_NAME.getValue, s"$host:$port")) + val labels = new ArrayBuffer[Label[_]] + val labelArgs = engineConf.filter(_._1.startsWith(EngineConnArgumentsParser.LABEL_PREFIX)) + if (labelArgs.nonEmpty) { + labelArgs.foreach { case (key, value) => + labels += labelBuilderFactory.createLabel[Label[_]](key.replace(EngineConnArgumentsParser.LABEL_PREFIX, ""), value) + } + engineCreationContext.setLabels(labels.toList) + } + val jMap = new java.util.HashMap[String, String](engineConf.size) + jMap.putAll(engineConf) + this.engineCreationContext.setOptions(jMap) + this.engineCreationContext.setArgs(args) + EngineConnObject.setEngineCreationContext(this.engineCreationContext) + info("Finished to init engineCreationContext" + EngineConnUtils.GSON.toJson(engineCreationContext)) + } + + def getEngineCreationContext: EngineCreationContext = this.engineCreationContext + + private def getEngineConnManager: EngineConnManager = EngineConnManager.getEngineConnManager + + private def getEngineExecutions: Array[EngineExecution] = EngineExecution.getEngineExecutions + + private def getShutdownHook: ShutdownHook = ShutdownHook.getShutdownHook + +} diff --git a/linkis-computation-governance/linkis-engineconn/pom.xml b/linkis-computation-governance/linkis-engineconn/pom.xml new file mode 100644 index 0000000000..07d1c6d4a0 --- /dev/null +++ b/linkis-computation-governance/linkis-engineconn/pom.xml @@ -0,0 +1,42 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + 4.0.0 + + linkis-engineconn + pom + + linkis-engineconn-common + linkis-engineconn-core + linkis-engineconn-executor/executor-core + linkis-engineconn-launch + linkis-engineconn-executor/accessible-executor + linkis-engineconn-executor/resource-executor + linkis-engineconn-executor/callback-service + linkis-computation-engineconn + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/pom.xml b/linkis-computation-governance/linkis-entrance-client/pom.xml new file mode 100644 index 0000000000..e88dff6d64 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/pom.xml @@ -0,0 +1,73 @@ + + + + + 4.0.0 + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + + linkis-entrance-client + + + + com.webank.wedatasphere.linkis + linkis-entrance + ${linkis.version} + + + com.webank.wedatasphere.linkis + linkis-io-entrance + + + + + com.webank.wedatasphere.linkis + linkis-rpc + ${linkis.version} + provided + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + + \ No newline at end of file diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java index 06c3415bb1..231eca71f5 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineBuilderBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineBuilderBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java index daf155ebd0..98f3c0f3fd 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineRequesterBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineRequesterBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java index 6bf9968452..6a51a80923 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEngineSelectorBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEngineSelectorBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java index daf074b80a..94a0735f51 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientEntranceParserBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientEntranceParserBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java index be9f298ff4..9f1d949062 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientGroupFactoryBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientGroupFactoryBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java index 4ac97bece0..6b7a58f2c1 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/ClientInterceptorsBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = ClientInterceptorsBeanAnnotation.BEAN_NAME) diff --git a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java similarity index 97% rename from ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java index 5a606c0290..f327db1982 100644 --- a/ujes/entranceclient/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/annotation/DefaultEntranceClientBeanAnnotation.java @@ -27,9 +27,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Created by johnnwang on 2019/2/15. - */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean(value = DefaultEntranceClientBeanAnnotation.BEAN_NAME) diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java new file mode 100644 index 0000000000..ac0fbb3c3c --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/java/com/webank/wedatasphere/linkis/entranceclient/conf/ClientSpringConfiguration.java @@ -0,0 +1,97 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.conf; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import com.webank.wedatasphere.linkis.common.conf.CommonVars; +import com.webank.wedatasphere.linkis.entrance.conf.EntranceSpringConfiguration; +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext; +import com.webank.wedatasphere.linkis.entranceclient.EntranceClient; +import com.webank.wedatasphere.linkis.entranceclient.EntranceClientImpl; +import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEntranceParserBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientInterceptorsBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.annotation.DefaultEntranceClientBeanAnnotation; +import com.webank.wedatasphere.linkis.entranceclient.context.ClientEntranceParser; +import com.webank.wedatasphere.linkis.rpc.RPCReceiveRestful; +import com.webank.wedatasphere.linkis.rpc.conf.RPCConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +@AutoConfigureBefore({EntranceSpringConfiguration.class, RPCReceiveRestful.class}) +class ClientSpringConfiguration { + + private Logger logger = LoggerFactory.getLogger(getClass()); + + { + logger.info("start a multi-entrance application..."); + } + + @ClientEntranceParserBeanAnnotation + @ConditionalOnMissingBean(name = {ClientEntranceParserBeanAnnotation.BEAN_NAME}) + public ClientEntranceParser generateClientEntranceParser() { + return new ClientEntranceParser(); + } + + + @ClientInterceptorsBeanAnnotation + @ConditionalOnMissingBean(name = {ClientInterceptorsBeanAnnotation.BEAN_NAME}) + public EntranceInterceptor[] generateEntranceInterceptor() { + return new EntranceInterceptor[0]; + } + + + @DefaultEntranceClientBeanAnnotation + @Conditional(MultiEntranceCondition.class) + public EntranceClient generateEntranceClient(@ClientEntranceParserBeanAnnotation.ClientEntranceParserAutowiredAnnotation ClientEntranceParser clientEntranceParser, + @ClientInterceptorsBeanAnnotation.ClientInterceptorsAutowiredAnnotation EntranceInterceptor[] clientInterceptors, + @Autowired EntranceSchedulerContext entranceSchedulerContext) { + logger.warn("try to check the rpc receiver consumer threadPool..."); + setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY_FOR_CLIENT()); + setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX_FOR_CLIENT()); + EntranceClientImpl client = EntranceClientImpl.apply(ClientConfiguration.CLIENT_DEFAULT_NAME()); + logger.warn("Multi-entrance application is ready to initial EntranceClient " + client.getEntranceClientName()); + client.init(clientEntranceParser, entranceSchedulerContext, clientInterceptors, ClientConfiguration.CLIENT_DEFAULT_PARALLELISM_USERS().getValue()); + return client; + } + +// @EventListener +// public void onApplicationStarting(ApplicationStartingEvent applicationStartingEvent) { +// if(MultiEntranceCondition.isMultiEntranceApplication()) { +// logger.warn("start a multi-entrance application, now try to check the rpc receiver consumer threadPool..."); +// setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_QUEUE_CAPACITY_FOR_CLIENT()); +// setClientValue(RPCConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX(), ClientConfiguration.BDP_RPC_RECEIVER_ASYN_CONSUMER_THREAD_MAX_FOR_CLIENT()); +// setClientValue(EntranceConfiguration.CONCURRENT_ENGINE_MAX_PARALLELISM(), ClientConfiguration.CONCURRENT_ENGINE_MAX_PARALLELISM_FOR_CLIENT()); +// } +// } + + private void setClientValue(CommonVars> fromConf, CommonVars toConf) { + int queueSize = Integer.parseInt(fromConf.getValue().toString()); + int queueSizeValue = toConf.getValue(); + if (queueSize < queueSizeValue) { + String key = fromConf.key(); + DataWorkCloudApplication.setProperty(key, String.valueOf(queueSizeValue)); + logger.warn("Multi-entrance application set " + key + "=" + queueSizeValue); + } + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories b/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..715812457a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.webank.wedatasphere.linkis.entranceclient.conf.ClientForEntranceSpringConfiguration,\ +com.webank.wedatasphere.linkis.entranceclient.conf.ClientSpringConfiguration \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala index cb3d225d3e..f4a4ce35c8 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EngineApplicationNameFactory.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient import com.webank.wedatasphere.linkis.entranceclient.conf.ClientConfiguration.{CLIENT_ENGINE_MANAGER_SPRING_APPLICATION_NAME, CLIENT_ENGINE_SPRING_APPLICATION_NAME} -/** - * Created by johnnwang on 2019/1/22. - */ trait EngineApplicationNameFactory { private var engineApplicationName: String = CLIENT_ENGINE_SPRING_APPLICATION_NAME.getValue diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala similarity index 96% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala index ef47c59060..d0cd9fb041 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClient.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient import com.webank.wedatasphere.linkis.entranceclient.execute.ClientJob -/** - * Created by johnnwang on 2019/1/22. - */ trait EntranceClient { def getEntranceClientName: String diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala new file mode 100644 index 0000000000..fe4923a63f --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/EntranceClientImpl.scala @@ -0,0 +1,131 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.context.DefaultEntranceContext +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext +import com.webank.wedatasphere.linkis.entrance.server.DefaultEntranceServer +import com.webank.wedatasphere.linkis.entrance.{EntranceContext, EntranceServer} +import com.webank.wedatasphere.linkis.entranceclient.execute._ +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +class EntranceClientImpl private() extends EntranceClient with EngineApplicationNameFactory + with EngineManagerApplicationNameFactory with Logging { + + private var entranceServer: EntranceServer = _ + private var clientName: String = _ + + + def setClientName(clientName: String): Unit = this.clientName = clientName + + + def init(entranceServer: EntranceServer): Unit = { + this.entranceServer = entranceServer + } + + def init(entranceContext: EntranceContext): Unit = init(new DefaultEntranceServer(entranceContext)) + + def init(clientEntranceParser: context.ClientEntranceParser, schedulerContext: EntranceSchedulerContext, interceptors: Array[EntranceInterceptor], + maxParallelismUsers: Int): Unit = if (entranceServer == null) synchronized { + if (entranceServer == null) { + val scheduler = new ParallelScheduler(schedulerContext) + scheduler.init() + scheduler.start() + val entranceContext = new DefaultEntranceContext(clientEntranceParser, new context.ClientPersistenceManager, new context.ClientLogManager, + scheduler, interceptors, null, Array.empty) + init(entranceContext) + } + } + + private def executeUntil[T](code: String, user: String, creator: String, + params: java.util.Map[String, Any], op: ClientJob => T): T = { + val execId = executeJob(code, user, creator, params) + entranceServer.getJob(execId).foreach { + case job: ClientJob => + job.waitForComplete() + return op(job) + } + throw new EntranceErrorException(50003, s"execute failed, cannot find the job $execId.") + } + + override def getEntranceClientName: String = if(StringUtils.isNotEmpty(clientName)) clientName else entranceServer.getName + + override def execute(code: String, user: String, creator: String): Boolean = execute(code, user, creator, null) + + override def execute(code: String, user: String, creator: String, + params: java.util.Map[String, Any]): Boolean = + executeUntil(code, user, creator, params, job => + if (job.isSucceed) true else false) + + override def executeJob(code: String, user: String, creator: String): String = executeJob(code, user, creator, null) + + override def executeJob(code: String, user: String, creator: String, params: util.Map[String, Any]): String = { + val requestMap = new JMap[String, Any] + requestMap.put(TaskConstant.EXECUTIONCODE, code) + requestMap.put(TaskConstant.UMUSER, user) + requestMap.put(TaskConstant.REQUESTAPPLICATIONNAME, creator) + if(params != null && !params.isEmpty) { + if(params.containsKey(EntranceServer.DO_NOT_PRINT_PARAMS_LOG)) { + requestMap.put(EntranceServer.DO_NOT_PRINT_PARAMS_LOG, params.get(EntranceServer.DO_NOT_PRINT_PARAMS_LOG)) + params.remove(EntranceServer.DO_NOT_PRINT_PARAMS_LOG) + } + if(!params.isEmpty) requestMap.put(TaskConstant.PARAMS, params) + } + entranceServer.execute(requestMap) + } + + override def getJob(jobId: String): Option[ClientJob] = entranceServer.getJob(jobId).map { case job: ClientJob => job } + + override def executeResult(code: String, user: String, creator: String): Array[String] = + executeResult(code, user, creator, null) + + override def executeResult(code: String, user: String, creator: String, + params: java.util.Map[String, Any]): Array[String] = + executeUntil(code, user, creator, params, job => + if(job.isSucceed) job.getResultSets + else if(job.getErrorResponse != null) { + val exception = new EntranceErrorException(22001, job.getErrorResponse.message) + if(job.getErrorResponse.t != null) exception.initCause(job.getErrorResponse.t) + throw exception + } else throw new EntranceErrorException(22002, "execute failed, unknown reason.")) + +} +object EntranceClientImpl { + + private val clientNameToEntranceClient = new JMap[String, EntranceClientImpl] + + def apply(clientName: String): EntranceClientImpl = { + if(!clientNameToEntranceClient.containsKey(clientName)) synchronized { + if(!clientNameToEntranceClient.containsKey(clientName)) { + val client = new EntranceClientImpl + client.setClientName(clientName) + clientNameToEntranceClient.put(clientName, client) + } + } + clientNameToEntranceClient.get(clientName) + } + + def getClientNames = clientNameToEntranceClient.keySet() +} \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala index ad46e5caad..68e381de44 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientConfiguration.scala @@ -18,9 +18,6 @@ package com.webank.wedatasphere.linkis.entranceclient.conf import com.webank.wedatasphere.linkis.common.conf.CommonVars -/** - * Created by johnnwang on 2019/1/22. - */ object ClientConfiguration { val CLIENT_ENGINE_MANAGER_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.client.enginemanager.application.name.default", "IOEngineManager") diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala new file mode 100644 index 0000000000..93a0342932 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/ClientForEntranceSpringConfiguration.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.conf + +import com.webank.wedatasphere.linkis.common.utils.Logging +//import com.webank.wedatasphere.linkis.entrance.annotation.EntranceServerBeanAnnotation.EntranceServerAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entrance.annotation._ +//import com.webank.wedatasphere.linkis.entrance.conf.EntranceSpringConfiguration +//import com.webank.wedatasphere.linkis.entrance.execute._ +//import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +//import com.webank.wedatasphere.linkis.entrance.log.LogManager +//import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +//import com.webank.wedatasphere.linkis.entrance.{EntranceParser, EntranceServer} +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEngineSelectorBeanAnnotation.ClientEngineSelectorAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientEntranceParserBeanAnnotation.ClientEntranceParserAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.ClientInterceptorsBeanAnnotation.ClientInterceptorsAutowiredAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.annotation.DefaultEntranceClientBeanAnnotation +//import com.webank.wedatasphere.linkis.entranceclient.{EntranceClient, EntranceClientImpl, _} +//import com.webank.wedatasphere.linkis.rpc.{RPCMessageEvent, Receiver, ReceiverChooser} +//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +//import org.springframework.boot.autoconfigure.{AutoConfigureAfter, AutoConfigureBefore} +//import org.springframework.context.annotation.{Conditional, Configuration} + +/*@Configuration +@AutoConfigureBefore(Array(classOf[EntranceSpringConfiguration])) +@AutoConfigureAfter(Array(classOf[ClientSpringConfiguration])) +@Conditional(Array(classOf[SingleEntranceCondition]))*/ +class ClientForEntranceSpringConfiguration extends Logging { + + warn(s"start a single-entrance application...") + + /*@DefaultEntranceClientBeanAnnotation + def generateEntranceClient(@EntranceServerAutowiredAnnotation entranceServer: EntranceServer): EntranceClient = { + val client = EntranceClientImpl(ClientConfiguration.CLIENT_DEFAULT_NAME) + warn(s"ready to initial EntranceClient ${client.getEntranceClientName}...") + client.init(entranceServer) + client + }*/ +/* + + @ReceiverChooserBeanAnnotation + def generateEntranceReceiverChooser(): ReceiverChooser = new ReceiverChooser{ + override def chooseReceiver(event: RPCMessageEvent): Option[Receiver] = None + } + + @PersistenceManagerBeanAnnotation + @ConditionalOnMissingBean(value = Array(classOf[context.ClientPersistenceManager])) + def generatePersistenceManager(): PersistenceManager = new context.ClientPersistenceManager + + @EntranceParserBeanAnnotation + def generateEntranceParser(@ClientEntranceParserAutowiredAnnotation clientEntranceParser: context.ClientEntranceParser): EntranceParser = clientEntranceParser + + @LogManagerBeanAnnotation + @ConditionalOnMissingBean(value = Array(classOf[context.ClientLogManager])) + def generateLogManager(): LogManager = new context.ClientLogManager + + + @EntranceInterceptorBeanAnnotation + def generateEntranceInterceptor(@ClientInterceptorsAutowiredAnnotation clientInterceptors: Array[EntranceInterceptor]): Array[EntranceInterceptor] = clientInterceptors +*/ + + +// @EngineSelectorBeanAnnotation +// def generateEngineSelector(@ClientEngineSelectorAutowiredAnnotation clientEngineSelector: EngineSelector): EngineSelector = clientEngineSelector + + +} \ No newline at end of file diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala similarity index 86% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala index 90d1077584..f3bac7e5f0 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/conf/MultiEntranceCondition.scala @@ -18,13 +18,9 @@ package com.webank.wedatasphere.linkis.entranceclient.conf import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entranceclient -import org.apache.commons.lang.StringUtils import org.springframework.context.annotation.{Condition, ConditionContext} import org.springframework.core.`type`.AnnotatedTypeMetadata -/** - * Created by johnnwang on 2019/1/22. - */ class MultiEntranceCondition extends Condition { override def matches(conditionContext: ConditionContext, annotatedTypeMetadata: AnnotatedTypeMetadata): Boolean = entranceclient.conf.MultiEntranceCondition.isMultiEntranceApplication @@ -34,5 +30,5 @@ class SingleEntranceCondition extends Condition { !entranceclient.conf.MultiEntranceCondition.isMultiEntranceApplication } object MultiEntranceCondition { - def isMultiEntranceApplication: Boolean = StringUtils.isNotBlank(EntranceConfiguration.ENGINE_MANAGER_SPRING_APPLICATION_NAME.getValue) + def isMultiEntranceApplication: Boolean = EntranceConfiguration.MULTI_ENTRANCE_CONDITION.getValue } \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala new file mode 100644 index 0000000000..e12fcf7e49 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientEntranceParser.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entranceclient.context + +import java.util + +import com.webank.wedatasphere.linkis.entrance.parser.CommonEntranceParser +import com.webank.wedatasphere.linkis.entranceclient.execute +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.scheduler.queue.Job + +class ClientEntranceParser extends CommonEntranceParser { + + override def parseToTask(job: Job): Task = job match { + case j: execute.ClientJob => j.getTask + } + + override def parseToJob(task: Task): Job = { + val job = new execute.ClientJob + task match { + case t: RequestPersistTask => + job.setTask(t) + job.setCreator(t.getRequestApplicationName) + job.setUser(t.getUmUser) + if (t.getParams != null) job.setParams(t.getParams.asInstanceOf[util.Map[String, Any]]) + } + job + } +} diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala index fd15742125..1b1b4d5bc7 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientLogManager.scala @@ -24,9 +24,6 @@ import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import org.apache.commons.io.input.NullInputStream import org.apache.commons.io.output.NullOutputStream -/** - * Created by johnnwang on 2018/10/30. - */ class ClientLogManager extends CacheLogManager { override def getLogReader(execId: String): LogReader = { new CacheLogReader("", ServerConfiguration.BDP_SERVER_ENCODING.getValue, diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala index 1f5e31d503..d69fe21aea 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceEngine.scala @@ -21,9 +21,6 @@ import java.lang import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceEngine import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * Created by johnnwang on 2018/10/30. - */ class ClientPersistenceEngine extends PersistenceEngine { override def persist(task: Task): Unit = {} diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala similarity index 97% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala index c9254c4fb3..c8320f9a76 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/context/ClientPersistenceManager.scala @@ -23,9 +23,6 @@ import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse import com.webank.wedatasphere.linkis.scheduler.queue.Job -/** - * Created by johnnwang on 2018/10/30. - */ class ClientPersistenceManager extends PersistenceManager { private val persistenceEngine = new ClientPersistenceEngine override def getEntranceContext: EntranceContext = null diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala similarity index 100% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/exception/ClientErrorException.scala diff --git a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala similarity index 80% rename from ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala rename to linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala index 58332dad65..23834cf411 100644 --- a/ujes/entranceclient/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala +++ b/linkis-computation-governance/linkis-entrance-client/src/main/scala/com/webank/wedatasphere/linkis/entranceclient/execute/ClientJob.scala @@ -17,27 +17,25 @@ package com.webank.wedatasphere.linkis.entranceclient.execute import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob -import com.webank.wedatasphere.linkis.entranceclient.context.ClientTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.scheduler.executer.{ExecuteRequest, JobExecuteRequest} import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState.SchedulerEventState import com.webank.wedatasphere.linkis.scheduler.queue.{JobInfo, SchedulerEventState} import scala.collection.mutable.ArrayBuffer -/** - * Created by johnnwang on 2018/10/30. - */ class ClientJob extends EntranceJob { private val resultSets = ArrayBuffer[String]() def addResultSet(resultSet: String): Unit = resultSets += resultSet + def getResultSets: Array[String] = resultSets.toArray def waitForComplete(): Unit = { - if(SchedulerEventState.isCompleted(this.getState)) return + if (SchedulerEventState.isCompleted(this.getState)) return resultSets synchronized { - while(!SchedulerEventState.isCompleted(this.getState)) resultSets.wait() + while (!SchedulerEventState.isCompleted(this.getState)) resultSets.wait() } } @@ -51,11 +49,11 @@ class ClientJob extends EntranceJob { override def init(): Unit = {} override protected def jobToExecuteRequest: ExecuteRequest = new ExecuteRequest with JobExecuteRequest { - override val code: String = getTask.asInstanceOf[ClientTask].getCode + override val code: String = getTask.asInstanceOf[RequestPersistTask].getCode override val jobId: String = getId } - override def getName: String = getTask.asInstanceOf[ClientTask].getCreator + "_" + getTask.asInstanceOf[ClientTask].getUser + "_" + getId + override def getName: String = getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName + "_" + getTask.asInstanceOf[RequestPersistTask].getUmUser + "_" + getId override def getJobInfo: JobInfo = null diff --git a/linkis-computation-governance/linkis-entrance/pom.xml b/linkis-computation-governance/linkis-entrance/pom.xml new file mode 100644 index 0000000000..c9e6678a1e --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/pom.xml @@ -0,0 +1,142 @@ + + + + + 4.0.0 + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + linkis-entrance + + + + com.webank.wedatasphere.linkis + linkis-scheduler + ${linkis.version} + + + com.webank.wedatasphere.linkis + linkis-common + + + + + + com.webank.wedatasphere.linkis + linkis-rpc + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-storage + ${linkis.version} + provided + + + + com.webank.wedatasphere.linkis + linkis-cs-engine-support + ${linkis.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + provided + + + + junit + junit + 4.12 + test + + + + com.webank.wedatasphere.linkis + linkis-computation-governance-common + ${linkis.version} + + + + + com.webank.wedatasphere.linkis + linkis-orchestrator-ecm-plugin + ${linkis.version} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + false + + + make-assembly + package + + single + + + + src/main/assembly/distribution.xml + + + + + + false + out + false + false + + src/main/assembly/distribution.xml + + + + + + + ${basedir}/src/main/resources + + + ${project.artifactId}-${project.version} + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml b/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml new file mode 100644 index 0000000000..6781dc2891 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/assembly/distribution.xml @@ -0,0 +1,319 @@ + + + + linkis-ujes-spark-entrance + + dir + zip + + false + linkis-ujes-linkis-entrance + + + + + + lib + true + true + false + false + true + + + antlr:antlr:jar + aopalliance:aopalliance:jar + asm:asm:jar + cglib:cglib:jar + com.amazonaws:aws-java-sdk-autoscaling:jar + com.amazonaws:aws-java-sdk-core:jar + com.amazonaws:aws-java-sdk-ec2:jar + com.amazonaws:aws-java-sdk-route53:jar + com.amazonaws:aws-java-sdk-sts:jar + com.amazonaws:jmespath-java:jar + com.fasterxml.jackson.core:jackson-annotations:jar + com.fasterxml.jackson.core:jackson-core:jar + com.fasterxml.jackson.core:jackson-databind:jar + com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:jar + com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar + com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar + com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:jar + com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar + com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar + com.fasterxml.jackson.module:jackson-module-parameter-names:jar + com.fasterxml.jackson.module:jackson-module-paranamer:jar + com.fasterxml.jackson.module:jackson-module-scala_2.11:jar + com.github.andrewoma.dexx:dexx-collections:jar + com.github.vlsi.compactmap:compactmap:jar + com.google.code.findbugs:annotations:jar + com.google.code.findbugs:jsr305:jar + com.google.code.gson:gson:jar + com.google.guava:guava:jar + com.google.inject:guice:jar + com.google.protobuf:protobuf-java:jar + com.netflix.archaius:archaius-core:jar + com.netflix.eureka:eureka-client:jar + com.netflix.eureka:eureka-core:jar + com.netflix.hystrix:hystrix-core:jar + com.netflix.netflix-commons:netflix-commons-util:jar + com.netflix.netflix-commons:netflix-eventbus:jar + com.netflix.netflix-commons:netflix-infix:jar + com.netflix.netflix-commons:netflix-statistics:jar + com.netflix.ribbon:ribbon:jar + com.netflix.ribbon:ribbon-core:jar + com.netflix.ribbon:ribbon-eureka:jar + com.netflix.ribbon:ribbon-httpclient:jar + com.netflix.ribbon:ribbon-loadbalancer:jar + com.netflix.ribbon:ribbon-transport:jar + com.netflix.servo:servo-core:jar + com.ning:async-http-client:jar + com.sun.jersey.contribs:jersey-apache-client4:jar + com.sun.jersey:jersey-client:jar + com.sun.jersey:jersey-core:jar + com.sun.jersey:jersey-json:jar + com.sun.jersey:jersey-server:jar + com.sun.jersey:jersey-servlet:jar + com.sun.xml.bind:jaxb-impl:jar + com.thoughtworks.paranamer:paranamer:jar + com.thoughtworks.xstream:xstream:jar + com.webank.wedatasphere.linkis:linkis-common:jar + com.webank.wedatasphere.linkis:linkis-module:jar + commons-beanutils:commons-beanutils:jar + commons-beanutils:commons-beanutils-core:jar + commons-cli:commons-cli:jar + commons-codec:commons-codec:jar + commons-collections:commons-collections:jar + commons-configuration:commons-configuration:jar + commons-daemon:commons-daemon:jar + commons-dbcp:commons-dbcp:jar + commons-digester:commons-digester:jar + commons-httpclient:commons-httpclient:jar + commons-io:commons-io:jar + commons-jxpath:commons-jxpath:jar + commons-lang:commons-lang:jar + commons-logging:commons-logging:jar + commons-net:commons-net:jar + commons-pool:commons-pool:jar + io.micrometer:micrometer-core:jar + io.netty:netty:jar + io.netty:netty-all:jar + io.netty:netty-buffer:jar + io.netty:netty-codec:jar + io.netty:netty-codec-http:jar + io.netty:netty-common:jar + io.netty:netty-handler:jar + io.netty:netty-transport:jar + io.netty:netty-transport-native-epoll:jar + io.reactivex:rxjava:jar + io.reactivex:rxnetty:jar + io.reactivex:rxnetty-contexts:jar + io.reactivex:rxnetty-servo:jar + javax.activation:activation:jar + javax.annotation:javax.annotation-api:jar + javax.inject:javax.inject:jar + javax.servlet:javax.servlet-api:jar + javax.servlet.jsp:jsp-api:jar + javax.validation:validation-api:jar + javax.websocket:javax.websocket-api:jar + javax.ws.rs:javax.ws.rs-api:jar + javax.xml.bind:jaxb-api:jar + javax.xml.stream:stax-api:jar + joda-time:joda-time:jar + log4j:log4j:jar + mysql:mysql-connector-java:jar + net.databinder.dispatch:dispatch-core_2.11:jar + net.databinder.dispatch:dispatch-json4s-jackson_2.11:jar + org.antlr:antlr-runtime:jar + org.antlr:stringtemplate:jar + org.apache.commons:commons-compress:jar + org.apache.commons:commons-math:jar + org.apache.commons:commons-math3:jar + org.apache.curator:curator-client:jar + org.apache.curator:curator-framework:jar + org.apache.curator:curator-recipes:jar + org.apache.directory.api:api-asn1-api:jar + org.apache.directory.api:api-util:jar + org.apache.directory.server:apacheds-i18n:jar + org.apache.directory.server:apacheds-kerberos-codec:jar + org.apache.hadoop:hadoop-annotations:jar + org.apache.hadoop:hadoop-auth:jar + org.apache.hadoop:hadoop-common:jar + org.apache.hadoop:hadoop-hdfs:jar + org.apache.htrace:htrace-core:jar + org.apache.httpcomponents:httpclient:jar + org.apache.httpcomponents:httpcore:jar + org.apache.logging.log4j:log4j-api:jar + org.apache.logging.log4j:log4j-core:jar + org.apache.logging.log4j:log4j-jul:jar + org.apache.logging.log4j:log4j-slf4j-impl:jar + org.apache.zookeeper:zookeeper:jar + org.aspectj:aspectjweaver:jar + org.bouncycastle:bcpkix-jdk15on:jar + org.bouncycastle:bcprov-jdk15on:jar + org.codehaus.jackson:jackson-jaxrs:jar + org.codehaus.jackson:jackson-xc:jar + org.codehaus.jettison:jettison:jar + org.codehaus.woodstox:stax2-api:jar + org.codehaus.woodstox:woodstox-core-asl:jar + org.eclipse.jetty:jetty-annotations:jar + org.eclipse.jetty:jetty-client:jar + org.eclipse.jetty:jetty-continuation:jar + org.eclipse.jetty:jetty-http:jar + org.eclipse.jetty:jetty-io:jar + org.eclipse.jetty:jetty-jndi:jar + org.eclipse.jetty:jetty-plus:jar + org.eclipse.jetty:jetty-security:jar + org.eclipse.jetty:jetty-server:jar + org.eclipse.jetty:jetty-servlet:jar + org.eclipse.jetty:jetty-servlets:jar + org.eclipse.jetty:jetty-util:jar + org.eclipse.jetty:jetty-webapp:jar + org.eclipse.jetty:jetty-xml:jar + org.eclipse.jetty.websocket:javax-websocket-client-impl:jar + org.eclipse.jetty.websocket:javax-websocket-server-impl:jar + org.eclipse.jetty.websocket:websocket-api:jar + org.eclipse.jetty.websocket:websocket-client:jar + org.eclipse.jetty.websocket:websocket-common:jar + org.eclipse.jetty.websocket:websocket-server:jar + org.eclipse.jetty.websocket:websocket-servlet:jar + org.fusesource.leveldbjni:leveldbjni-all:jar + org.glassfish.hk2:class-model:jar + org.glassfish.hk2:config-types:jar + org.glassfish.hk2.external:aopalliance-repackaged:jar + org.glassfish.hk2.external:asm-all-repackaged:jar + org.glassfish.hk2.external:bean-validator:jar + org.glassfish.hk2.external:javax.inject:jar + org.glassfish.hk2:hk2:jar + org.glassfish.hk2:hk2-api:jar + org.glassfish.hk2:hk2-config:jar + org.glassfish.hk2:hk2-core:jar + org.glassfish.hk2:hk2-locator:jar + org.glassfish.hk2:hk2-runlevel:jar + org.glassfish.hk2:hk2-utils:jar + org.glassfish.hk2:osgi-resource-locator:jar + org.glassfish.hk2:spring-bridge:jar + org.glassfish.jersey.bundles:jaxrs-ri:jar + org.glassfish.jersey.bundles.repackaged:jersey-guava:jar + org.glassfish.jersey.containers:jersey-container-servlet:jar + org.glassfish.jersey.containers:jersey-container-servlet-core:jar + org.glassfish.jersey.core:jersey-client:jar + org.glassfish.jersey.core:jersey-common:jar + org.glassfish.jersey.core:jersey-server:jar + org.glassfish.jersey.ext:jersey-entity-filtering:jar + org.glassfish.jersey.ext:jersey-spring3:jar + org.glassfish.jersey.media:jersey-media-jaxb:jar + org.glassfish.jersey.media:jersey-media-json-jackson:jar + org.glassfish.jersey.media:jersey-media-multipart:jar + org.hdrhistogram:HdrHistogram:jar + org.javassist:javassist:jar + org.json4s:json4s-ast_2.11:jar + org.json4s:json4s-core_2.11:jar + org.json4s:json4s-jackson_2.11:jar + org.jsoup:jsoup:jar + org.jvnet.mimepull:mimepull:jar + org.jvnet:tiger-types:jar + org.latencyutils:LatencyUtils:jar + org.mortbay.jasper:apache-el:jar + org.mortbay.jetty:jetty:jar + org.mortbay.jetty:jetty-util:jar + org.ow2.asm:asm-analysis:jar + org.ow2.asm:asm-commons:jar + org.ow2.asm:asm-tree:jar + org.reflections:reflections:jar + org.scala-lang.modules:scala-parser-combinators_2.11:jar + org.scala-lang.modules:scala-xml_2.11:jar + org.scala-lang:scala-compiler:jar + org.scala-lang:scala-library:jar + org.scala-lang:scala-reflect:jar + org.scala-lang:scalap:jar + org.slf4j:jul-to-slf4j:jar + org.slf4j:slf4j-api:jar + org.springframework.boot:spring-boot:jar + org.springframework.boot:spring-boot-actuator:jar + org.springframework.boot:spring-boot-actuator-autoconfigure:jar + org.springframework.boot:spring-boot-autoconfigure:jar + org.springframework.boot:spring-boot-starter:jar + org.springframework.boot:spring-boot-starter-actuator:jar + org.springframework.boot:spring-boot-starter-aop:jar + org.springframework.boot:spring-boot-starter-jetty:jar + org.springframework.boot:spring-boot-starter-json:jar + org.springframework.boot:spring-boot-starter-log4j2:jar + org.springframework.boot:spring-boot-starter-web:jar + org.springframework.cloud:spring-cloud-commons:jar + org.springframework.cloud:spring-cloud-config-client:jar + org.springframework.cloud:spring-cloud-context:jar + org.springframework.cloud:spring-cloud-netflix-archaius:jar + org.springframework.cloud:spring-cloud-netflix-core:jar + org.springframework.cloud:spring-cloud-netflix-eureka-client:jar + org.springframework.cloud:spring-cloud-netflix-ribbon:jar + org.springframework.cloud:spring-cloud-starter:jar + org.springframework.cloud:spring-cloud-starter-config:jar + org.springframework.cloud:spring-cloud-starter-eureka:jar + org.springframework.cloud:spring-cloud-starter-netflix-archaius:jar + org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:jar + org.springframework.cloud:spring-cloud-starter-netflix-ribbon:jar + org.springframework.security:spring-security-crypto:jar + org.springframework.security:spring-security-rsa:jar + org.springframework:spring-aop:jar + org.springframework:spring-beans:jar + org.springframework:spring-context:jar + org.springframework:spring-core:jar + org.springframework:spring-expression:jar + org.springframework:spring-jcl:jar + org.springframework:spring-web:jar + org.springframework:spring-webmvc:jar + org.tukaani:xz:jar + org.yaml:snakeyaml:jar + software.amazon.ion:ion-java:jar + xerces:xercesImpl:jar + xmlenc:xmlenc:jar + xmlpull:xmlpull:jar + xpp3:xpp3_min:jar + + + + + + + ${basedir}/src/main/resources + + * + + 0777 + conf + unix + + + + + + diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java new file mode 100644 index 0000000000..ac80d687bb --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/LinkisEntranceApplication.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance; + +import com.webank.wedatasphere.linkis.DataWorkCloudApplication; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + + +public class LinkisEntranceApplication { + + private static final Log logger = LogFactory.getLog(DataWorkCloudApplication.class); + + public static void main(String[] args) throws ReflectiveOperationException { + logger.info("Start to running LinkisManagerApplication"); + DataWorkCloudApplication.main(args); + } +} diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/BackGroundServiceBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ConsumerManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineBuilderBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineRequesterBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EngineSelectorBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceContextBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java similarity index 97% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java index 902733be5f..38659f6e1f 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceExecutorManagerBeanAnnotation.java @@ -35,7 +35,7 @@ @Bean(value = EntranceExecutorManagerBeanAnnotation.BEAN_NAME) @Component(value = EntranceExecutorManagerBeanAnnotation.BEAN_NAME) public @interface EntranceExecutorManagerBeanAnnotation { - String BEAN_NAME = "entranceExecutorManager"; + String BEAN_NAME = "executorManager"; @AliasFor(annotation = Component.class) String value() default BEAN_NAME; diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceInterceptorBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceListenerBusBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceParserBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/EntranceServerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ErrorCodeManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/GroupFactoryBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/LogManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/NewEngineBroadcastListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceEngineBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/PersistenceManagerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ReceiverChooserBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResponseEngineStatusChangedBroadcastListenerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/ResultSetEngineBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/annotation/SchedulerContextBeanAnnotation.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java similarity index 84% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java index 360e8ffa1f..d9e27e299c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/conf/EntranceSpringConfiguration.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,15 +13,15 @@ package com.webank.wedatasphere.linkis.entrance.conf; -import com.webank.wedatasphere.linkis.entrance.EntranceContext; import com.webank.wedatasphere.linkis.entrance.EntranceParser; +import com.webank.wedatasphere.linkis.entrance.EntranceServer; import com.webank.wedatasphere.linkis.entrance.annotation.*; import com.webank.wedatasphere.linkis.entrance.background.BackGroundService; import com.webank.wedatasphere.linkis.entrance.event.EntranceEvent; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListener; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListenerBus; -import com.webank.wedatasphere.linkis.entrance.execute.*; -import com.webank.wedatasphere.linkis.entrance.execute.impl.*; +import com.webank.wedatasphere.linkis.entrance.execute.EntranceExecutionService; +import com.webank.wedatasphere.linkis.entrance.execute.impl.EntranceExecutorManagerImpl; import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; import com.webank.wedatasphere.linkis.entrance.interceptor.impl.*; import com.webank.wedatasphere.linkis.entrance.log.*; @@ -32,26 +29,29 @@ import com.webank.wedatasphere.linkis.entrance.persistence.*; import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceGroupFactory; import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceSchedulerContext; -import com.webank.wedatasphere.linkis.rpc.ReceiverChooser; +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManagerBuilder; +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManagerBuilder$; +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Policy; import com.webank.wedatasphere.linkis.scheduler.Scheduler; import com.webank.wedatasphere.linkis.scheduler.SchedulerContext; +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorManager; import com.webank.wedatasphere.linkis.scheduler.queue.ConsumerManager; import com.webank.wedatasphere.linkis.scheduler.queue.GroupFactory; import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelConsumerManager; import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelScheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Configuration; import static com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration.ENTRANCE_SCHEDULER_MAX_PARALLELISM_USERS; /** - * created by enjoyyin on 2018/10/16 * Description:This configuration class is used to generate some singleton classes in the entity module.(该配置类用于生成entrance模块中的一些单例类) */ @Configuration +@AutoConfigureBefore({EntranceServer.class, EntranceExecutionService.class}) public class EntranceSpringConfiguration { private Logger logger = LoggerFactory.getLogger(getClass()); @@ -59,11 +59,7 @@ public class EntranceSpringConfiguration { logger.info("load the ujes-entrance spring configuration."); } - @EntranceParserBeanAnnotation - @ConditionalOnMissingBean(name = {EntranceParserBeanAnnotation.BEAN_NAME}) - public EntranceParser generateEntranceParser(){ - return new CommonEntranceParser(); - } + @PersistenceEngineBeanAnnotation @ConditionalOnMissingBean(name = {PersistenceEngineBeanAnnotation.BEAN_NAME}) @@ -81,12 +77,18 @@ public ResultSetEngine generateResultSetEngine(){ @ConditionalOnMissingBean(name = {PersistenceManagerBeanAnnotation.BEAN_NAME}) public PersistenceManager generatePersistenceManager(@PersistenceEngineBeanAnnotation.PersistenceEngineAutowiredAnnotation PersistenceEngine persistenceEngine, @ResultSetEngineBeanAnnotation.ResultSetEngineAutowiredAnnotation ResultSetEngine resultSetEngine){ + logger.info("init PersistenceManager."); QueryPersistenceManager persistenceManager = new QueryPersistenceManager(); persistenceManager.setPersistenceEngine(persistenceEngine); persistenceManager.setResultSetEngine(resultSetEngine); return persistenceManager; } + @EntranceParserBeanAnnotation + @ConditionalOnMissingBean(name = {EntranceParserBeanAnnotation.BEAN_NAME}) + public EntranceParser generateEntranceParser(){ + return new CommonEntranceParser(); + } @EntranceListenerBusBeanAnnotation @ConditionalOnMissingBean(name = {EntranceListenerBusBeanAnnotation.BEAN_NAME}) @@ -104,7 +106,7 @@ public EntranceEventListenerBus generateEn @EntranceInterceptorBeanAnnotation @ConditionalOnMissingBean(name = {EntranceInterceptorBeanAnnotation.BEAN_NAME}) public EntranceInterceptor[] generateEntranceInterceptors() { - return new EntranceInterceptor[]{new CSEntranceInterceptor(), new PythonCodeCheckInterceptor(), new DBInfoCompleteInterceptor(), new SparkCodeCheckInterceptor(), + return new EntranceInterceptor[]{new CSEntranceInterceptor(), new PythonCodeCheckInterceptor(), new DBInfoCompleteInterceptor(), new SparkCodeCheckInterceptor(), new SQLCodeCheckInterceptor(), new VarSubstitutionInterceptor(), new LogPathCreateInterceptor(), new StorePathEntranceInterceptor(), new ScalaCodeInterceptor(), new SQLLimitEntranceInterceptor(), new CommentInterceptor(), }; @@ -152,18 +154,18 @@ public ConsumerManager generateConsumerManager(){ @SchedulerContextBeanAnnotation @ConditionalOnMissingBean(name = {SchedulerContextBeanAnnotation.BEAN_NAME}) public SchedulerContext generateSchedulerContext(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory, - @EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation EntranceExecutorManager executorManager, + @EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation ExecutorManager executorManager, @ConsumerManagerBeanAnnotation.ConsumerManagerAutowiredAnnotation ConsumerManager consumerManager) { return new EntranceSchedulerContext(groupFactory, consumerManager, executorManager); } - @EngineRequesterBeanAnnotation + /* @EngineRequesterBeanAnnotation @ConditionalOnMissingBean(name = {EngineRequesterBeanAnnotation.BEAN_NAME}) public EngineRequester generateEngineRequester(){ return new EngineRequesterImpl(); } - - @EngineSelectorBeanAnnotation +*/ + /* @EngineSelectorBeanAnnotation @ConditionalOnMissingBean(name = {EngineSelectorBeanAnnotation.BEAN_NAME}) public EngineSelector generateEngineSelector(@EntranceListenerBusBeanAnnotation.EntranceListenerBusAutowiredAnnotation EntranceEventListenerBus entranceEventListenerBus) { @@ -171,8 +173,8 @@ public EngineSelector generateEngineSelector(@EntranceListenerBusBeanAnnotation. singleEngineSelector.setEntranceEventListenerBus(entranceEventListenerBus); return singleEngineSelector; } - - @EngineBuilderBeanAnnotation +*/ + /*@EngineBuilderBeanAnnotation @ConditionalOnMissingBean(name = {EngineBuilderBeanAnnotation.BEAN_NAME}) public EngineBuilder generateEngineBuilder(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory) { return new AbstractEngineBuilder(groupFactory) { @@ -181,49 +183,39 @@ public EntranceEngine createEngine(long id) { return new SingleEntranceEngine(id); } }; - } + }*/ - @EngineManagerBeanAnnotation + /* @EngineManagerBeanAnnotation @ConditionalOnMissingBean(name = {EngineManagerBeanAnnotation.BEAN_NAME}) public EngineManager generateEngineManager() { return new EngineManagerImpl(); - } + }*/ @EntranceExecutorManagerBeanAnnotation @ConditionalOnMissingBean(name = {EntranceExecutorManagerBeanAnnotation.BEAN_NAME}) - public EntranceExecutorManager generateExecutorManager(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory, - @EngineBuilderBeanAnnotation.EngineBuilderAutowiredAnnotation EngineBuilder engineBuilder, - @EngineRequesterBeanAnnotation.EngineRequesterAutowiredAnnotation EngineRequester engineRequester, - @EngineSelectorBeanAnnotation.EngineSelectorAutowiredAnnotation EngineSelector engineSelector, - @EngineManagerBeanAnnotation.EngineManagerAutowiredAnnotation EngineManager engineManager, - @Autowired EntranceExecutorRuler[] entranceExecutorRulers){ - return new EntranceExecutorManagerImpl(groupFactory, engineBuilder, - engineRequester, engineSelector, engineManager, entranceExecutorRulers); + public ExecutorManager generateExecutorManager(@GroupFactoryBeanAnnotation.GroupFactoryAutowiredAnnotation GroupFactory groupFactory) { + EngineConnManagerBuilder engineConnManagerBuilder = EngineConnManagerBuilder$.MODULE$.builder(); + engineConnManagerBuilder.setPolicy(Policy.Process); + return new EntranceExecutorManagerImpl(groupFactory, engineConnManagerBuilder.build()); } @SchedulerBeanAnnotation @ConditionalOnMissingBean(name = {SchedulerBeanAnnotation.BEAN_NAME}) - public Scheduler generateScheduler(@SchedulerContextBeanAnnotation.SchedulerContextAutowiredAnnotation SchedulerContext schedulerContext){ + public Scheduler generateScheduler(@SchedulerContextBeanAnnotation.SchedulerContextAutowiredAnnotation SchedulerContext schedulerContext) { Scheduler scheduler = new ParallelScheduler(schedulerContext); scheduler.init(); scheduler.start(); return scheduler; } - @ReceiverChooserBeanAnnotation - @ConditionalOnMissingBean(name = {ReceiverChooserBeanAnnotation.BEAN_NAME}) - public ReceiverChooser generateEntranceReceiverChooser(@EntranceContextBeanAnnotation.EntranceContextAutowiredAnnotation - EntranceContext entranceContext) { - return new EntranceReceiverChooser(entranceContext); - } @BackGroundServiceBeanAnnotation @ConditionalOnMissingBean(name = {BackGroundServiceBeanAnnotation.BEAN_NAME}) - public BackGroundService[] generateBackGroundService(){ + public BackGroundService[] generateBackGroundService() { return new BackGroundService[]{}; } - @NewEngineBroadcastListenerBeanAnnotation + /* @NewEngineBroadcastListenerBeanAnnotation @ConditionalOnMissingBean(name = {NewEngineBroadcastListenerBeanAnnotation.BEAN_NAME}) public NewEngineBroadcastListener generateNewEngineBroadcastListener(@EntranceExecutorManagerBeanAnnotation.EntranceExecutorManagerAutowiredAnnotation EntranceExecutorManager entranceExecutorManager) { @@ -239,5 +231,5 @@ public ResponseEngineStatusChangedBroadcastListener generateResponseEngineStatus ResponseEngineStatusChangedBroadcastListener broadcastListener = new ResponseEngineStatusChangedBroadcastListener(); broadcastListener.setEntranceExecutorManager(entranceExecutorManager); return broadcastListener; - } + }*/ } diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java index e0ad6babb9..7bb61e9f0c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/context/DefaultEntranceContext.java @@ -29,16 +29,18 @@ import com.webank.wedatasphere.linkis.entrance.event.EntranceEvent; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListener; import com.webank.wedatasphere.linkis.entrance.event.EntranceEventListenerBus; -import com.webank.wedatasphere.linkis.entrance.execute.EntranceExecutorManager; import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor; import com.webank.wedatasphere.linkis.entrance.log.LogManager; import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager; import com.webank.wedatasphere.linkis.scheduler.Scheduler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; @EntranceContextBeanAnnotation public class DefaultEntranceContext extends EntranceContext { + private static Logger logger = LoggerFactory.getLogger(DefaultEntranceContext.class); @EntranceParserBeanAnnotation.EntranceParserAutowiredAnnotation private EntranceParser entranceParser; @@ -79,11 +81,12 @@ public DefaultEntranceContext() { @PostConstruct public void init() { entranceParser.setEntranceContext(this); + logger.info("Finished init entranceParser from postConstruct end!"); persistenceManager.setEntranceContext(this); logManager.setEntranceContext(this); - if(scheduler.getSchedulerContext().getOrCreateExecutorManager() instanceof EntranceExecutorManager) { + /* if(scheduler.getSchedulerContext().getOrCreateExecutorManager() instanceof EntranceExecutorManager) { listenerBus.addListener(((EntranceExecutorManager) scheduler.getSchedulerContext().getOrCreateExecutorManager()).getOrCreateEngineManager()); - } + }*/ } @Override diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java similarity index 86% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java index dbf48ab111..e6b144283d 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorCode.java @@ -27,7 +27,10 @@ public enum EntranceErrorCode { * */ CACHE_NOT_READY(200, "shared cache not ready"), - ENTRANCE_CAST_FAIL(20002, "class cast failed") + ENTRANCE_CAST_FAIL(20002, "class cast failed"), + PARAM_CANNOT_EMPTY(20008, "params cannot be empty "), + LABEL_PARAMS_INVALID(20009, "Label params invalid. ") + ; private int errCode; private String desc; diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java similarity index 84% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java index 82da5b66b5..8497c9edc1 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceIllegalParamException.java @@ -18,15 +18,14 @@ import com.webank.wedatasphere.linkis.common.exception.ErrorException; -/** - * created by enjoyyin on 2018/10/8 - * Description: - */ + public class EntranceIllegalParamException extends ErrorException { public EntranceIllegalParamException(int errCode, String message){ super(errCode, message); } - + public EntranceIllegalParamException(EntranceErrorCode entranceErrorCode) { + super(entranceErrorCode.getErrCode(), entranceErrorCode.getDesc()); + } } diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/EntranceRPCException.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/exception/QueryFailedException.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java index 1f5585b500..1a7c36b1c3 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/job/EntranceExecutionJob.java @@ -21,8 +21,9 @@ import com.webank.wedatasphere.linkis.entrance.execute.*; import com.webank.wedatasphere.linkis.entrance.log.*; import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils; import com.webank.wedatasphere.linkis.scheduler.executer.ExecuteRequest; @@ -37,12 +38,10 @@ import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.List; import java.util.Map; -/** - * created by enjoyyin on 2018/10/17 - * Description: - */ + public class EntranceExecutionJob extends EntranceJob implements LogHandler { private LogReader logReader; @@ -51,14 +50,15 @@ public class EntranceExecutionJob extends EntranceJob implements LogHandler { private WebSocketLogWriter webSocketLogWriter; private static final Logger logger = LoggerFactory.getLogger(EntranceExecutionJob.class); - public class EntranceExecuteRequest implements ExecuteRequest, LockExecuteRequest, JobExecuteRequest, RuntimePropertiesExecuteRequest { + public class EntranceExecuteRequest implements ExecuteRequest, LabelExecuteRequest, JobExecuteRequest, RuntimePropertiesExecuteRequest { private String executionCode; - public void setExecutionCode(){ + + public void setExecutionCode() { Task task = getTask(); - if (task instanceof RequestPersistTask){ - this.executionCode = ((RequestPersistTask) task).getExecutionCode(); + if (task instanceof RequestPersistTask) { + this.executionCode = ((RequestPersistTask) task).getExecutionCode(); } } @@ -67,24 +67,29 @@ public String code() { return this.executionCode; } - @Override - public String lock() { - return getLock(); - } - @Override public String jobId() { return getId(); } + @Override public Map properties() { Map properties = TaskUtils.getRuntimeMap(getParams()); - if(getTask() instanceof RequestPersistTask) { + if (getTask() instanceof RequestPersistTask) { properties.put(TaskConstant.RUNTYPE, ((RequestPersistTask) getTask()).getRunType()); } return properties; } + + @Override + public List> labels() { + Task task = getTask(); + if (task instanceof RequestPersistTask) { + return ((RequestPersistTask) task).getLabels(); + } + return null; + } } public class StorePathEntranceExecuteRequest extends EntranceExecuteRequest implements StorePathExecuteRequest { diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java similarity index 79% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java index 78a2777917..c911e481c3 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/AbstractEntranceParser.java @@ -21,19 +21,19 @@ import com.webank.wedatasphere.linkis.entrance.exception.EntranceIllegalParamException; import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.utils.GovernanceConstant; import com.webank.wedatasphere.linkis.protocol.task.Task; +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils; import com.webank.wedatasphere.linkis.scheduler.queue.Job; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; +import java.util.Map; + -/** - * created by enjoyyin on 2018/10/11 - * Description: - */ public abstract class AbstractEntranceParser extends EntranceParser { private EntranceContext entranceContext; @@ -61,26 +61,21 @@ public Task parseToTask(Job job) throws EntranceIllegalParamException{ if (job == null){ throw new EntranceIllegalParamException(20002, "job can't be null"); } - Task task = ((EntranceJob)job).getTask(); + Task task = ((EntranceJob) job).getTask(); if(StringUtils.isEmpty(task.getExecId())) { task.setExecId(job.getId()); } - if (task instanceof RequestPersistTask){ + if (task instanceof RequestPersistTask) { ((RequestPersistTask) task).setProgress(job.getProgress()); ((RequestPersistTask) task).setStatus(job.getState().toString()); ((RequestPersistTask) task).setUpdatedTime(new Date(System.currentTimeMillis())); ((RequestPersistTask) task).setProgress(job.getProgress()); - if(job.isCompleted() && !job.isSucceed() && job.getErrorResponse() != null + if (job.isCompleted() && !job.isSucceed() && job.getErrorResponse() != null && StringUtils.isBlank(((RequestPersistTask) task).getErrDesc()) - && StringUtils.isNotEmpty(job.getErrorResponse().message())) { + && StringUtils.isNotEmpty(job.getErrorResponse().message())) { ((RequestPersistTask) task).setErrDesc(job.getErrorResponse().message()); } - //if job is successful, errCode and errDesc needs to be null - if (job.isSucceed()){ - ((RequestPersistTask) task).setErrCode(null); - ((RequestPersistTask) task).setErrDesc(null); - } - }else{ + } else { logger.warn("not supported task type"); } return task; @@ -92,25 +87,27 @@ protected EntranceJob createEntranceJob() { /** * Parse a task into an executable job(将一个task解析成一个可执行的job) + * * @param task * @return */ @Override public Job parseToJob(Task task) throws EntranceIllegalParamException { - if (task == null){ + if (task == null) { throw new EntranceIllegalParamException(20001, "task can't be null"); } EntranceJob job = null; - if (task instanceof RequestPersistTask){ + if (task instanceof RequestPersistTask) { job = createEntranceJob(); job.setTask(task); job.setUser(((RequestPersistTask) task).getUmUser()); job.setCreator(((RequestPersistTask) task).getRequestApplicationName()); + job.setParams(((RequestPersistTask) task).getParams()); - //job.setLogListener(entranceContext.getOrCreateLogManager()); - //job.setProgressListener(entranceContext.getOrCreatePersistenceManager()); - //job.setJobListener(entranceContext.getOrCreatePersistenceManager()); + //TODO 放置source到RequestTask的properties中,后续会进行优化 + Map properties = TaskUtils.getRuntimeMap(job.getParams()); + properties.put(GovernanceConstant.TASK_SOURCE_MAP_KEY(), ((RequestPersistTask) task).getSource()); job.setEntranceListenerBus(entranceContext.getOrCreateEventListenerBus()); job.setEntranceContext(entranceContext); job.setListenerEventBus(null); diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java similarity index 95% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java index bc3aff72ab..b1816e298f 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/parser/ParserUtils.java @@ -17,7 +17,7 @@ package com.webank.wedatasphere.linkis.entrance.parser; import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration$; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import org.apache.commons.lang.StringUtils; @@ -25,10 +25,7 @@ import java.util.Date; import java.util.HashMap; import java.util.Map; -/** - * created by enjoyyin on 2018/10/17 - * Description: - */ + public final class ParserUtils { diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java similarity index 100% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java similarity index 95% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java index 67daab244a..80ff979281 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceEngine.java @@ -23,13 +23,12 @@ package com.webank.wedatasphere.linkis.entrance.persistence; import com.google.gson.Gson; -import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration; import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration$; import com.webank.wedatasphere.linkis.entrance.exception.EntranceIllegalParamException; import com.webank.wedatasphere.linkis.entrance.exception.EntranceRPCException; import com.webank.wedatasphere.linkis.entrance.exception.QueryFailedException; +import com.webank.wedatasphere.linkis.governance.common.entity.task.*; import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; -import com.webank.wedatasphere.linkis.protocol.query.*; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.rpc.Sender; import org.slf4j.Logger; @@ -49,7 +48,7 @@ public class QueryPersistenceEngine extends AbstractPersistenceEngine{ public QueryPersistenceEngine(){ /* - Get the corresponding sender through datawork-cloud-publicservice(通过datawork-cloud-publicservice 拿到对应的sender) + Get the corresponding sender through datawork-linkis-publicservice(通过datawork-linkis-publicservice 拿到对应的sender) */ sender = Sender.getSender(EntranceConfiguration$.MODULE$.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME().getValue()); } @@ -84,7 +83,7 @@ public void persist(Task task) throws QueryFailedException, EntranceIllegalParam throw new QueryFailedException(20011, "insert task failed, reason: " + message); } String taskStr = object.toString(); - Long taskID = Long.parseLong(taskStr.substring(0,taskStr.indexOf("."))); + Long taskID = Long.parseLong(taskStr); ((RequestPersistTask) task).setTaskID(taskID); } }else{ @@ -116,7 +115,7 @@ public Task retrieve(Long taskID)throws EntranceIllegalParamException, QueryFail logger.error("By taskID: {} request the corresponding task return status code is not 0, the query fails(通过taskID: {} 请求相应的task返回状态码不为0,查询失败)", taskID); throw new QueryFailedException(20010, "retrieve task failed, reason: " + message); } - java.util.Map data = responsePersist.getData(); + Map data = responsePersist.getData(); if (data != null){ Object object = data.get(TaskConstant.TASK); if (object instanceof List){ diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java similarity index 92% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java index a73cd8d8e8..ebfed2bff1 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/QueryPersistenceManager.java @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,8 +24,8 @@ import com.webank.wedatasphere.linkis.entrance.EntranceContext; import com.webank.wedatasphere.linkis.entrance.cs.CSEntranceHelper; import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo; -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask; import com.webank.wedatasphere.linkis.protocol.task.Task; import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse; import com.webank.wedatasphere.linkis.scheduler.queue.Job; @@ -84,7 +81,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { path = createResultSetEngine().persistResultSet(job, response); } catch (Throwable e) { job.onFailure("persist resultSet failed!", e); - if(isEntranceJob) ((EntranceJob)job).incrementResultSetPersisted(); + if (isEntranceJob) ((EntranceJob) job).incrementResultSetPersisted(); return; } if(StringUtils.isNotBlank(path)) { @@ -99,7 +96,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { logger.error("job {} onLogUpdate error, reason:", job.getId(), e1); } //ignore it if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } return; } @@ -108,7 +105,7 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { if(StringUtils.isEmpty(requestPersistTask.getResultLocation())) synchronized (task) { if(StringUtils.isNotEmpty(requestPersistTask.getResultLocation())) { if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } return; } @@ -122,13 +119,13 @@ public void onResultSetCreated(Job job, OutputExecuteResponse response) { } } if(isEntranceJob) { - ((EntranceJob)job).incrementResultSetPersisted(); + ((EntranceJob) job).incrementResultSetPersisted(); } } @Override public void onResultSizeCreated(Job job, int resultSize) { - if(job instanceof EntranceJob) { + if (job instanceof EntranceJob) { ((EntranceJob) job).setResultSize(resultSize); } } @@ -136,9 +133,6 @@ public void onResultSizeCreated(Job job, int resultSize) { @Override public void onProgressUpdate(Job job, float progress, JobProgressInfo[] progressInfo) { job.setProgress(progress); - if (job instanceof EntranceJob){ - ((EntranceJob) job).setProgressInfo(progressInfo); - } updateJobStatus(job); } @@ -162,7 +156,7 @@ public void onJobWaitForRetry(Job job) { @Override public void onJobCompleted(Job job) { - //update by peaceWong(2020/05/10) to set jobID to CS + //update by peaceWong to set jobID to CS try { if (job.isSucceed()) { CSEntranceHelper.registerCSRSData(job); @@ -170,7 +164,6 @@ public void onJobCompleted(Job job) { } catch (Throwable e) { logger.error("Failed to register cs rs data ", e); } - //end update updateJobStatus(job); } diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java new file mode 100644 index 0000000000..93b2c3264a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulApi.java @@ -0,0 +1,405 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.restful; + +import com.google.gson.Gson; +import com.google.gson.internal.LinkedTreeMap; +import com.webank.wedatasphere.linkis.common.log.LogUtils; +import com.webank.wedatasphere.linkis.entrance.EntranceServer; +import com.webank.wedatasphere.linkis.entrance.annotation.EntranceServerBeanAnnotation; +import com.webank.wedatasphere.linkis.entrance.background.BackGroundService; +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration; +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob; +import com.webank.wedatasphere.linkis.entrance.log.LogReader; +import com.webank.wedatasphere.linkis.entrance.utils.JobHistoryHelper; +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask; +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant; +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo; +import com.webank.wedatasphere.linkis.protocol.task.Task; +import com.webank.wedatasphere.linkis.protocol.utils.ZuulEntranceUtils; +import com.webank.wedatasphere.linkis.rpc.Sender; +import com.webank.wedatasphere.linkis.scheduler.queue.Job; +import com.webank.wedatasphere.linkis.server.Message; +import com.webank.wedatasphere.linkis.server.security.SecurityFilter; +import com.webank.wedatasphere.linkis.server.socket.controller.ServerEvent; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import scala.Option; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.*; + +/** + * Description: an implementation class of EntranceRestfulRemote + */ +@Path("/entrance") +@Component +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class EntranceRestfulApi implements EntranceRestfulRemote { + + private EntranceServer entranceServer; + + private static final Logger logger = LoggerFactory.getLogger(EntranceRestfulApi.class); + + @EntranceServerBeanAnnotation.EntranceServerAutowiredAnnotation + public void setEntranceServer(EntranceServer entranceServer) { + this.entranceServer = entranceServer; + } + + /** + * The execute function handles the request submitted by the user to execute the task, and the execution ID is returned to the user. + * execute函数处理的是用户提交执行任务的请求,返回给用户的是执行ID + * json Incoming key-value pair(传入的键值对) + * Repsonse + */ + @Override + @POST + @Path("/execute") + public Response execute(@Context HttpServletRequest req, Map json) { + Message message = null; +// try{ + logger.info("Begin to get an execID"); + json.put(TaskConstant.UMUSER, SecurityFilter.getLoginUsername(req)); + String execID = entranceServer.execute(json); + Job job = entranceServer.getJob(execID).get(); + Task task = ((EntranceJob) job).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + pushLog(LogUtils.generateInfo("You have submitted a new job, script code (after variable substitution) is"), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(((RequestPersistTask) task).getCode(), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(LogUtils.generateInfo("Your job is accepted, jobID is " + execID + " and taskID is " + taskID + ". Please wait it to be scheduled"), job); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/execute"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); +// }catch(ErrorException e){ +// message = Message.error(e.getDesc()); +// message.setStatus(1); +// message.setMethod("/api/entrance/execute"); +// } + return Message.messageToResponse(message); + + } + + @Override + @POST + @Path("/submit") + public Response submit(@Context HttpServletRequest req, Map json) { + Message message = null; + logger.info("Begin to get an execID"); + json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req)); + String execID = entranceServer.execute(json); + Job job = entranceServer.getJob(execID).get(); + Task task = ((EntranceJob) job).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + pushLog(LogUtils.generateInfo("You have submitted a new job, script code (after variable substitution) is"), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(((RequestPersistTask) task).getCode(), job); + pushLog("************************************SCRIPT CODE************************************", job); + pushLog(LogUtils.generateInfo("Your job is accepted, jobID is " + execID + " and taskID is " + taskID + ". Please wait it to be scheduled"), job); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/submit"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); + return Message.messageToResponse(message); + } + + private void pushLog(String log, Job job) { + entranceServer.getEntranceContext().getOrCreateLogManager().onLogUpdate(job, log); + } + + @Override + @GET + @Path("/{id}/status") + public Response status(@PathParam("id") String id, @QueryParam("taskID") String taskID) { + Message message = null; + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = Option.apply(null); + try { + job = entranceServer.getJob(realId); + } catch (Exception e) { + logger.warn("获取任务 {} 状态时出现错误", realId, e); + //如果获取错误了,证明在内存中已经没有了,去jobhistory找寻一下taskID代表的任务的状态,然后返回 + long realTaskID = Long.parseLong(taskID); + String status = JobHistoryHelper.getStatusByTaskID(realTaskID); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/status"); + message.data("status", status).data("execID", id); + return Message.messageToResponse(message); + } + if (job.isDefined()) { + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/status"); + message.data("status", job.get().getState().toString()).data("execID", id); + } else { + message = Message.error("ID The corresponding job is empty and cannot obtain the corresponding task status.(ID 对应的job为空,不能获取相应的任务状态)"); + } + return Message.messageToResponse(message); + } + + + + + @Override + @GET + @Path("/{id}/progress") + public Response progress(@PathParam("id") String id) { + Message message = null; + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = entranceServer.getJob(realId); + if (job.isDefined()) { + JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo(); + if (jobProgressInfos == null) { + message = Message.error("Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)"); + message.setMethod("/api/entrance/" + id + "/progress"); + } else { + List> list = new ArrayList<>(); + for (JobProgressInfo jobProgressInfo : jobProgressInfos) { + if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())) { + Map map = new HashMap<>(); + map.put("id", jobProgressInfo.id()); + map.put("succeedTasks", jobProgressInfo.succeedTasks()); + map.put("failedTasks", jobProgressInfo.failedTasks()); + map.put("runningTasks", jobProgressInfo.runningTasks()); + map.put("totalTasks", jobProgressInfo.totalTasks()); + list.add(map); + } else if (jobProgressInfo.failedTasks() > 0 || jobProgressInfo.runningTasks() > 0) { + Map map = new HashMap<>(); + map.put("id", jobProgressInfo.id()); + map.put("succeedTasks", jobProgressInfo.succeedTasks()); + map.put("failedTasks", jobProgressInfo.failedTasks()); + map.put("runningTasks", jobProgressInfo.runningTasks()); + map.put("totalTasks", jobProgressInfo.totalTasks()); + list.add(map); + } + } + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/progress"); + message.data("progress", job.get().getProgress()).data("execID", id).data("progressInfo", list); + } + } else { + message = Message.error("The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)"); + } + return Message.messageToResponse(message); + } + + @Override + @GET + @Path("/{id}/log") + public Response log(@Context HttpServletRequest req, @PathParam("id") String id) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = Option.apply(null); + Message message = null; + try { + job = entranceServer.getJob(realId); + } catch (final Throwable t) { + message = Message.error("The job you just executed has ended. This interface no longer provides a query. It is recommended that you download the log file for viewing.(您刚刚执行的job已经结束,本接口不再提供查询,建议您下载日志文件进行查看)"); + message.setMethod("/api/entrance/" + id + "/log"); + return Message.messageToResponse(message); + } + if (job.isDefined()) { + logger.debug("开始获取 {} 的日志", job.get().getId()); + LogReader logReader = entranceServer.getEntranceContext().getOrCreateLogManager().getLogReader(realId); + int fromLine = 0; + int size = 100; + boolean distinctLevel = true; + if (req != null) { + String fromLineStr = req.getParameter("fromLine"); + String sizeStr = req.getParameter("size"); + if (StringUtils.isNotBlank(fromLineStr)) { + fromLine = Math.max(Integer.parseInt(fromLineStr), 0); + } + if (StringUtils.isNotBlank(sizeStr)) { + size = Integer.parseInt(sizeStr) >= 0 ? Integer.parseInt(sizeStr) : 10000; + } + String distinctLevelStr = req.getParameter("distinctLevel"); + if ("false".equals(distinctLevelStr)) { + distinctLevel = false; + } + } + + Object retLog = null; + int retFromLine = 0; + try { + if (distinctLevel) { + String[] logs = new String[4]; + retFromLine = logReader.readArray(logs, fromLine, size); + retLog = new ArrayList(Arrays.asList(logs)); + } else { + StringBuilder sb = new StringBuilder(); + retFromLine = logReader.read(sb, fromLine, size); + retLog = sb.toString(); + } + } catch (IllegalStateException e) { + logger.error("为 {} 获取日志失败 原因:{}", job.get().getId(), e.getMessage()); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + } catch (final IllegalArgumentException e) { + logger.error("为 {} 获取日志失败", job.get().getId()); + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + return Message.messageToResponse(message); + } catch (final Exception e1) { + logger.error("为 {} 获取日志失败", job.get().getId(), e1); + message = Message.error("Failed to get log information(获取日志信息失败)"); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine); + return Message.messageToResponse(message); + } + message = Message.ok(); + message.setMethod("/api/entrance/" + id + "/log"); + message.data("log", retLog).data("execID", id).data("fromLine", retFromLine + fromLine); + logger.debug("获取 {} 日志成功", job.get().getId()); + } else { + message = Message.error("Can't find execID(不能找到execID): " + id + "Corresponding job, can not get the corresponding log(对应的job,不能获得对应的日志)"); + message.setMethod("/api/entrance/" + id + "/log"); + } + return Message.messageToResponse(message); + } + + + @Override + @GET + @Path("/{id}/kill") + public Response kill(@PathParam("id") String id, @QueryParam("taskID") long taskID) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + //通过jobid获取job,可能会由于job找不到而导致有looparray的报错,一旦报错的话,就可以将该任务直接置为Cancenlled + Option job = Option.apply(null); + try { + job = entranceServer.getJob(realId); + } catch (Exception e) { + logger.warn("can not find a job in entranceServer, will force to kill it", e); + //如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的 + JobHistoryHelper.forceKill(taskID); + Message message = Message.ok("强制杀死任务"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(0); + return Message.messageToResponse(message); + } + Message message = null; + if (job.isEmpty()) { + message = Message.error("Can't find execID(不能找到execID): " + id + "Corresponding job, can't kill(对应的job,不能进行kill)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(1); + } else { + try { + logger.info("begin to kill job {} ", job.get().getId()); + job.get().kill(); + message = Message.ok("Successfully killed the job(成功kill了job)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(0); + message.data("execID", id); + //ensure the job's state is cancelled in database + if (job.get() instanceof EntranceJob) { + EntranceJob entranceJob = (EntranceJob) job.get(); + Task task = entranceJob.getTask(); + ((RequestPersistTask) task).setStatus("Cancelled"); + this.entranceServer.getEntranceContext().getOrCreatePersistenceManager().createPersistenceEngine().updateIfNeeded(task); + } + logger.info("end to kill job {} ", job.get().getId()); + } catch (Throwable t) { + logger.error("kill job {} failed ", job.get().getId(), t); + message = Message.error("An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)"); + message.setMethod("/api/entrance/" + id + "/kill"); + message.setStatus(1); + } + } + return Message.messageToResponse(message); + } + + @Override + @GET + @Path("/{id}/pause") + public Response pause(@PathParam("id") String id) { + String realId = ZuulEntranceUtils.parseExecID(id)[3]; + Option job = entranceServer.getJob(realId); + Message message = null; + if (job.isEmpty()) { + message = Message.error("不能找到execID: " + id + "对应的job,不能进行pause"); + message.setMethod("/api/entrance/" + id + "/pause"); + message.setStatus(1); + } else { + try { + //todo job pause 接口还未实现和给出 + //job.pause(); + logger.info("begin to pause job {} ", job.get().getId()); + message = Message.ok("成功pause了job"); + message.setStatus(0); + message.data("execID", id); + message.setMethod("/api/entrance/" + id + "/pause"); + logger.info("end to pause job {} ", job.get().getId()); + } catch (Throwable t) { + logger.info("pause job {} failed ", job.get().getId()); + message = Message.error("Abnormal when pausing job, pause failed(pause job的时候出现了异常,pause失败)"); + message.setMethod("/api/entrance/" + id + "/pause"); + message.setStatus(1); + } + } + return Message.messageToResponse(message); + } + + @Override + @POST + @Path("/backgroundservice") + public Response backgroundservice(@Context HttpServletRequest req, Map json) { + Message message = null; + logger.info("Begin to get an execID"); + String backgroundType = (String) json.get("background"); + BackGroundService[] bgServices = entranceServer.getEntranceContext().getOrCreateBackGroundService(); + BackGroundService bgService = null; + for (BackGroundService backGroundService : bgServices) { + if (backgroundType.equals(backGroundService.serviceType())) { + bgService = backGroundService; + break; + } + } + Gson gson = new Gson(); + Map executionCode = (Map) json.get("executionCode"); + executionCode = gson.fromJson(gson.toJson(executionCode), LinkedTreeMap.class); + json.put("executionCode", executionCode); + json.put(TaskConstant.UMUSER, SecurityFilter.getLoginUsername(req)); + ServerEvent serverEvent = new ServerEvent(); + serverEvent.setData(json); + serverEvent.setUser(SecurityFilter.getLoginUsername(req)); + ServerEvent operation = bgService.operation(serverEvent); + String execID = entranceServer.execute(operation.getData()); + Task task = ((EntranceJob) entranceServer.getJob(execID).get()).getTask(); + Long taskID = ((RequestPersistTask) task).getTaskID(); + execID = ZuulEntranceUtils.generateExecID(execID, Sender.getThisServiceInstance().getApplicationName(), new String[]{Sender.getThisInstance()}); + message = Message.ok(); + message.setMethod("/api/entrance/backgroundservice"); + message.data("execID", execID); + message.data("taskID", taskID); + logger.info("End to get an an execID: {}, taskID: {}", execID, taskID); + return Message.messageToResponse(message); + + } +} diff --git a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java similarity index 94% rename from ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java rename to linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java index 7813eccf89..3bfd3f3f0c 100644 --- a/ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java +++ b/linkis-computation-governance/linkis-entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/server/DefaultEntranceServer.java @@ -25,10 +25,7 @@ import javax.annotation.PostConstruct; -/** - * created by enjoyyin on 2018/10/12 - * Description: - */ + @EntranceServerBeanAnnotation public class DefaultEntranceServer extends EntranceServer { @@ -46,6 +43,7 @@ public DefaultEntranceServer(EntranceContext entranceContext) { @PostConstruct public void init() { getEntranceWebSocketService(); + addRunningJobEngineStatusMonitor(); } @Override @@ -63,4 +61,7 @@ public LogReader logReader(String execId) { return getEntranceContext().getOrCreateLogManager().getLogReader(execId); } + private void addRunningJobEngineStatusMonitor() { + + } } diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml b/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml new file mode 100644 index 0000000000..62b82b3283 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/application.yml @@ -0,0 +1,27 @@ +server: + port: 9104 +spring: + application: + name: linkis-cg-entrance + + +eureka: + client: + serviceUrl: + defaultZone: http://127.0.0.1:20303/eureka/ + instance: + metadata-map: + test: + +management: + endpoints: + web: + exposure: + include: refresh,info +logging: + config: classpath:log4j2.xml +# register-with-eureka: false +# fetch-registry: false +ribbon: + ReadTimeout: 10000 + ConnectTimeout: 10000 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties b/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties new file mode 100644 index 0000000000..c34c581003 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/linkis-server.properties @@ -0,0 +1,20 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +##restful +wds.linkis.server.restful.scan.packages=com.webank.wedatasphere.linkis.entrance.restful +wds.linkis.server.socket.mode=false +#wds.linkis.entrance.config.log.path=hdfs:///tmp/linkis/ +#wds.linkis.resultSet.store.path=hdfs:///tmp/linkis \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml b/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..0f19fc3c17 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala similarity index 97% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala index 881f544158..3f216504f3 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceContext.scala @@ -23,9 +23,7 @@ import com.webank.wedatasphere.linkis.entrance.log.LogManager import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager import com.webank.wedatasphere.linkis.scheduler.Scheduler -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class EntranceContext { def getOrCreateScheduler(): Scheduler @@ -40,6 +38,7 @@ abstract class EntranceContext { /** * Please note: it can be empty(请注意:可以为空) + * * @return */ def getOrCreateEventListenerBus: EntranceEventListenerBus[EntranceEventListener, EntranceEvent] diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceParser.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala similarity index 97% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala index da2188f763..d12199fb8b 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceServer.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,15 +18,13 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.exception.{EntranceErrorException, SubmitFailedException} import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob import com.webank.wedatasphere.linkis.entrance.log.LogReader -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import org.apache.commons.lang.StringUtils import org.apache.commons.lang.exception.ExceptionUtils -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class EntranceServer extends Logging { private var entranceWebSocketService: Option[EntranceWebSocketService] = None diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala similarity index 92% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala index 89ae6100fd..ec0e0ef792 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/EntranceWebSocketService.scala @@ -30,9 +30,9 @@ import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob import com.webank.wedatasphere.linkis.entrance.log.LogReader import com.webank.wedatasphere.linkis.entrance.restful.EntranceRestfulApi +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.utils.ZuulEntranceUtils import com.webank.wedatasphere.linkis.rpc.Sender import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} @@ -41,9 +41,7 @@ import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration import com.webank.wedatasphere.linkis.server.socket.controller.{ServerEvent, ServerEventService, SocketServerEvent} import org.apache.commons.lang.StringUtils -/** - * Created by enjoyyin on 2018/9/14. - */ + class EntranceWebSocketService extends ServerEventService with EntranceEventListener { private val jobIdToEventId = new util.HashMap[String, Integer] @@ -59,7 +57,6 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList private val killUrlPattern = (restfulURI + """entrance/(.+)/kill""").r private val pauseUrlPattern = (restfulURI + """entrance/(.+)/pause""").r private val backgroundUrlPattern = restfulURI + """entrance/backgroundservice""" - private val runtimeTuningUrlPattern = (restfulURI + """entrance/(.+)/runtimeTuning""").r def setEntranceServer(entranceServer: EntranceServer):Unit = this.entranceServer = entranceServer def setEntranceRestfulApi(entranceRestfulApi: EntranceRestfulApi):Unit = this.entranceRestfulApi = entranceRestfulApi @@ -140,13 +137,9 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList LogUtils.generateInfo(s"Your job's execution code is (after variable substitution and code check) ")) entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, "************************************SCRIPT CODE************************************") -// entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,task.asInstanceOf[RequestPersistTask].getCode) val code = task.asInstanceOf[RequestPersistTask].getCode val codeLength = code.length() - val pushLog = if (codeLength > 1000){ - code.substring(0, 1000) + " ... " - } else code - entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,pushLog) + entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job,code) entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, "************************************SCRIPT CODE************************************") entranceServer.getEntranceContext.getOrCreateLogManager().onLogUpdate(job, @@ -167,11 +160,11 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => { + case entranceExecutionJob: EntranceExecutionJob => { info(s"begin to get job $realID log via websocket") - val logsArr:Array[String] = new Array[String](4) + val logsArr: Array[String] = new Array[String](4) entranceExecutionJob.getWebSocketLogReader.foreach(logReader => logReader.readArray(logsArr, 0, 100)) - val logList:util.List[String] = new util.ArrayList[String]() + val logList: util.List[String] = new util.ArrayList[String]() logsArr foreach logList.add retMessage = Message.ok("Successfully obtained log information(成功获取到日志信息)") retMessage.data("execID", id).data("log", logList).data("websocketTag", websocketTagJobID.get(realID)) @@ -196,11 +189,11 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList //val realID:String = if (entranceServer.getJob(id).isDefined) id else ZuulEntranceUtils.parseExecID(id)(2) val realID:String = if (!id.contains(":")) id else ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => + case entranceExecutionJob: EntranceExecutionJob => val longExecID = ZuulEntranceUtils.generateExecID(realID, entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName, Sender.getThisInstance, entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName) - if(!jobIdToEventId.containsKey(realID) && event != null) jobIdToEventId synchronized jobIdToEventId.put(realID, event.getId) + if (!jobIdToEventId.containsKey(realID) && event != null) jobIdToEventId synchronized jobIdToEventId.put(realID, event.getId) val status = entranceExecutionJob.getState retMessage = Message.ok("Get the status of the task successfully(获取任务状态成功)") @@ -226,7 +219,7 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => { + case entranceExecutionJob: EntranceExecutionJob => { val progress = entranceExecutionJob.getProgress retMessage = Message.ok("Get the task progress successfully(获取任务进度成功)") val taskID = entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getTaskID @@ -254,16 +247,16 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList var retMessage:Message = null val realID = ZuulEntranceUtils.parseExecID(id)(3) entranceServer.getJob(realID) foreach { - case entranceExecutionJob:EntranceExecutionJob => - try{ + case entranceExecutionJob: EntranceExecutionJob => + try { entranceExecutionJob.kill() retMessage = Message.ok("Kill task succeeded(kill任务成功)") retMessage.setMethod(restfulURI + "entrance/" + id + "/kill") retMessage.setStatus(0) return retMessage - }catch{ - case e:Exception => retMessage = Message.error("Kill task failed(kill任务失败)", e) - case t:Throwable => retMessage = Message.error("Kill task failed(kill任务失败)", t) + } catch { + case e: Exception => retMessage = Message.error("Kill task failed(kill任务失败)", e) + case t: Throwable => retMessage = Message.error("Kill task failed(kill任务失败)", t) } case _ => } @@ -380,27 +373,33 @@ class EntranceWebSocketService extends ServerEventService with EntranceEventList } } }) - val logList:util.List[String] = new util.ArrayList[String]() + if (StringUtils.isBlank(info.toString()) && + StringUtils.isBlank(warn.toString()) && + StringUtils.isBlank(error.toString()) && + StringUtils.isBlank(all.toString())) { + return + } + val logList: util.List[String] = new util.ArrayList[String]() logList.add(error.toString()) logList.add(warn.toString()) logList.add(info.toString()) logList.add(all.toString()) message = Message.ok("Return log information(返回日志信息)") val executeApplicationName = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName - val creator:String = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName - val execID:String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) + val creator: String = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName + val execID: String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) message.setMethod(restfulURI + "entrance/" + execID + "/log") val taskID = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getTaskID - message.data("execID",execID).data("log", logList).data("websocketTag", websocketTagJobID.get(job.getId)).data("taskID", taskID) + message.data("execID", execID).data("log", logList).data("websocketTag", websocketTagJobID.get(job.getId)).data("taskID", taskID) sendMsg(job, message) } def pushProgressToFrontend(job: Job, progress: Float, progressInfo: Array[JobProgressInfo]): Unit = { val progressInfoMap = progressInfo.map(info => toJavaMap(Map("id" -> info.id, "succeedTasks" -> info.succeedTasks, - "failedTasks" -> info.failedTasks , "runningTasks" -> info.runningTasks, "totalTasks" -> info.totalTasks))) + "failedTasks" -> info.failedTasks, "runningTasks" -> info.runningTasks, "totalTasks" -> info.totalTasks))) val executeApplicationName = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getExecuteApplicationName val creator = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getRequestApplicationName job.asInstanceOf[EntranceJob].setProgressInfo(progressInfo) - val execID:String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) + val execID: String = ZuulEntranceUtils.generateExecID(job.getId, executeApplicationName, Sender.getThisInstance, creator) val message = Message.ok("返回进度信息!") message.setMethod(restfulURI + "entrance/" + execID + "/progress") val taskID = job.asInstanceOf[EntranceJob].getTask.asInstanceOf[RequestPersistTask].getTaskID diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/AbstractBackGroundService.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/background/BackGroundService.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala similarity index 85% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala index f2258e1563..f5532539d1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cache/GlobalConfigurationKeyValueCache.scala @@ -15,18 +15,17 @@ */ package com.webank.wedatasphere.linkis.entrance.cache + import java.util import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.protocol.conf.{RequestQueryGlobalConfig, ResponseQueryConfig} import com.webank.wedatasphere.linkis.protocol.CacheableProtocol -import com.webank.wedatasphere.linkis.protocol.config.{RequestQueryGlobalConfig, ResponseQueryConfig} -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.rpc.RPCMapCache -/** - * Created by enjoyyin on 2018/11/4. - */ + object GlobalConfigurationKeyValueCache extends RPCMapCache[RequestPersistTask, String, String](EntranceConfiguration.CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME.getValue) { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala new file mode 100644 index 0000000000..ff2ff61dd5 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConfiguration.scala @@ -0,0 +1,157 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.conf + +import com.webank.wedatasphere.linkis.common.conf.{CommonVars, TimeType} + + +object EntranceConfiguration { + + val ENTRANCE_SCHEDULER_MAX_PARALLELISM_USERS = CommonVars("wds.linkis.entrance.scheduler.maxParallelismUsers", new Integer(1000)) + val ENTRANCE_LISTENER_BUS_EVENT_QUEUE_CAPACITY = CommonVars("wds.linkis.entrance.listenerBus.queue.capacity", new Integer(5000)) + + val JOB_MAX_PERSIST_WAIT_TIME = CommonVars("wds.linkis.entrance.job.persist.wait.max", new TimeType("5m")) + + val MULTI_ENTRANCE_CONDITION = CommonVars("wds.linkis.entrance.multi.entrance.flag", true) + + val RESULT_SET_STORE_PATH = CommonVars("wds.linkis.resultSet.store.path", CommonVars[String]("wds.linkis.filesystem.hdfs.root.path").getValue) + + /** + * QUERY_PERSISTENCE_SPRING_APPLICATION_NAME is the name of the application that represents the query module in springcloud + * QUERY_PERSISTENCE_SPRING_APPLICATION_NAME 是表示query模块在springcloud中的应用名称 + */ + val QUERY_PERSISTENCE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.query.application.name", "linkis-ps-publicservice") + /** + * DEFAULT_LOGPATH_PREFIX is the prefix that represents the default log storage path + * DEFAULT_LOGPATH_PREFIX 是表示默认的日志存储路径的前缀 + */ + val DEFAULT_LOGPATH_PREFIX = CommonVars[String]("wds.linkis.entrance.config.log.path", CommonVars[String]("wds.linkis.filesystem.hdfs.root.path").getValue) + /** + * Default_Cache_Max is used to specify the size of the LoopArray of the CacheLogWriter + * Default_Cache_Max 是用来指定CacheLogWriter的LoopArray的大小 + */ + val DEFAULT_CACHE_MAX = CommonVars("wds.linkis.entrance.log.cacheMax", 500) + /** + * Default_Log_CharSet is used to specify the encoding mode of the log storage. + * Default_Log_CharSet 是用来指定日志存储的编码方式 + */ + val DEFAULT_LOG_CHARSET = CommonVars("wds.linkis.entrance.log.defaultCharSet", "utf-8") + /** + * The application name of the console module in spring-cloud + * console 模块在spring-cloud中的应用名称 + */ + val CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.console.configuration.application.name", "linkis-ps-publicservice") + val CLOUD_CONSOLE_VARIABLE_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.console.variable.application.name", "linkis-ps-publicservice") + /** + * The logPath in the console module returns the key in the map. + * console 模块中logPath在返回map中的key + */ + val CLOUD_CONSOLE_LOGPATH_KEY = CommonVars("wds.linkis.console.config.logPath", "wds.linkis.config.logPath") + /** + * requestApplicationName(Creator) The default service name, the default is IDE + * requestApplicationName(Creator) 默认的服务名,默认为IDE + */ + val DEFAULT_REQUEST_APPLICATION_NAME = CommonVars("wds.linkis.default.requestApplication.name", "IDE") + /** + * runType + */ + val DEFAULT_RUN_TYPE = CommonVars("wds.linkis.default.runType", "sql") + + val DEFAULT_CREATE_SERVICE = CommonVars("wds.linkis.default.create.service", "dss") + + val LOG_WARN_EXCLUDE = CommonVars("wds.linkis.warn.log.exclude", "org.apache,hive.ql,hive.metastore,com.netflix,com.webank.wedatasphere") + + val CLEAR_LOG = CommonVars("wds.linkis.log.clear", false) + + /** + * LOG_EXCLUDE is used to remove the log of the framework log, such as hive spark spring, so that it is not pushed to the front end through websocket. + * LOG_EXCLUDE 是用来进行把框架日志,比如hive spark spring等日志进行剔除,不让其通过websocket进行推送到前端 + */ + val LOG_EXCLUDE = CommonVars("wds.linkis.log.exclude", "org.apache,hive.ql,hive.metastore,com.netflix,com.webank.wedatasphere,com.webank") + + /** + * wds.linkis.dwc.instance is a parameter used to control the number of engines each user starts. + *wds.linkis.instance 是用来进行控制每个用户启动engine数量的参数 + */ + val WDS_LINKIS_INSTANCE = CommonVars("wds.linkis.instance", 3) + + val LOG_EXCLUDE_ALL = CommonVars("wds.linkis.log.exclude.all", "com.netflix") + + val MAX_ASK_EXECUTOR_TIME = CommonVars("wds.linkis.max.ask.executor.time", new TimeType("5m")) + + val ERROR_CODE_FILE_DIR = CommonVars("wds.linkis.errorcode.file.dir", "") + + val ENTRANCE_USER = CommonVars("wds.linkis.entrance.user", "") + + val ERROR_CODE_FILE = CommonVars("wds.linkis.errorcode.file", "") + + //todo enjoyyin Simple processing first, this log is not filtered, and subsequent optimization is performed.(先简单处理 不过滤这个日志,后续进行优化) + val HIVE_SPECIAL_LOG_INCLUDE = CommonVars("wds.linkis.hive.special.log.include", "org.apache.hadoop.hive.ql.exec.Task") + + val SHARE_FILE_PRE = CommonVars("wds.linkis.share.file.prefix", "") + + val HIVE_THREAD_NAME = CommonVars("wds.linkis.hive.thread.name", "[Thread") + + val HIVE_STAGE_NAME = CommonVars("wds.linkis.hive.stage.name", "Stage-") + + val SPARK_SPECIAL_LOG_INCLUDE = CommonVars("wds.linkis.spark.special.log.include", "com.webank.wedatasphere.linkis.engine.spark.utils.JobProgressUtil") + + + val SPARK_PROGRESS_NAME = CommonVars("wds.linkis.spark.progress.name", "com.webank.wedatasphere.linkis.engine.spark.utils.JobProgressUtil$") + + val END_FLAG = CommonVars("bdp.dataworkcloud.entrance.end.flag", "info -") + + val HIVE_CREATE_TABLE_LOG = CommonVars("wds.linkis.hive.create.table.log", "numFiles") + + val HIVE_PRINT_INFO_LOG = CommonVars("wds.linkis.hive.printinfo.log", "printInfo -") + + val DATAMAP_APPID = CommonVars("wds.linkis.entrance.datawmap.appid", "75116e6f690e6d222fb55f2dd6f9cb5a") + + val DATAMAP_APPTOKEN = CommonVars("wds.linkis.entrance.datamap.apptoken", + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJjb29wZXJ5YW5nIiwiYXBwa2V5IjoiNzUxMTZlNmY2OTBlNmQyMjJmYjU1ZjJkZDZmOWNiNWEiLCJpYXQiOjE1NzE4MTQxOTYzNDZ9.JfjvsiNMWSc1RnQh1k7vsNjwp4YRquT_XXbYmlEgBgc") + + + val DATA_MAP_IP = CommonVars("wds.linkis.entrance.datamap.ip", "") + + //val DATA_MAP_PORT = CommonVars("wds.linkis.entrance.datamap.port", "8122") + val DATA_MAP_PORT = CommonVars("wds.linkis.entrance.datamap.port", "9001") + + val IS_BDP_ENV = CommonVars("wds.linkis.entrance.bdp.env", "true") + + + val SHELL_DANGER_CHECK_SWITCH = CommonVars("wds.linkis.entrance.shell.danger.check.enabled", false) + val SHELL_DANGER_USAGE = CommonVars("wds.linkis.shell.danger.usage", "rm,sh,find,kill,python,for,source,hdfs,hadoop,spark-sql,spark-submit,pyspark,spark-shell,hive,yarn") + val SHELL_WHITE_USAGE = CommonVars("wds.linkis.shell.white.usage", "cd,ls") + + val FLOW_EXECUTION_CREATOR = CommonVars("wds.linkis.entrance.flow.creator", "nodeexecution") + + val SCHEDULER_CREATOR = CommonVars("wds.linkis.entrance.scheduler.creator", "scheduler") + + + val IS_QML = CommonVars("wds.linkis.entrance.is.qml", false) + + val PROGRESS_PUSH = CommonVars[String]("wds.linkis.entrance.push.progress", "false") + + val CONCURRENT_FACTORY_MAX_CAPACITY = CommonVars("wds.linkis.concurrent.group.factory.capacity", 1000) + + val CONCURRENT_MAX_RUNNING_JOBS = CommonVars("wds.linkis.concurrent.group.factory.running.jobs", 30) + + val CONCURRENT_EXECUTOR_TIME = CommonVars("wds.linkis.concurrent.group.factory.executor.time", 5 * 60 * 1000) + + val ENGINE_MANAGER_SPRING_APPLICATION_NAME = CommonVars("wds.linkis.enginemanager.application.name", "linkis-cg-engineconnmanager") + + val ENTRANCE_ENGINE_LASTUPDATE_TIMEOUT = CommonVars("wds.linkis.entrance.engine.lastupdate.timeout", new TimeType("5s")) + val ENTRANCE_ENGINE_ACTIVITY_TIMEOUT = CommonVars("wds.linkis.entrance.engine.timeout", new TimeType("10s")) + val ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL = CommonVars("wds.linkis.entrance.engine.activity_monitor.interval", new TimeType("3s")) +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala new file mode 100644 index 0000000000..06f49e5655 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/conf/EntranceConstant.scala @@ -0,0 +1,26 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.conf + +import com.google.gson.Gson + + +object EntranceConstant { + + val GSON = new Gson() + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala similarity index 95% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala index 1caa1325a4..44139ff5ea 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/cs/CSEntranceHelper.scala @@ -25,8 +25,8 @@ import com.webank.wedatasphere.linkis.cs.common.entity.source.{CommonContextKey, import com.webank.wedatasphere.linkis.cs.common.utils.CSCommonUtils import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils import com.webank.wedatasphere.linkis.scheduler.queue.Job import org.apache.commons.lang.StringUtils @@ -34,10 +34,7 @@ import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions._ import scala.collection.mutable -/** - * @author peacewong - * @date 2020/3/5 15:33 - */ + object CSEntranceHelper extends Logging { @@ -150,7 +147,7 @@ object CSEntranceHelper extends Logging { * @return */ def addCSVariable(requestPersistTask: RequestPersistTask): Unit = { - val variableMap = new mutable.HashMap[String, String]() + val variableMap = new util.HashMap[String, Any]() val (contextIDValueStr, nodeNameStr) = getContextInfo(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) if (StringUtils.isNotBlank(contextIDValueStr)) { @@ -161,7 +158,9 @@ object CSEntranceHelper extends Logging { variableMap.put(linkisVariable.getKey, linkisVariable.getValue) } } - TaskUtils.addVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]], variableMap) + if(variableMap.nonEmpty){ + TaskUtils.addVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]], variableMap) + } info(s"parse variable end nodeName:$nodeNameStr") } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEvent.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/event/EntranceEventListenerBus.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/CacheNotReadyException.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceCastFailException.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/EntranceErrorException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala new file mode 100644 index 0000000000..aae992b4ba --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/JobHistoryFailedException.scala @@ -0,0 +1,22 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class JobHistoryFailedException(errorMsg:String) extends ErrorException(50081, errorMsg) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/LogReadFailedException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala new file mode 100644 index 0000000000..7bd885c11e --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SensitiveTablesCheckException.scala @@ -0,0 +1,24 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class SensitiveTablesCheckException(errorMsg:String) extends ErrorException(50079, errorMsg) + +case class DangerousGramsCheckException(errorMsg:String) extends ErrorException(50081, errorMsg) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/exception/SubmitFailedException.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala new file mode 100644 index 0000000000..ad72245900 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/DefaultEntranceExecutor.scala @@ -0,0 +1,87 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, ResponseTaskStatus} +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Mark +import com.webank.wedatasphere.linkis.scheduler.executer.{ConcurrentTaskOperateSupport, ErrorExecuteResponse, ExecutorState, SubmitResponse} + + + +class DefaultEntranceExecutor(id: Long, mark: Mark) extends EntranceExecutor(id, mark) with ConcurrentTaskOperateSupport { + + + /* private def doMethod[T](exec: String => T): T = if (engineReturns.isEmpty) + throw new EntranceErrorException(20001, s"Engine${id} could not find a job in RUNNING state(Engine${id}找不到处于RUNNING状态的Job)") + else exec(engineReturns(0).execId)*/ + + + override protected def callExecute(request: RequestTask): EngineExecuteAsynReturn = { + val response = getEngineConnExecutor().execute(request) + response match { + case SubmitResponse(execId) => new EngineExecuteAsynReturn(request, getEngineConnExecutor().getServiceInstance.getInstance, execId, engineReturn => { + info("remove execId-" + execId + " with instance " + getEngineConnExecutor().getServiceInstance) + engineReturns -= engineReturn + }) + case ErrorExecuteResponse(message, t) => + info(s"failed to submit task to engineConn,reason: $message") + throw t + } + } + + override def close(): Unit = { + if (engineReturns.nonEmpty) engineReturns.foreach { e => + e.notifyError(s"$toString has already been completed with state $state.") + e.notifyStatus(ResponseTaskStatus(e.execId, ExecutionNodeStatus.Failed)) + } + } + + override def kill(jobId: String): Boolean = { + info(s"start to kill job $jobId") + engineReturns.find(_.getJobId.contains(jobId)).exists(e => killExecId(e.execId)) + } + + override def killAll(): Boolean = { + engineReturns.foreach(f => Utils.tryQuietly(killExecId(f.execId))) + true + } + + override def pause(jobId: String): Boolean = { + //TODO + true + } + + + override def pauseAll(): Boolean = { + //TODO + true + } + + override def resume(jobId: String): Boolean = { + //TODO + true + } + + override def resumeAll(): Boolean = { + //TODO + true + } + + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala similarity index 80% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala index 65a1df54dc..9f9a390705 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EngineLockListener.scala @@ -16,10 +16,9 @@ package com.webank.wedatasphere.linkis.entrance.execute -/** - * Created by enjoyyin on 2018/9/15. - */ + trait EngineLockListener { - def onEngineLocked(engine: EntranceEngine, lock: String): Unit - def onEngineLockUsed(engine: EntranceEngine): Unit + def onEngineLocked(engine: EntranceExecutor, lock: String): Unit + + def onEngineLockUsed(engine: EntranceExecutor): Unit } \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala new file mode 100644 index 0000000000..994b8d1a4a --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutionService.scala @@ -0,0 +1,258 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.annotation.EntranceContextBeanAnnotation +import com.webank.wedatasphere.linkis.entrance.conf.{EntranceConfiguration, EntranceConstant} +import com.webank.wedatasphere.linkis.entrance.event.EntranceProgressEvent +import com.webank.wedatasphere.linkis.governance.common.conf.GovernanceCommonConf +import com.webank.wedatasphere.linkis.governance.common.entity.{ExecutionNodeStatus, NodeExistStatus} +import com.webank.wedatasphere.linkis.governance.common.protocol.engineconn.{RequestEngineStatusBatch, ResponseEngineStatusBatch} +import com.webank.wedatasphere.linkis.governance.common.protocol.task._ +import com.webank.wedatasphere.linkis.governance.common.utils.GovernanceConstant +import com.webank.wedatasphere.linkis.manager.common.entity.enumeration.NodeStatus +import com.webank.wedatasphere.linkis.manager.common.protocol.node.{RequestNodeStatus, ResponseNodeStatus} +import com.webank.wedatasphere.linkis.message.annotation.Receiver +import com.webank.wedatasphere.linkis.message.builder.ServiceMethodContext +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.{EngineConnExecutor, TaskExecutionReceiver} +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.rpc.exception.DWCRPCRetryException +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.AliasOutputExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import org.springframework.stereotype.Service + +import javax.annotation.PostConstruct +import scala.collection.JavaConverters._ +import java.util +import java.util.concurrent.TimeUnit + + +@Service +class EntranceExecutionService extends TaskExecutionReceiver with Logging { + + @EntranceContextBeanAnnotation.EntranceContextAutowiredAnnotation + private var entranceContext: EntranceContext = _ + + @PostConstruct + private def init(): Unit = { + addEngineExecutorStatusMonitor() + } + + private[execute] def getEntranceExecutorManager = entranceContext.getOrCreateScheduler().getSchedulerContext + .getOrCreateExecutorManager.asInstanceOf[EntranceExecutorManager] + + private def findEngineExecuteAsyncReturn(execId: String, sender: Sender, message: String): Option[EngineExecuteAsynReturn] = { + val serviceInstance = RPCUtils.getServiceInstanceFromSender(sender) + if (serviceInstance == null || serviceInstance.getInstance == null) { + warn(s"because of not support sender $sender, cannot update the message $message for execId $execId.") + return None + } + val engine = getEntranceExecutorManager.getEntranceExecutorByInstance(serviceInstance.getInstance) + if (engine.isEmpty) { + warn(s"${getEntranceExecutorManager.getClass.getSimpleName} cannot find a entranceEngine to update the message $message for execId $execId from $sender.") + None + } else { + val jobReturn = engine.flatMap(_.getEngineReturns.find(_.execId == execId)) + if (jobReturn.isEmpty) warn(s"${engine.get} cannot find a job to update the message $message for execId $execId from $sender, EngineReturns List is ${engine.map(_.getEngineReturns.map(_.execId).toList).get}.") + jobReturn + } + } + + def onOperate(execId: String, sender: Sender, op: Job => Unit, message: String): Unit = findEngineExecuteAsyncReturn(execId, sender, message).foreach { er => + er.notifyHeartbeat() + er.getJobId.flatMap(entranceContext.getOrCreateScheduler().get).foreach { + case job: Job => op(job) + case _ => + } + } + + private def askRetryWhenExecuteAsyncReturnIsEmpty(execId: String, sender: Sender, message: String) = + findEngineExecuteAsyncReturn(execId, sender, message).getOrElse { + Utils.tryQuietly(Thread.sleep(50)) + findEngineExecuteAsyncReturn(execId, sender, toString) + .getOrElse(throw new DWCRPCRetryException(s"please retry, since $execId cannot be consumed by entrance!")) + } + + @Receiver + override def taskLogReceiver(taskLog: ResponseTaskLog, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + onOperate(taskLog.execId, sender, entranceContext.getOrCreateLogManager().onLogUpdate(_, taskLog.log), "ResponseTaskLog") + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + private def updateExecutorActivityTime(serviceInstance: ServiceInstance) = { + if (null != serviceInstance) { + val engineConnExecutor = getEntranceExecutorManager.engineConnManager.getEngineConnExecutorCache().getOrDefault(serviceInstance, null) + if (null != engineConnExecutor) synchronized { + engineConnExecutor.updateLastUpdateTime() + } else { + warn(s"EngineConnExecutor ${serviceInstance.toString} cannot be found in engineConnExecutorCache") + } + } + } + + @Receiver + override def taskProgressReceiver(taskProgress: ResponseTaskProgress, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + Utils.tryAndWarn { + onOperate(taskProgress.execId, sender, job => { + entranceContext.getOrCreateEventListenerBus.post(EntranceProgressEvent(job, taskProgress.progress, taskProgress.progressInfo)) + entranceContext.getOrCreatePersistenceManager().onProgressUpdate(job, taskProgress.progress, taskProgress.progressInfo) + job.asInstanceOf[EntranceJob].setProgressInfo(taskProgress.progressInfo) + }, "ResponseTaskProgress") + } + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + @Receiver + override def taskStatusReceiver(taskStatus: ResponseTaskStatus, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + if (ExecutionNodeStatus.isCompleted(taskStatus.status)) + info(s"The execId ${taskStatus.execId} from engine $sender is completed with state ${taskStatus.status}.") + askRetryWhenExecuteAsyncReturnIsEmpty(taskStatus.execId, sender, s"ResponseTaskStatus(${taskStatus.execId}, ${taskStatus.status})") + .notifyStatus(taskStatus) + updateExecutorActivityTime(RPCUtils.getServiceInstanceFromSender(sender)) + } + + @Receiver + override def taskResultSizeReceiver(taskResultSize: ResponseTaskResultSize, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + askRetryWhenExecuteAsyncReturnIsEmpty(taskResultSize.execId, sender, "ResponseTaskResultSize") + .getJobId.flatMap(entranceContext.getOrCreateScheduler().get).foreach { + case j: Job => entranceContext.getOrCreatePersistenceManager().onResultSizeCreated(j, taskResultSize.resultSize) + case _ => + } + } + + @Receiver + override def taskResultSetReceiver(taskResultSet: ResponseTaskResultSet, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender + onOperate(taskResultSet.execId, sender + , entranceContext.getOrCreatePersistenceManager() + .onResultSetCreated(_, AliasOutputExecuteResponse(taskResultSet.alias, taskResultSet.output)) + , "ResponseTaskResultSet") + } + + @Receiver + override def taskErrorReceiver(taskTaskError: ResponseTaskError, smc: ServiceMethodContext): Unit = { + val sender = smc.getSender +// askRetryWhenExecuteAsyncReturnIsEmpty(taskTaskError.execId, sender, s"ResponseTaskError(${taskTaskError.execId}, ${taskTaskError.errorMsg})") +// .notifyError(taskTaskError.errorMsg) + onOperate(taskTaskError.execId, sender, entranceContext.getOrCreateLogManager().onLogUpdate(_, taskTaskError.errorMsg), "ResponseTaskErrorLog") + } + + private def addEngineExecutorStatusMonitor(): Unit = { + val task = new Runnable { + override def run(): Unit = { + val startTime = System.currentTimeMillis() + val engineExecutorCache = getEntranceExecutorManager.engineConnManager.getEngineConnExecutorCache() + if (engineExecutorCache.size() > 0) { + info(s"Entrance Executor cache num : ${engineExecutorCache.size()}") + } + val unActivityEngines = engineExecutorCache.asScala.filter(startTime - _._2.getLastUpdateTime() > EntranceConfiguration.ENTRANCE_ENGINE_LASTUPDATE_TIMEOUT.getValue.toLong).keySet + if (null != unActivityEngines && !unActivityEngines.isEmpty) { + info(s"There are ${unActivityEngines.size} unActivity engines.") + val engineList = new util.ArrayList[ServiceInstance]() + unActivityEngines.foreach(engine => { + engineList.add(engine) + if (engineList.size() >= GovernanceConstant.REQUEST_ENGINE_STATUS_BATCH_LIMIT) { + queryEngineStatusAndHandle(engineList, engineExecutorCache) + engineList.clear() + } + }) + if (!engineList.isEmpty) { + queryEngineStatusAndHandle(engineList, engineExecutorCache) + engineList.clear() + } + } + val endTime = System.currentTimeMillis() + if (endTime - startTime >= EntranceConfiguration.ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL.getValue.toLong) { + error("Query engines status costs longer time than query task interval, you should increase interval.") + } + } + } + Utils.defaultScheduler.scheduleWithFixedDelay(task, 10000, EntranceConfiguration.ENTRANCE_ENGINE_ACTIVITY_MONITOR_INTERVAL.getValue.toLong, TimeUnit.MILLISECONDS) + info("Entrance engineStatusMonitor inited.") + } + + private def queryEngineStatusAndHandle(engineList: util.List[ServiceInstance], engineExecutorCache: util.Map[ServiceInstance, EngineConnExecutor]): Unit = { + val requestEngineStatus = RequestEngineStatusBatch(engineList) + Utils.tryAndError { + Sender.getSender(GovernanceCommonConf.MANAGER_SPRING_NAME.getValue).ask(requestEngineStatus) match { + case response: ResponseEngineStatusBatch => + if (null != response.msg) { + info(s"ResponseEngineStatusBatch msg : ${response.msg}") + } + if (response.engineStatus.size() != requestEngineStatus.engineList.size()) { + error("ResponseEngineStatusBatch engines size is not euqal requet.") + } + response.engineStatus.asScala.foreach(status => { + status._2 match { + case NodeExistStatus.UnExist => + warn(s"Engine ${status._1.toString} is Failed, now go to clear its task.") + endJobByEngineInstance(status._1, NodeStatus.Failed) + case NodeExistStatus.Exist | NodeExistStatus.Unknown => + val engineConnExecutor = engineExecutorCache.getOrDefault(status._1, null) + if (null != engineConnExecutor) { + Utils.tryCatch { + // todo check - only for engine with accessible executor + val requestNodeStatus = new RequestNodeStatus + Sender.getSender(status._1).ask(requestNodeStatus) match { + case rs: ResponseNodeStatus => + if (NodeStatus.isCompleted(rs.getNodeStatus)) { + endJobByEngineInstance(status._1, rs.getNodeStatus) + } else { + warn("Will update engineConnExecutor lastupdated time") + updateExecutorActivityTime(status._1) + } + case o: Any => + Utils.tryAndWarn(warn(s"Unknown response : ${EntranceConstant.GSON.toJson(o)} for request : ${EntranceConstant.GSON.toJson(requestNodeStatus)}")) + } + } { + case t: Throwable => + error(s"Failed to get status of engineConn : ${status._1.toString}, now end the job. ", t) + endJobByEngineInstance(status._1, NodeStatus.Failed) + } + } + case o: Any => + error(s"Status of engine ${status._1.toString} is ${status._2}") + } + }) + case _ => + error(s"Invalid response. request : ${EntranceConstant.GSON.toJson(requestEngineStatus)}") + } + } + } + + private def endJobByEngineInstance(engineServiceInstance: ServiceInstance, engineNodeStatus: NodeStatus) = { + Utils.tryQuietly { + val entranceExecutor = getEntranceExecutorManager.getEntranceExecutorByInstance(engineServiceInstance.getInstance).getOrElse(null) + if (null != entranceExecutor) { + entranceExecutor.getEngineReturns.foreach(er => { + er.notifyError(s"Engine has exited unexpectedly with status : ${engineNodeStatus}") + er.notifyStatus(ResponseTaskStatus(er.execId, ExecutionNodeStatus.Failed)) + }) + } else { + warn(s"Cannot find entranceExecutor for ${engineServiceInstance.toString}") + } + } + } +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala new file mode 100644 index 0000000000..7c5193537d --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutor.scala @@ -0,0 +1,189 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import com.webank.wedatasphere.linkis.common.ServiceInstance +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.governance.common.entity.ExecutionNodeStatus._ +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, ResponseTaskStatus} +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.Mark +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.EngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.UserWithCreator +import com.webank.wedatasphere.linkis.scheduler.executer.ExecutorState.ExecutorState +import com.webank.wedatasphere.linkis.scheduler.executer._ + +import scala.collection.mutable.ArrayBuffer + + +abstract class EntranceExecutor(val id: Long, val mark: Mark) extends Executor with Logging { + + + private implicit var userWithCreator: UserWithCreator = _ + + private var engineConnExecutor: EngineConnExecutor = _ + + protected val engineReturns = ArrayBuffer[EngineExecuteAsynReturn]() + + protected var interceptors: Array[ExecuteRequestInterceptor] = Array(LabelExecuteRequestInterceptor, JobExecuteRequestInterceptor) + + + def setInterceptors(interceptors: Array[ExecuteRequestInterceptor]) = if (interceptors != null && interceptors.nonEmpty) { + this.interceptors = interceptors + } + + + def setUser(user: String): Unit = userWithCreator = if (userWithCreator != null) UserWithCreator(user, userWithCreator.creator) + else UserWithCreator(user, null) + + def getUser = if (userWithCreator != null) userWithCreator.user else null + + def setCreator(creator: String): Unit = userWithCreator = if (userWithCreator != null) UserWithCreator(userWithCreator.user, creator) + else UserWithCreator(null, creator) + + def getCreator = if (userWithCreator != null) userWithCreator.creator else null + + + def getEngineConnExecutor(): EngineConnExecutor = this.engineConnExecutor + + def setEngineConnExecutor(engineConnExecutor: EngineConnExecutor): Unit = { + this.engineConnExecutor = engineConnExecutor + } + + def getInstance: ServiceInstance = getEngineConnExecutor().getServiceInstance + + private[execute] def getEngineReturns = engineReturns.toArray + + override def execute(executeRequest: ExecuteRequest): ExecuteResponse = { + var request: RequestTask = null + interceptors.foreach(in => request = in.apply(request, executeRequest)) + if (request.getProperties != null && + request.getProperties.containsKey(ReconnectExecuteRequestInterceptor.PROPERTY_EXEC_ID)) { + val execId = ReconnectExecuteRequestInterceptor.PROPERTY_EXEC_ID.toString + Utils.tryCatch { + getEngineConnExecutor().status(execId) + val engineReturn = new EngineExecuteAsynReturn(request, getInstance.getInstance, execId, _ => callback()) + engineReturns synchronized engineReturns += engineReturn + return engineReturn + } { t: Throwable => + error(s"Failed to get execId $execId status", t) + } + } + val engineReturn = callExecute(request) + engineReturns synchronized engineReturns += engineReturn + engineReturn + } + + protected def callback(): Unit = {} + + protected def callExecute(request: RequestTask): EngineExecuteAsynReturn + + override def toString: String = s"${getInstance.getApplicationName}Engine($getId, $getUser, $getCreator, ${getInstance.getInstance})" + + protected def killExecId(execId: String): Boolean = { + info(s"begin to send killExecId, execID: $execId") + Utils.tryAndError(getEngineConnExecutor().killTask(execId)) + true + } + + override def getId: Long = this.id + + override def state: ExecutorState = ExecutorState.Idle + + override def getExecutorInfo: ExecutorInfo = { + null + } + + def canEqual(other: Any): Boolean = other.isInstanceOf[EntranceExecutor] + + override def equals(other: Any): Boolean = other match { + case that: EntranceExecutor => + (that canEqual this) && + getEngineConnExecutor().equals(that.getEngineConnExecutor()) + case _ => false + } + + def getExecId(jobId: String): String = { + val erOption = engineReturns.find(_.getJobId.contains(jobId)) + if ( erOption.isDefined ) { + erOption.get.execId + } else { + null + } + } + + override def hashCode(): Int = { + getEngineConnExecutor().hashCode() + } +} + +class EngineExecuteAsynReturn(request: RequestTask, val instance: String, + val execId: String, callback: EngineExecuteAsynReturn => Unit) extends AsynReturnExecuteResponse with Logging { + getJobId.foreach(id => info("Job " + id + " received a execId " + execId + " from engine " + instance)) + + private var notifyJob: ExecuteResponse => Unit = _ + + private var error: Throwable = _ + + private var errorMsg: String = _ + + private var lastNotifyTime = System.currentTimeMillis + + def getLastNotifyTime = lastNotifyTime + + private[execute] def notifyStatus(responseEngineStatus: ResponseTaskStatus): Unit = { + lastNotifyTime = System.currentTimeMillis() + val response = responseEngineStatus.status match { + case Succeed => Some(SuccessExecuteResponse()) + case Failed | Cancelled | Timeout => Some(ErrorExecuteResponse(errorMsg, error)) + case _ => None + } + response.foreach { r => + getJobId.foreach(id => info("Job " + id + " with execId-" + execId + " from engine " + instance + " completed with state " + r)) + callback(this) + if (notifyJob == null) this synchronized (while (notifyJob == null) this.wait(1000)) + notifyJob(r) + } + } + + private[execute] def notifyHeartbeat(): Unit = { + lastNotifyTime = System.currentTimeMillis() + } + + private[execute] def notifyError(errorMsg: String): Unit = { + lastNotifyTime = System.currentTimeMillis() + this.errorMsg = errorMsg + } + + private[execute] def notifyError(errorMsg: String, t: Throwable): Unit = { + lastNotifyTime = System.currentTimeMillis() + this.errorMsg = errorMsg + this.error = t + } + + private[execute] def getJobId: Option[String] = { + val jobId = request.getProperties.get(JobExecuteRequestInterceptor.PROPERTY_JOB_ID) + jobId match { + case j: String => Option(j) + case _ => None + } + } + + override def notify(rs: ExecuteResponse => Unit): Unit = { + notifyJob = rs + this synchronized notify() + } +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala new file mode 100644 index 0000000000..7c0871461b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceExecutorManager.scala @@ -0,0 +1,161 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import java.util +import java.util.Date +import java.util.concurrent.atomic.AtomicLong + +import com.webank.wedatasphere.linkis.common.exception.WarnException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManager +import com.webank.wedatasphere.linkis.orchestrator.ecm.entity.{DefaultMarkReq, MarkReq, Policy} +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.impl.ComputationConcurrentEngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{Executor, ExecutorManager} +import com.webank.wedatasphere.linkis.scheduler.queue.{GroupFactory, Job, SchedulerEvent} +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.Duration + + +abstract class EntranceExecutorManager(groupFactory: GroupFactory, val engineConnManager: EngineConnManager) extends ExecutorManager with Logging { + + private val idGenerator = new AtomicLong(0) + + private val idToEngines = new util.HashMap[Long, EntranceExecutor] + + private val instanceToEngines = new util.HashMap[String, EntranceExecutor] + + def getOrCreateInterceptors(): Array[ExecuteRequestInterceptor] + + override def delete(executor: Executor): Unit = { + if (null != executor) { + executor.close() + val entranceExecutor = idToEngines.remove(executor.getId) + instanceToEngines.remove(entranceExecutor.getInstance.getInstance) + entranceExecutor.getEngineConnExecutor() match { + case current: ComputationConcurrentEngineConnExecutor => + case _ => engineConnManager.releaseEngineConnExecutor(entranceExecutor.getEngineConnExecutor(), entranceExecutor.mark) + } + } + } + + protected def createMarkReq(requestPersistTask: RequestPersistTask): MarkReq = { + val markReq = new DefaultMarkReq + markReq.setPolicyObj(Policy.Task) + markReq.setCreateService(requestPersistTask.getCreateService) + markReq.setDescription(requestPersistTask.getDescription) + markReq.setEngineConnCount(3) + val properties = if (requestPersistTask.getParams == null) new util.HashMap[String, String] + else { + val startupMap = TaskUtils.getStartupMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) + val properties = new JMap[String, String] + startupMap.foreach { case (k, v) => if (v != null && StringUtils.isNotEmpty(v.toString)) properties.put(k, v.toString) } + properties + } + // todo get default config from db + markReq.setProperties(properties) + markReq.setUser(requestPersistTask.getUmUser) + markReq.setLabels(LabelUtils.labelsToMap(requestPersistTask.getLabels)) + markReq + } + + + override def askExecutor(schedulerEvent: SchedulerEvent): Option[Executor] = schedulerEvent match { + case job: Job => + val executor = createExecutor(job) + if (executor != null) { + job match { + case entranceExecutionJob: EntranceExecutionJob => val task = entranceExecutionJob.getTask + task.asInstanceOf[RequestPersistTask].setEngineStartTime(new Date()) + case _ => + } + Some(executor) + } else None + + } + + override def askExecutor(schedulerEvent: SchedulerEvent, wait: Duration): Option[Executor] = schedulerEvent match { + case job: Job => + val startTime = System.currentTimeMillis() + var warnException: WarnException = null + var executor: Option[Executor] = None + while (System.currentTimeMillis - startTime < wait.toMillis && executor.isEmpty) + Utils.tryCatch(askExecutor(job)) { + case warn: WarnException => + this.warn("request engine failed!", warn) + warnException = warn + None + case t: Throwable => throw t + } match { + case Some(e) => executor = Option(e) + case _ => + if (System.currentTimeMillis - startTime < wait.toMillis) { + val interval = math.min(3000, wait.toMillis - System.currentTimeMillis + startTime) + //getOrCreateEngineManager().waitForIdle(interval) + } + } + if (warnException != null && executor.isEmpty) throw warnException + executor + } + + override def getById(id: Long): Option[Executor] = { + Option(idToEngines.get(id)) + } + + override def getByGroup(groupName: String): Array[Executor] = { + //TODO by peaceWong + null + } + + override protected def createExecutor(schedulerEvent: SchedulerEvent): EntranceExecutor = schedulerEvent match { + case job: EntranceJob => + job.getTask match { + case requestPersistTask: RequestPersistTask => + // CreateMarkReq + val markReq = createMarkReq(requestPersistTask) + // getMark + val mark = engineConnManager.applyMark(markReq) + // getEngineConn Executor + job.getLogListener.foreach(_.onLogUpdate(job, "Background is starting a new engine for you, it may take several seconds, please wait")) + val engineConnExecutor = engineConnManager.getAvailableEngineConnExecutor(mark) + //TODO 修改Executor创建为builder模式 + val entranceEntranceExecutor = new DefaultEntranceExecutor(idGenerator.incrementAndGet(), mark) + idToEngines.put(entranceEntranceExecutor.getId, entranceEntranceExecutor) + instanceToEngines.put(engineConnExecutor.getServiceInstance.getInstance, entranceEntranceExecutor) + entranceEntranceExecutor.setEngineConnExecutor(engineConnExecutor) + entranceEntranceExecutor.setInterceptors(getOrCreateInterceptors()) + job.getLogListener.foreach(_.onLogUpdate(job, s" Congratulations! Your new engine has started successfully,Engine are ${engineConnExecutor.getServiceInstance}")) + entranceEntranceExecutor + case _ => + throw new EntranceErrorException(20001, "Task is not requestPersistTask, cannot to create Executor") + } + case _ => + throw new EntranceErrorException(20001, "Task is not EntranceJob, cannot to create Executor") + } + + override def shutdown(): Unit = {} + + def getEntranceExecutorByInstance(instance: String): Option[EntranceExecutor] = { + Option(instanceToEngines.get(instance)) + } + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala new file mode 100644 index 0000000000..9c2c7a4a04 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/EntranceJob.scala @@ -0,0 +1,196 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute + +import java.util +import java.util.concurrent.atomic.AtomicInteger + +import com.webank.wedatasphere.linkis.common.log.LogUtils +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.event._ +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.orchestrator.ecm.service.EngineConnExecutor +import com.webank.wedatasphere.linkis.protocol.engine.JobProgressInfo +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.rpc.utils.RPCUtils +import com.webank.wedatasphere.linkis.scheduler.executer.{CompletedExecuteResponse, ErrorExecuteResponse} +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState._ +import com.webank.wedatasphere.linkis.scheduler.queue.{Job, SchedulerEventState} + + +abstract class EntranceJob extends Job { + + private var creator: String = _ + private var user: String = _ + private var params: util.Map[String, Any] = new util.HashMap[String, Any](1) + private var task: Task = _ + + private var entranceListenerBus: Option[EntranceEventListenerBus[EntranceEventListener, EntranceEvent]] = None + private var progressInfo: Array[JobProgressInfo] = Array.empty + private val persistedResultSets = new AtomicInteger(0) + private var resultSize = -1 + private var entranceContext: EntranceContext = _ + + def getTask: Task = task + + def setTask(task: Task): Unit = this.task = task + + def setCreator(creator: String): Unit = this.creator = creator + + def getCreator: String = creator + + def setUser(user: String): Unit = this.user = user + + def getUser: String = user + + def setParams(params: util.Map[String, Any]): Unit = this.params = params + + def getParams: util.Map[String, Any] = params + + def setEntranceListenerBus(entranceListenerBus: EntranceEventListenerBus[EntranceEventListener, EntranceEvent]): Unit = + this.entranceListenerBus = Option(entranceListenerBus) + + def getEntranceListenerBus = this.entranceListenerBus + + def setProgressInfo(progressInfo: Array[JobProgressInfo]): Unit = this.progressInfo = progressInfo + + def getProgressInfo: Array[JobProgressInfo] = this.progressInfo + + def setEntranceContext(entranceContext: EntranceContext): Unit = this.entranceContext = entranceContext + + def getEntranceContext: EntranceContext = this.entranceContext + + + def setResultSize(resultSize: Int): Unit = { + this.resultSize = resultSize + persistedResultSets synchronized persistedResultSets.notify() + } + + def incrementResultSetPersisted(): Unit = { + persistedResultSets.incrementAndGet() + persistedResultSets synchronized persistedResultSets.notify() + } + + protected def isWaitForPersistedTimeout(startWaitForPersistedTime: Long): Boolean = + System.currentTimeMillis - startWaitForPersistedTime >= EntranceConfiguration.JOB_MAX_PERSIST_WAIT_TIME.getValue.toLong + + + override def beforeStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = { + if (SchedulerEventState.isCompleted(toState) && (resultSize < 0 || persistedResultSets.get() < resultSize)) { + val startWaitForPersistedTime = System.currentTimeMillis + persistedResultSets synchronized { + while ((resultSize < 0 || persistedResultSets.get() < resultSize) && getErrorResponse == null && !isWaitForPersistedTimeout(startWaitForPersistedTime)) + persistedResultSets.wait(3000) + } + if (isWaitForPersistedTimeout(startWaitForPersistedTime)) onFailure("persist resultSets timeout!", new EntranceErrorException(20305, "persist resultSets timeout!")) + if (isSucceed && getErrorResponse != null) { + val _toState = if (getErrorResponse.t == null) Cancelled else Failed + transition(_toState) + return + } + } + super.beforeStateChanged(fromState, toState) + } + + override def afterStateChanged(fromState: SchedulerEventState, toState: SchedulerEventState): Unit = { + if (SchedulerEventState.isRunning(toState)) { + def setEngineInstance(task: Task): Unit = task match { + case requestTask: RequestPersistTask => getExecutor match { + case engine: EntranceExecutor => requestTask.setEngineInstance(engine.getInstance.getInstance) + case _ => + } + case haTask: HaPersistenceTask => setEngineInstance(haTask.task) + case _ => + } + + setEngineInstance(task) + } + super.afterStateChanged(fromState, toState) + toState match { + case Scheduled => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is Scheduled. Please wait it to run."))) + case WaitForRetry => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is turn to retry. Please wait it to schedule."))) + case Running => + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo("Your job is Running now. Please wait it to complete."))) + //TODO job start event + case _ if SchedulerEventState.isCompleted(toState) => + endTime = System.currentTimeMillis() + if (getJobInfo != null) getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateInfo(getJobInfo.getMetric))) + if (isSucceed) + getLogListener.foreach(_.onLogUpdate(this, + LogUtils.generateInfo("Congratulations. Your job completed with status Success."))) + else getLogListener.foreach(_.onLogUpdate(this, + LogUtils.generateInfo(s"Sorry. Your job completed with a status $toState. You can view logs for the reason."))) + this.setProgress(1.0f) + entranceListenerBus.foreach(_.post(EntranceProgressEvent(this, 1.0f, this.getProgressInfo))) + this.getProgressListener.foreach(listener => listener.onProgressUpdate(this, 1.0f, Array[JobProgressInfo]())) + case _ => + } + entranceListenerBus.foreach(_.post(EntranceJobEvent(this.getId))) + } + + override def onFailure(errorMsg: String, t: Throwable): Unit = { + this.entranceListenerBus.foreach(_.post( + EntranceLogEvent(this, LogUtils.generateERROR(s"Sorry, your job executed failed with reason: $errorMsg")))) + super.onFailure(errorMsg, t) + } + + override protected def transitionCompleted(executeCompleted: CompletedExecuteResponse): Unit = { + executeCompleted match { + case error: ErrorExecuteResponse if RPCUtils.isReceiverNotExists(error.t) => + entranceListenerBus.foreach(_.post(MissingEngineNotifyEvent(this, error.t, getExecutor))) + case _ => + } + Utils.tryAndErrorMsg(clearInstanceInfo())("Failed to clear executor") + super.transitionCompleted(executeCompleted) + } + + private def clearInstanceInfo(): Unit = { + val executorManager = entranceContext.getOrCreateScheduler().getSchedulerContext.getOrCreateExecutorManager + executorManager.delete(getExecutor) + } + + def transitionCompleted(executeCompleted: CompletedExecuteResponse, reason: String): Unit = { + info("Job directly completed with reason: " + reason) + transitionCompleted(executeCompleted) + } + + override protected def isJobShouldRetry(errorExecuteResponse: ErrorExecuteResponse): Boolean = isJobSupportRetry && errorExecuteResponse != null && + (if (RPCUtils.isReceiverNotExists(errorExecuteResponse.t)) { + getExecutor match { + case e: EntranceExecutor => + val instance = e.getInstance.getInstance + getLogListener.foreach(_.onLogUpdate(this, LogUtils.generateSystemWarn(s"Since the submitted engine rejects the connection, the system will automatically retry and exclude the engine $instance.(由于提交的引擎拒绝连接,系统将自动进行重试,并排除引擎 $instance.)"))) + case _ => + } + true + } else super.isJobShouldRetry(errorExecuteResponse)) + + def operation[T](operate: EntranceExecutor => T ): T = { + this.getExecutor match { + case entranceExecutor: EntranceExecutor => + operate(entranceExecutor) + case _ => throw new EntranceErrorException(10000, "不支持的操作") + } + + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala similarity index 81% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala index aa79e922e3..188680df82 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/ExecuteRequestInterceptor.scala @@ -16,28 +16,26 @@ package com.webank.wedatasphere.linkis.entrance.execute -import com.webank.wedatasphere.linkis.protocol.engine.{RequestTask, RequestTaskExecute} +import com.webank.wedatasphere.linkis.governance.common.protocol.task.{RequestTask, RequestTaskExecute} import com.webank.wedatasphere.linkis.scheduler.executer.{ExecuteRequest, JobExecuteRequest} import scala.collection.JavaConversions -/** - * Created by enjoyyin on 2018/9/17. - */ + trait ExecuteRequestInterceptor { def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask } -object LockExecuteRequestInterceptor extends ExecuteRequestInterceptor { +object LabelExecuteRequestInterceptor extends ExecuteRequestInterceptor { override def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask = executeRequest match { - case lock: LockExecuteRequest => - val rq = if(requestTask == null) { + case labelExecuteRequest: LabelExecuteRequest => + val rq = if (requestTask == null) { val requestTask = new RequestTaskExecute requestTask.setCode(executeRequest.code) requestTask } else requestTask - rq.setLock(lock.lock) + rq.setLabels(labelExecuteRequest.labels) rq case _ => requestTask } @@ -87,15 +85,3 @@ object RuntimePropertiesExecuteRequestInterceptor extends ExecuteRequestIntercep case _ => requestTask } } - -//object RunTypeExecuteRequestInterceptor extends ExecuteRequestInterceptor{ -// private val runType:String = "runType" -// override def apply(requestTask: RequestTask, executeRequest: ExecuteRequest): RequestTask = { -// executeRequest match { -// case r:RunTypeExecuteRequest => -// requestTask.data(runType, r.runType) -// case _ => -// } -// requestTask -// } -//} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala similarity index 86% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala index dbd09ce10a..7dbe9c4351 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/JobLockExecuteRequest.scala @@ -16,15 +16,15 @@ package com.webank.wedatasphere.linkis.entrance.execute -/** - * Created by enjoyyin on 2018/9/15. - */ +import com.webank.wedatasphere.linkis.manager.label.entity.Label + + trait ReconnectExecuteRequest { val execId: String } -trait LockExecuteRequest { - val lock: String +trait LabelExecuteRequest { + val labels: java.util.List[Label[_]] } trait StorePathExecuteRequest { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala new file mode 100644 index 0000000000..a86227ddf9 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/execute/impl/EntranceExecutorManagerImpl.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.execute.impl + +import com.webank.wedatasphere.linkis.entrance.execute._ +import com.webank.wedatasphere.linkis.orchestrator.ecm.EngineConnManager +import com.webank.wedatasphere.linkis.scheduler.listener.ExecutorListener +import com.webank.wedatasphere.linkis.scheduler.queue.GroupFactory + +/** + * Created by enjoyyin on 2018/9/26. + */ +class EntranceExecutorManagerImpl(groupFactory: GroupFactory, + engineConnManager: EngineConnManager) extends EntranceExecutorManager(groupFactory, engineConnManager) { + + + override def getOrCreateInterceptors(): Array[ExecuteRequestInterceptor] = Array(JobExecuteRequestInterceptor, + LabelExecuteRequestInterceptor, ReconnectExecuteRequestInterceptor, StorePathExecuteRequestInterceptor, RuntimePropertiesExecuteRequestInterceptor) + + override def setExecutorListener(engineListener: ExecutorListener): Unit = {} +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala similarity index 88% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala index 0d88e5afdb..b966dc6d42 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/EntranceInterceptor.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,16 +16,16 @@ package com.webank.wedatasphere.linkis.entrance.interceptor import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * Created by enjoyyin on 2018/9/4. - */ + + trait EntranceInterceptor { /** * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. - * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * * @param task * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) * @return diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala similarity index 89% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala index 3b14958a6c..4a3101d983 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/RuntypeInterceptor.scala @@ -15,18 +15,18 @@ */ package com.webank.wedatasphere.linkis.entrance.interceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask + +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/12/5 * Description: this interceptor is used to complete code with run type for * further use in engine */ class RuntypeInterceptor extends EntranceInterceptor { - override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType.toLowerCase() match { case "python" | "py" | "pyspark" => val code = requestPersistTask.getExecutionCode requestPersistTask.setExecutionCode("%python\n" + code) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala similarity index 79% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala index 2a8469c5db..2f648b7a9a 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/CodeCheckException.scala @@ -18,11 +18,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/20 - * Description: - */ -case class CodeCheckException(errCode:Int, - errDesc:String) extends ErrorException(errCode, errDesc){ + +case class CodeCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala new file mode 100644 index 0000000000..47bb4a12df --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LabelCheckException.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.exception + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + + +case class LabelCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala index 708b2a8dcf..3d4b2e43b1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LimitCheckException.scala @@ -18,11 +18,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/20 - * Description: - */ -case class LimitCheckException(errCode:Int, - errDesc:String) extends ErrorException(errCode, errDesc) { + +case class LimitCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala index 7ab4a857b6..8db8a6a3e4 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/LogPathCreateException.scala @@ -18,12 +18,9 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/23 - * Description: - */ -case class LogPathCreateException(errCode:Int, - errDesc:String) - extends ErrorException(errCode,errDesc){ + +case class LogPathCreateException(errCode: Int, + errDesc: String) + extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala similarity index 80% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala index 273e2a78a9..f91767bf53 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/PythonCodeCheckException.scala @@ -18,12 +18,9 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/22 - * Description: - */ -case class PythonCodeCheckException(errCode:Int, - errDesc:String)extends ErrorException(errCode, errDesc) { + +case class PythonCodeCheckException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala index b371fdacbe..2b965e291f 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/exception/VarSubstitutionException.scala @@ -18,10 +18,7 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.exception import com.webank.wedatasphere.linkis.common.exception.ErrorException -/** - * created by enjoyyin on 2018/10/19 - * Description: - */ -case class VarSubstitutionException(errCode:Int, - errDesc:String) extends ErrorException(errCode,errDesc){ + +case class VarSubstitutionException(errCode: Int, + errDesc: String) extends ErrorException(errCode, errDesc) { } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala similarity index 92% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala index 26629f847a..943b1b298f 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CSEntranceInterceptor.scala @@ -18,13 +18,10 @@ import java.lang import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.cs.CSEntranceHelper import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * @author peacewong - * @date 2020/3/24 18:28 - */ + class CSEntranceInterceptor extends EntranceInterceptor with Logging { override def apply(task: Task, logAppender: lang.StringBuilder): Task = { diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala new file mode 100644 index 0000000000..a9e1911657 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CommentInterceptor.scala @@ -0,0 +1,104 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import java.lang +import java.util.regex.Pattern + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import org.slf4j.{Logger, LoggerFactory} + +import scala.util.matching.Regex + + +class CommentInterceptor extends EntranceInterceptor { + /** + * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 + * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * + * @param task + * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) + * @return + */ + override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType match { + case "sql" | "hql" => requestPersistTask.setExecutionCode(SQLCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "python" | "py" => requestPersistTask.setExecutionCode(PythonCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "scala" | "java" => requestPersistTask.setExecutionCode(ScalaCommentHelper.dealComment(requestPersistTask.getExecutionCode)) + case "sh" | "shell" => + case _ => + } + requestPersistTask + case _ => task + } +} + +trait CommentHelper { + val commentPattern: Regex + + def dealComment(code: String): String +} + +object SQLCommentHelper extends CommentHelper { + override val commentPattern: Regex = """\s*--.+\s*""".r.unanchored + private val comment = "(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/|#.*?$|" + private val logger: Logger = LoggerFactory.getLogger(getClass) + + override def dealComment(code: String): String = { + try { + val p = Pattern.compile(comment) + val sql = p.matcher(code).replaceAll("$1") + sql + } catch { + case e: Exception => logger.warn("sql comment failed") + code + case t: Throwable => logger.warn("sql comment failed") + code + } + } +} + +object PythonCommentHelper extends CommentHelper { + override val commentPattern: Regex = """^\s*#.+\s*""".r.unanchored + val pythonCommentPattern: String = "(?ms)([\"'](?:|[^'])*['\"])|#.*?$|/\\*.*?\\*/" + + override def dealComment(code: String): String = { + code + } +} + + +object ScalaCommentHelper extends CommentHelper { + override val commentPattern: Regex = """^\s*//.+\s*""".r.unanchored + private val scalaCommentPattern: String = "(?ms)([\"'](?:|[^'])*['\"])|//.*?$|/\\*.*?\\*/" + + override def dealComment(code: String): String = code +} + + +object CommentMain { + def main(args: Array[String]): Unit = { + val sqlCode = "select * from default.user;--你好;show tables" + val sqlCode1 = "select * from default.user--你好;show tables" + println(SQLCommentHelper.dealComment(sqlCode)) + } +} + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala similarity index 81% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala index 334960e7ac..3ac8e8057e 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/CustomVariableUtils.scala @@ -1,12 +1,9 @@ /* * Copyright 2019 WeBank - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * * http://www.apache.org/licenses/LICENSE-2.0 - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,7 +13,6 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl - import java.text.SimpleDateFormat import java.util import java.util.{Calendar, Date} @@ -24,7 +20,7 @@ import java.util.{Calendar, Date} import com.webank.wedatasphere.linkis.common.utils.Logging import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.exception.VarSubstitutionException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils import com.webank.wedatasphere.linkis.protocol.variable.{RequestQueryAppVariable, ResponseQueryVariable} @@ -37,9 +33,7 @@ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.util.control.Exception._ -/** - * Created by enjoyyin on 11/14/17. - */ + object CustomVariableUtils extends Logging { //hql sql jdbc to sql python to py val SQL_TYPE = "sql" @@ -49,36 +43,37 @@ object CustomVariableUtils extends Logging { val R_TYPE:String = "r" val RUN_DATE = "run_date" val TEAM:String = "team" - val SHELL_TYPE:String="shell" /** * date Format */ val dateFormat = new SimpleDateFormat("yyyyMMdd") val dateFormat_std = new SimpleDateFormat("yyyy-MM-dd") + /** * replace custom variable * 1. Get the user-defined variable from the code and replace it - * 2. If 1 is not done, then get the user-defined variable from args and replace it. - * 3. If 2 is not done, get the user-defined variable from the console and replace it. - + * * 2. If 1 is not done, then get the user-defined variable from args and replace it. + * * 3. If 2 is not done, get the user-defined variable from the console and replace it. + * * 1. 从代码中得到用户定义的变量,进行替换 * 2. 如果1没有做,那么从args中得到用户定义的变量,进行替换 * 3. 如果2没有做,从CS中得到用户定义的变量,进行替换 *3. 如果3没有做,从控制台中得到用户定义的变量,进行替换 + * * @param task : requestPersistTask * @return */ def replaceCustomVar(task: Task, runType: String): (Boolean, String) = { - val code:String = task.asInstanceOf[RequestPersistTask].getExecutionCode - val umUser:String = task.asInstanceOf[RequestPersistTask].getUmUser + val code: String = task.asInstanceOf[RequestPersistTask].getExecutionCode + val umUser: String = task.asInstanceOf[RequestPersistTask].getUmUser var codeType = SQL_TYPE runType match { - case "hql" | "sql" | "jdbc" | "hive" | "psql" | "essql" => codeType = SQL_TYPE - case "python" => codeType = PY_TYPE + case "hql" | "sql" | "jdbc" | "hive" => codeType = SQL_TYPE + case "python" | "py" => codeType = PY_TYPE case "java" => codeType = JAVA_TYPE - case "scala" | "esjson" => codeType = SCALA_TYPE - case "shell" | "sh" => codeType = SHELL_TYPE + case "scala" => codeType = SCALA_TYPE + case "sh" | "shell" => codeType = SQL_TYPE case _ => return (false, code) } @@ -101,7 +96,7 @@ object CustomVariableUtils extends Logging { } else { nameAndType(key) = StringType(value) } - } + } } } @@ -110,26 +105,26 @@ object CustomVariableUtils extends Logging { putNameAndType(nameAndValue) task match { - case requestPersistTask:RequestPersistTask => + case requestPersistTask: RequestPersistTask => /* Perform the second step to replace the parameters passed in args*/ /* 进行第二步,对args传进的参数进行替换*/ val variableMap = TaskUtils.getVariableMap(requestPersistTask.getParams.asInstanceOf[util.Map[String, Any]]) - .map{case (k, v) => k -> v.asInstanceOf[String]} + .map { case (k, v) => k -> v.asInstanceOf[String] } putNameAndType(variableMap) case _ => } - /* Go to the four step and take the user's parameters to the cloud-publicservice module.*/ - /*进行第四步,向cloud-publicservice模块去拿用户的参数*/ + /* Go to the four step and take the user's parameters to the linkis-ps-publicservice module.*/ + /*进行第四步,向linkis-ps-publicservice模块去拿用户的参数*/ val sender = Sender.getSender(EntranceConfiguration.CLOUD_CONSOLE_VARIABLE_SPRING_APPLICATION_NAME.getValue) task match { - case requestPersistTask:RequestPersistTask => - val umUser:String = requestPersistTask.getUmUser - val creator:String = requestPersistTask.getRequestApplicationName - val runType:String = requestPersistTask.getRunType - val requestQueryAppVariable:RequestQueryAppVariable = RequestQueryAppVariable(umUser, creator, runType) - val response:ResponseQueryVariable = sender.ask(requestQueryAppVariable).asInstanceOf[ResponseQueryVariable] + case requestPersistTask: RequestPersistTask => + val umUser: String = requestPersistTask.getUmUser + val creator: String = requestPersistTask.getRequestApplicationName + val runType: String = requestPersistTask.getRunType + val requestQueryAppVariable: RequestQueryAppVariable = RequestQueryAppVariable(umUser, creator, runType) + val response: ResponseQueryVariable = sender.ask(requestQueryAppVariable).asInstanceOf[ResponseQueryVariable] val keyAndValue = response.getKeyAndValue - val keyAndValueScala:mutable.Map[String, String] = keyAndValue + val keyAndValueScala: mutable.Map[String, String] = keyAndValue putNameAndType(keyAndValueScala) case _ => } @@ -163,59 +158,55 @@ object CustomVariableUtils extends Logging { */ def parserVar(code: String, nameAndType: mutable.Map[String, VariableType]): String = { - val codeReg = "\\$\\{\\s*[A-Za-z][A-Za-z0-9_]*\\s*[\\+\\-\\*/]?\\s*[A-Za-z0-9_\\.]*\\s*\\}".r - val calReg = "(\\s*[A-Za-z][A-Za-z0-9_]*\\s*)([\\+\\-\\*/]?)(\\s*[A-Za-z0-9_\\.]*\\s*)".r + val codeReg = "\\$\\{\\s*[A-Za-z][A-Za-z0-9_\\.]*\\s*[\\+\\-\\*/]?\\s*[A-Za-z0-9_\\.]*\\s*\\}".r + val calReg = "(\\s*[A-Za-z][A-Za-z0-9_\\.]*\\s*)([\\+\\-\\*/]?)(\\s*[A-Za-z0-9_\\.]*\\s*)".r + val parseCode = new StringBuilder + val codes = codeReg.split(code) val expressionCache = mutable.HashSet[String]() - var targetCode = code - var noChange = false - while (!noChange && codeReg.findFirstIn(targetCode).isDefined) { - var i = 0 - val parseCode = new StringBuilder - val codes = codeReg.split(targetCode) - codeReg.findAllIn(targetCode).foreach(str => { - calReg.findFirstMatchIn(str).foreach(ma => { - i = i + 1 - val name = ma.group(1) - val signal = ma.group(2) - val bValue = ma.group(3) - - if (name == null || name.trim.isEmpty) { - throw VarSubstitutionException(20041,s"[$str] replaced var is null") + + var i = 0 + + codeReg.findAllIn(code).foreach(str => { + calReg.findFirstMatchIn(str).foreach(ma => { + i = i + 1 + val name = ma.group(1) + val signal = ma.group(2) + val bValue = ma.group(3) + + if (name == null || name.trim.isEmpty) { + throw VarSubstitutionException(20041,s"[$str] replaced var is null") + } else { + var expression = name.trim + val varType = nameAndType.get(name.trim).orNull + if (varType == null) { + warn(s"Use undefined variables or use the set method: [$str](使用了未定义的变量或者使用了set方式:[$str])") + parseCode ++= codes(i - 1) ++ str } else { - var expression = name.trim - val varType = nameAndType.get(name.trim).orNull - if (varType == null) { - warn(s"Use undefined variables or use the set method: [$str](使用了未定义的变量或者使用了set方式:[$str])") - parseCode ++= codes(i - 1) ++ str - } else { - var res: String = varType.getValue - if (signal != null && !signal.trim.isEmpty) { - if (bValue == null || bValue.trim.isEmpty) { - throw VarSubstitutionException(20042, s"[$str] expression is not right, please check") - } else { - expression = expression + "_" + signal.trim + "_" + bValue.trim - res = varType.calculator(signal.trim, bValue.trim) - } + var res: String = varType.getValue + if (signal != null && !signal.trim.isEmpty) { + if (bValue == null || bValue.trim.isEmpty) { + throw VarSubstitutionException(20042, s"[$str] expression is not right, please check") + } else { + expression = expression + "_" + signal.trim + "_" + bValue.trim + res = varType.calculator(signal.trim, bValue.trim) } - if (!expressionCache.contains(expression)) { - info(s"Variable expression [$str] = $res(变量表达式[$str] = $res)") - //println(s"变量表达式[$str] = $res") - expressionCache += expression - } - //println(s"变量表达式序号:$i\t[$str] = $res") - parseCode ++= codes(i - 1) ++ res } + if (!expressionCache.contains(expression)) { + info(s"Variable expression [$str] = $res(变量表达式[$str] = $res)") + //println(s"变量表达式[$str] = $res") + expressionCache += expression + } + //println(s"变量表达式序号:$i\t[$str] = $res") + parseCode ++= codes(i - 1) ++ res } - }) + } }) - if (i == codes.length - 1) { - parseCode ++= codes(i) - } - val parsedCode = org.apache.commons.lang.StringUtils.strip(deleteUselessSemicolon(parseCode)) - if (targetCode.equals(parsedCode)) noChange = true - targetCode = parsedCode + }) + if (i == codes.length - 1) { + parseCode ++= codes(i) } - targetCode + val parsedCode = deleteUselessSemicolon(parseCode) + org.apache.commons.lang.StringUtils.strip(parsedCode) // Utils.trimBlank() } @@ -310,8 +301,6 @@ object CustomVariableUtils extends Logging { case SCALA_TYPE => varString = """\s*//@set\s*.+\s*""" errString = """\s*//@.+""" case JAVA_TYPE => varString = """\s*!!@set\s*.+\s*""" - case SHELL_TYPE => varString = """\s*#@set\s*.+\s*""" - errString = """\s*#@""" } val customRegex = varString.r.unanchored @@ -387,7 +376,7 @@ object CustomVariableUtils extends Logging { def main(args: Array[String]): Unit = { val code = "--@set a=1\n--@set b=2\nselect ${a +2},${a + 1},${a},${a },${b},${b}" val task = new RequestPersistTask - val args:java.util.Map[String, Object] = new util.HashMap[String, Object]() + val args: java.util.Map[String, Object] = new util.HashMap[String, Object]() args.put(RUN_DATE, "20181030") task.setExecutionCode(code) task.setParams(args) diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala similarity index 83% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala index f3a65260ee..890963680b 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/DBInfoCompleteInterceptor.scala @@ -19,11 +19,8 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * created by enjoyyin on 2018/10/19 - * Description: For database information completion(用于数据库信息补全) - */ -class DBInfoCompleteInterceptor extends EntranceInterceptor{ + +class DBInfoCompleteInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { //todo Database information completion(数据库信息补全) task diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala index e6c54a95f4..6b4eb7a131 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/Explain.scala @@ -22,17 +22,15 @@ import com.webank.wedatasphere.linkis.common.conf.CommonVars import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.common.log.LogUtils import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.exception.{PythonCodeCheckException, ScalaCodeCheckException} -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import org.apache.commons.lang.StringUtils import org.slf4j.{Logger, LoggerFactory} import scala.collection.mutable.ArrayBuffer -/** - * created by enjoyyin on 2018/10/19 - * Description: - */ + abstract class Explain extends Logging { /** * 用于检查code是否符合规范 @@ -50,18 +48,18 @@ object SparkExplain extends Explain { private val sy = Pattern.compile("sys\\.") private val scCancelAllJobs = Pattern.compile("sc\\.cancelAllJobs(\\s*)") private val runtime = Pattern.compile("Runtime\\.getRuntime") + private val LINE_BREAK = "\n" private val LOG:Logger = LoggerFactory.getLogger(getClass) override def authPass(code: String, error: StringBuilder): Boolean = { - + if (EntranceConfiguration.IS_QML.getValue) { + return true + } if (scStop.matcher(code).find()) { error.append("Authentication error: sc.stop() is not allowed in IDE.") false } else if (systemExit.matcher(code).find()) { error.append("Authentication error: System.exit(exitCode) is not allowed in IDE.") false - } else if (sy.matcher(code).find()) { - error.append("Authentication error: the package `sys` cannot be used in IDE.") - false } else if (scCancelAllJobs.matcher(code).find()) { error.append("Authentication error: sc.cancelAllJobs() is not allowed in IDE.") false @@ -82,6 +80,7 @@ object SQLExplain extends Explain { val SQL_APPEND_LIMIT:String = " limit " + SQL_DEFAULT_LIMIT.getValue val DROP_TABLE_SQL = "\\s*drop\\s+table\\s+\\w+\\s*" val CREATE_DATABASE_SQL = "\\s*create\\s+database\\s+\\w+\\s*" + private val IDE_ALLOW_NO_LIMIT_REGEX = "--set\\s*ide.engine.no.limit.allow\\s*=\\s*true".r.unanchored private val LINE_BREAK = "\n" private val COMMENT_FLAG = "--" val SET_OWN_USER = "set owner user" @@ -98,20 +97,31 @@ object SQLExplain extends Explain { /** * to deal with sql limit - * @param executionCode sql code + * + * @param executionCode sql code * @param requestPersistTask use to store inited logs */ - def dealSQLLimit(executionCode:String, requestPersistTask: RequestPersistTask, logAppender: java.lang.StringBuilder):Unit = { - val fixedCode:ArrayBuffer[String] = new ArrayBuffer[String]() - executionCode.split(";") foreach { singleCode => + def dealSQLLimit(executionCode: String, requestPersistTask: RequestPersistTask, logAppender: java.lang.StringBuilder): Unit = { + val fixedCode: ArrayBuffer[String] = new ArrayBuffer[String]() + val tempCode = SQLCommentHelper.dealComment(executionCode) + val isNoLimitAllowed = Utils.tryCatch { + IDE_ALLOW_NO_LIMIT_REGEX.findFirstIn(executionCode).isDefined + } { + case e: Exception => logger.warn("sql limit check error happens") + executionCode.contains(IDE_ALLOW_NO_LIMIT) + } + if (isNoLimitAllowed) logAppender.append(LogUtils.generateWarn("请注意,SQL全量导出模式打开\n")) + tempCode.split(";") foreach { singleCode => if (isSelectCmd(singleCode)){ val trimCode = singleCode.trim - if (isSelectCmdNoLimit(trimCode) && !executionCode.contains(IDE_ALLOW_NO_LIMIT)){ - logAppender.append(LogUtils.generateWarn(s"You submitted a sql $trimCode without limit, program will add limit 5000 to your sql") + "\n") - fixedCode += (trimCode + SQL_APPEND_LIMIT) - }else if (isSelectOverLimit(singleCode) && !executionCode.contains(IDE_ALLOW_NO_LIMIT)){ + if (isSelectCmdNoLimit(trimCode) && !isNoLimitAllowed){ + logAppender.append(LogUtils.generateWarn(s"You submitted a sql without limit, DSS will add limit 5000 to your sql") + "\n") + //将注释先干掉,然后再进行添加limit + val realCode = cleanComment(trimCode) + fixedCode += (realCode + SQL_APPEND_LIMIT) + }else if (isSelectOverLimit(singleCode) && !isNoLimitAllowed){ val trimCode = singleCode.trim - logAppender.append(LogUtils.generateWarn(s"You submitted a sql $trimCode with limit exceeding 5000, it is not allowed. Program will change your limit to 5000") + "\n") + logAppender.append(LogUtils.generateWarn(s"You submitted a sql with limit exceeding 5000, it is not allowed. DSS will change your limit to 5000") + "\n") fixedCode += repairSelectOverLimit(trimCode) }else{ fixedCode += singleCode.trim @@ -236,6 +246,9 @@ object PythonExplain extends Explain{ */ private val SC_STOP = """sc\.stop""".r.unanchored override def authPass(code: String, error: StringBuilder): Boolean = { + if (EntranceConfiguration.IS_QML.getValue) { + return true + } code.split(System.lineSeparator()) foreach {code => if (IMPORT_SYS_MOUDLE.findAllIn(code).nonEmpty || FROM_SYS_IMPORT.findAllIn(code).nonEmpty) throw PythonCodeCheckException(20070, "can not use sys module") @@ -257,6 +270,9 @@ object ScalaExplain extends Explain{ private val runtime = """Runtime.getRunTime""".r.unanchored private val LOG:Logger = LoggerFactory.getLogger(getClass) override def authPass(code: String, error: StringBuilder): Boolean = { + if (EntranceConfiguration.IS_QML.getValue) { + return true + } code match { case systemExit() => LOG.error("scala code can not use System.exit") throw ScalaCodeCheckException(20074, "scala code can not use System.exit") diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala new file mode 100644 index 0000000000..826940ecd1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LabelCheckInterceptor.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import java.lang + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.LabelCheckException +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.protocol.task.Task +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +class LabelCheckInterceptor extends EntranceInterceptor { + + /** + * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 + * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 + * + * @param task + * @param logAppender Used to cache the necessary reminder logs and pass them to the upper layer(用于缓存必要的提醒日志,传给上层) + * @return + */ + override def apply(task: Task, logAppender: lang.StringBuilder): Task = { + task match { + case requestPersistTask: RequestPersistTask => + val labels = requestPersistTask.getLabels + checkEngineTypeLabel(labels) + checkUserCreatorLabel(labels) + task + case _ => task + } + } + + private def checkEngineTypeLabel(labels: java.util.List[Label[_]]): Unit = { + val engineTypeLabelOption = labels.find(_.isInstanceOf[EngineTypeLabel]) + if (engineTypeLabelOption.isDefined) { + val engineLabel = engineTypeLabelOption.get.asInstanceOf[EngineTypeLabel] + if (StringUtils.isNotBlank(engineLabel.getEngineType)) { + return + } + } + throw LabelCheckException(50079, "engineTypeLabel must be need") + } + + + private def checkUserCreatorLabel(labels: java.util.List[Label[_]]): Unit = { + val userCreatorLabelOption = labels.find(_.isInstanceOf[UserCreatorLabel]) + if (userCreatorLabelOption.isDefined) { + val userCreator = userCreatorLabelOption.get.asInstanceOf[UserCreatorLabel] + if (StringUtils.isNotBlank(userCreator.getUser)) { + return + } + } + throw LabelCheckException(50079, "UserCreatorLabel must be need") + } + + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala new file mode 100644 index 0000000000..9b806e6a1b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/LogPathCreateInterceptor.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import com.webank.wedatasphere.linkis.common.exception.ErrorException +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.cache.GlobalConfigurationKeyValueCache +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.LogPathCreateException +import com.webank.wedatasphere.linkis.entrance.parser.ParserUtils +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task + +/** + * Description:Log path generation interceptor, used to set the path log of the task(日志路径生成拦截器, 用于设置task的路径日志) + */ +class LogPathCreateInterceptor extends EntranceInterceptor with Logging { + + @throws[ErrorException] + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { + task match { + case requestPersistTask: RequestPersistTask => Utils.tryThrow { + ParserUtils.generateLogPath(requestPersistTask, Utils.tryAndWarn(GlobalConfigurationKeyValueCache.getCacheMap(requestPersistTask))) + requestPersistTask + } { + case e: ErrorException => + val exception: LogPathCreateException = LogPathCreateException(20075, "Failed to get logPath(获取logPath失败),reason: " + e.getMessage) + exception.initCause(e) + exception + case t: Throwable => + val exception: LogPathCreateException = LogPathCreateException(20075, "Failed to get logPath(获取logPath失败), reason: " + t.getCause) + exception.initCause(t) + exception + } + case _ => task + } + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala similarity index 83% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala index 5c4c95b76d..ceabc45885 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/PythonCodeCheckInterceptor.scala @@ -19,22 +19,21 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.PythonCodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.exception.ExceptionUtils /** - * created by enjoyyin on 2018/10/22 * Description: Check for python code, prohibiting the use of sys, os, and creating processes(用于python代码的检查,禁止使用sys、os以及创建进程等行为) */ -class PythonCodeCheckInterceptor extends EntranceInterceptor{ - override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => +class PythonCodeCheckInterceptor extends EntranceInterceptor { + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => val error = new StringBuilder requestPersistTask.getRunType match { - case "python" | "pyspark" => - Utils.tryThrow(PythonExplain.authPass(requestPersistTask.getExecutionCode, error)){ - case PythonCodeCheckException(errCode,errDesc) => + case "python" | "pyspark" | "py" => + Utils.tryThrow(PythonExplain.authPass(requestPersistTask.getExecutionCode, error)) { + case PythonCodeCheckException(errCode, errDesc) => requestPersistTask.setErrCode(errCode) requestPersistTask.setErrDesc(errDesc) PythonCodeCheckException(errCode, errDesc) diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala new file mode 100644 index 0000000000..5bad733844 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLCodeCheckInterceptor.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.interceptor.impl + +import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor +import com.webank.wedatasphere.linkis.entrance.interceptor.exception.CodeCheckException +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task + +/** + * Description: + */ +class SQLCodeCheckInterceptor extends EntranceInterceptor { + + override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => + requestPersistTask.getEngineType.toLowerCase() match { + case "hql" | "sql" | "jdbc" | "hive" => + val sb: StringBuilder = new StringBuilder + val isAuth: Boolean = SQLExplain.authPass(requestPersistTask.getExecutionCode, sb) + if (!isAuth) { + throw CodeCheckException(20051, "sql code check failed, reason is " + sb.toString()) + } + case _ => + } + requestPersistTask + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala similarity index 77% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala index 05081e3d08..83943defb1 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SQLLimitEntranceInterceptor.scala @@ -17,22 +17,21 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/10/19 * Description: LimitEntranceInterceptor Interceptors are used to set certain restrictions(拦截器用于对某些限制的设定) */ class SQLLimitEntranceInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { - case requestPersistTask:RequestPersistTask => requestPersistTask.getEngineType.toLowerCase() match { - case "hql" | "sql" | "jdbc"|"hive" | "psql" | "essql" => val executionCode = requestPersistTask.getExecutionCode + case requestPersistTask: RequestPersistTask => requestPersistTask.getEngineType.toLowerCase() match { + case "hql" | "sql" | "jdbc" | "hive" => val executionCode = requestPersistTask.getExecutionCode SQLExplain.dealSQLLimit(executionCode, requestPersistTask, logAppender) case _ => } - requestPersistTask + requestPersistTask case _ => task } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala similarity index 79% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala index 557504f46e..cafa99aa63 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/ScalaCodeInterceptor.scala @@ -21,25 +21,22 @@ import java.lang import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.ScalaCodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task -/** - * created by enjoyyin on 2019/2/25 - * Description: - */ + class ScalaCodeInterceptor extends EntranceInterceptor { private val SCALA_TYPE = "scala" - override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match{ - case requestPersistTask:RequestPersistTask => val error = new StringBuilder + override def apply(task: Task, logAppender: lang.StringBuilder): Task = task match { + case requestPersistTask: RequestPersistTask => val error = new StringBuilder requestPersistTask.getRunType match { - case SCALA_TYPE => Utils.tryThrow(ScalaExplain.authPass(requestPersistTask.getExecutionCode, error)){ + case SCALA_TYPE => Utils.tryThrow(ScalaExplain.authPass(requestPersistTask.getExecutionCode, error)) { case ScalaCodeCheckException(errorCode, errDesc) => requestPersistTask.setErrCode(errorCode) requestPersistTask.setErrDesc(errDesc) ScalaCodeCheckException(errorCode, errDesc) - case t:Throwable => val exception = ScalaCodeCheckException(20074, "Scala code check failed(scala代码检查失败)") + case t: Throwable => val exception = ScalaCodeCheckException(20074, "Scala code check failed(scala代码检查失败)") exception.initCause(t) exception } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala index 3a6beb5391..1b3d13edb4 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/SparkCodeCheckInterceptor.scala @@ -18,25 +18,24 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.CodeCheckException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task /** - * created by enjoyyin on 2018/10/22 * Description: * Yòng yú jiǎnchá spark dàimǎ * 11/5000 * Used to check the spark code(用于检查spark代码) */ -class SparkCodeCheckInterceptor extends EntranceInterceptor{ +class SparkCodeCheckInterceptor extends EntranceInterceptor { override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { case requestPersistTask: RequestPersistTask => requestPersistTask.getRunType.toLowerCase() match { - case "scala" => val stringBuilder:StringBuilder = new StringBuilder() + case "scala" => val stringBuilder: StringBuilder = new StringBuilder() val isAuth = SparkExplain.authPass(requestPersistTask.getExecutionCode, stringBuilder) - if (!isAuth){ + if (!isAuth) { throw CodeCheckException(20050, "spark code check failed") } case _ => diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala index 1216592ac1..11d8ee3ace 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/StorePathEntranceInterceptor.scala @@ -16,20 +16,19 @@ package com.webank.wedatasphere.linkis.entrance.interceptor.impl +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.cache.GlobalConfigurationKeyValueCache import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.time.DateFormatUtils -/** - * Created by enjoyyin on 2018/11/3. - */ -class StorePathEntranceInterceptor extends EntranceInterceptor { + +class StorePathEntranceInterceptor extends EntranceInterceptor with Logging { /** * The apply function is to supplement the information of the incoming parameter task, making the content of this task more complete. - * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. + * * Additional information includes: database information supplement, custom variable substitution, code check, limit limit, etc. * apply函数是对传入参数task进行信息的补充,使得这个task的内容更加完整。 * 补充的信息包括: 数据库信息补充、自定义变量替换、代码检查、limit限制等 * @@ -38,9 +37,9 @@ class StorePathEntranceInterceptor extends EntranceInterceptor { */ override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = task match { case persistTask: RequestPersistTask => - val globalConfig = GlobalConfigurationKeyValueCache.getCacheMap(persistTask) + val globalConfig = Utils.tryAndWarn(GlobalConfigurationKeyValueCache.getCacheMap(persistTask)) var parentPath: String = null - if (globalConfig.containsKey(EntranceConfiguration.RESULT_SET_STORE_PATH.key)) + if (null != globalConfig && globalConfig.containsKey(EntranceConfiguration.RESULT_SET_STORE_PATH.key)) parentPath = EntranceConfiguration.RESULT_SET_STORE_PATH.getValue(globalConfig) else { parentPath = EntranceConfiguration.RESULT_SET_STORE_PATH.getValue diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala similarity index 84% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala index bc1646dac9..5cadab5c92 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/interceptor/impl/VarSubstitutionInterceptor.scala @@ -21,28 +21,27 @@ import com.webank.wedatasphere.linkis.common.log.LogUtils import com.webank.wedatasphere.linkis.common.utils.Utils import com.webank.wedatasphere.linkis.entrance.interceptor.EntranceInterceptor import com.webank.wedatasphere.linkis.entrance.interceptor.exception.VarSubstitutionException -import com.webank.wedatasphere.linkis.protocol.query.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask import com.webank.wedatasphere.linkis.protocol.task.Task import org.apache.commons.lang.exception.ExceptionUtils /** - * created by enjoyyin on 2018/10/19 * Description: For variable substitution(用于变量替换) */ -class VarSubstitutionInterceptor extends EntranceInterceptor{ +class VarSubstitutionInterceptor extends EntranceInterceptor { @throws[ErrorException] override def apply(task: Task, logAppender: java.lang.StringBuilder): Task = { task match { - case requestPersistTask:RequestPersistTask => + case requestPersistTask: RequestPersistTask => Utils.tryThrow { logAppender.append(LogUtils.generateInfo("Program is substituting variables for you") + "\n") val (result, code) = CustomVariableUtils.replaceCustomVar(requestPersistTask, requestPersistTask.getEngineType) if (result) requestPersistTask.setExecutionCode(code) - logAppender.append(LogUtils.generateInfo( "Variables substitution ended successfully") + "\n") + logAppender.append(LogUtils.generateInfo("Variables substitution ended successfully") + "\n") requestPersistTask - }{ - case e:VarSubstitutionException => + } { + case e: VarSubstitutionException => val exception = VarSubstitutionException(20050, "Variable replacement failed!(变量替换失败!)" + ExceptionUtils.getRootCauseMessage(e)) exception.initCause(e) exception diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/Cache.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala new file mode 100644 index 0000000000..6dca503a3b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogManager.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.{CacheNotReadyException, EntranceErrorCode} +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.scheduler.queue.Job +/** + * LogManager implementation, using a singleton class + * LogManager 的实现, 采用单例类进行 + */ +class CacheLogManager extends LogManager { + + override def getLogReader(execId: String): LogReader = { + var retLogReader:LogReader = null + this.entranceContext.getOrCreateScheduler().get(execId).foreach { + case entranceExecutionJob: EntranceExecutionJob => + retLogReader = entranceExecutionJob.getLogReader.getOrElse({ + this.synchronized { + val logWriter: CacheLogWriter = + entranceExecutionJob.getLogWriter.getOrElse(createLogWriter(entranceExecutionJob)).asInstanceOf[CacheLogWriter] + val sharedCache: Cache = logWriter.getCache. + getOrElse(throw CacheNotReadyException(EntranceErrorCode.CACHE_NOT_READY.getErrCode, EntranceErrorCode.CACHE_NOT_READY.getDesc)) + val logPath: String = entranceExecutionJob.getTask match { + case requestPersistTask: RequestPersistTask => requestPersistTask.getLogPath + case _ => null + } + new CacheLogReader(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, sharedCache, entranceExecutionJob.getUser) + } + }) + entranceExecutionJob.setLogReader(retLogReader) + case _ => null + } + retLogReader + } + + + override def createLogWriter(job: Job): LogWriter = { + + job match { + case entranceExecutionJob: EntranceExecutionJob => { + val cache: Cache = Cache(EntranceConfiguration.DEFAULT_CACHE_MAX.getValue) + val logPath: String = entranceExecutionJob.getTask.asInstanceOf[RequestPersistTask].getLogPath + val cacheLogWriter: CacheLogWriter = + new CacheLogWriter(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, cache, entranceExecutionJob.getUser) + entranceExecutionJob.setLogWriter(cacheLogWriter) + val webSocketCacheLogReader: WebSocketCacheLogReader = + new WebSocketCacheLogReader(logPath, EntranceConfiguration.DEFAULT_LOG_CHARSET.getValue, cache, entranceExecutionJob.getUser) + entranceExecutionJob.setWebSocketLogReader(webSocketCacheLogReader) + val webSocketLogWriter: WebSocketLogWriter = new WebSocketLogWriter(entranceExecutionJob, entranceContext.getOrCreateEventListenerBus) + entranceExecutionJob.setWebSocketLogWriter(webSocketLogWriter) + cacheLogWriter + } + case _ => null + } + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala similarity index 95% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala index 832520c7e6..9412f643bd 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogReader.scala @@ -14,12 +14,7 @@ * limitations under the License. */ -/** - * author: enjoyyin - * date: 2018/9/5 - * time: 11:14 - * Description: - */ + package com.webank.wedatasphere.linkis.entrance.log import java.io.{IOException, InputStream} @@ -46,7 +41,7 @@ class CacheLogReader(logPath:String , private def createInputStream: InputStream = { if (fileSystem == null) this synchronized { if (fileSystem == null){ - fileSystem = FSFactory.getFs(new FsPath(logPath)) + fileSystem = FSFactory.getFsByProxyUser(new FsPath(logPath), user) fileSystem.init(new util.HashMap[String, String]()) } } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/CacheLogWriter.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCode.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala new file mode 100644 index 0000000000..2e67ae94b6 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeListener.scala @@ -0,0 +1,66 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.entrance.EntranceParser +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import org.apache.commons.lang.StringUtils +import org.slf4j.{Logger, LoggerFactory} + + +trait ErrorCodeListener { + + def onErrorCodeCreated(job: Job, errorCode: String, detailErrorMsg: String) +} + +class PersistenceErrorCodeListener extends ErrorCodeListener{ + + private var persistenceManager: PersistenceManager = _ + private var entranceParser: EntranceParser = _ + + private val logger:Logger = LoggerFactory.getLogger(classOf[PersistenceErrorCodeListener]) + + def setPersistenceManager(persistenceManager: PersistenceManager): Unit = this.persistenceManager = persistenceManager + def getPersistenceManager = persistenceManager + def setEntranceParser(entranceParser: EntranceParser): Unit = this.entranceParser = entranceParser + def getEntranceParser = entranceParser + + /** + * onErrorCodeCreated: When a job is running, it terminates unexpectedly or generates an error, and the error code and error information need to be persisted to the database. + * The subsequent front end will get this error code when querying a specific task as a key error message. + * onErrorCodeCreated: 当一个job在运行的时候,意外终止或者产生错误,需要将错误码和错误信息持久化到数据库中 + * 后续前端在查询一个具体任务的时候,会得到这个错误码,作为关键错误信息 + * @param job Wrong job(出错的job) + * @param errorCode error code(错误码) + * @param detailErrorMsg wrong description(错误描述) + */ + override def onErrorCodeCreated(job: Job, errorCode: String, detailErrorMsg: String): Unit = { + val task:Task = this.entranceParser.parseToTask(job) + task match{ + case requestPersistTask:RequestPersistTask => if (StringUtils.isEmpty(requestPersistTask.getErrDesc) || "50032".equals(errorCode)){ + requestPersistTask.setErrCode(Integer.parseInt(errorCode)) + val realErrorMsg = if (detailErrorMsg.length <= 255) detailErrorMsg else detailErrorMsg.substring(0, 255) + requestPersistTask.setErrDesc(realErrorMsg) + persistenceManager.createPersistenceEngine().updateIfNeeded(task) + } + case _ => logger.warn("task {} is not a instance of RequestPersistTask", task.getExecId) + } + } +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala new file mode 100644 index 0000000000..7900d0f048 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/ErrorCodeManager.scala @@ -0,0 +1,234 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import java.io.{BufferedReader, InputStreamReader} +import java.util +import java.util.concurrent.TimeUnit + +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.storage.FSFactory +import javax.annotation.PostConstruct + +import scala.collection.mutable.ArrayBuffer + + +abstract class ErrorCodeManager { + + def getErrorCodes: Array[ErrorCode] + + def errorMatch(log: String): Option[(String, String)] = { + getErrorCodes.foreach(e => if(e.regex.findFirstIn(log).isDefined) { + val matched = e.regex.unapplySeq(log) + if(matched.nonEmpty) + return Some(e.code -> e.message.format(matched.get:_*)) + else Some(e.code -> e.message) + }) + None + } +} + +abstract class FileErrorCodeManager extends ErrorCodeManager with Logging { + override def getErrorCodes: Array[ErrorCode] = (new ArrayBuffer[ErrorCode]() ++= getCommonErrorCodes ++= getErrorCodesDynamic).toArray + + val errorCodeFileDir: String = { + val specifiedDir = EntranceConfiguration.ERROR_CODE_FILE_DIR.getValue + if (specifiedDir.endsWith("/")) specifiedDir else specifiedDir + "/" + } + + val errorCodeFile: String + private val user = EntranceConfiguration.ENTRANCE_USER.getValue + private val fileSystem = FSFactory.getFs(new FsPath(errorCodeFileDir)) + + @PostConstruct + def init(): Unit = { + Utils.tryAndWarn(fileSystem.init(new util.HashMap[String, String]())) + } + + val dynamicErrorCodes: ArrayBuffer[ErrorCode] = new ArrayBuffer[ErrorCode]() + + Utils.defaultScheduler.scheduleAtFixedRate(new Runnable { + override def run(): Unit = { + logger.info("start to get error code properties from {}", errorCodeFile) + dynamicErrorCodes.clear() + val bufferedReader = new BufferedReader(new InputStreamReader(fileSystem.read(new FsPath(errorCodeFile)), "utf-8")) + var line: String = null + while ( { + line = bufferedReader.readLine(); line != null + }) { + val arr = line.split(",") + if (arr.length < 3){ + logger.warn("errorcode line {} format is not correct", line) + }else{ + dynamicErrorCodes += ErrorCode(arr(0).r.unanchored, arr(1), arr(2)) + } + } + } + }, 0, 1,TimeUnit.HOURS) + + + def getErrorCodesDynamic:Array[ErrorCode] = dynamicErrorCodes.toArray + + def getCommonErrorCodes:Array[ErrorCode] = { + Array(ErrorCode("queue (\\S+) is not exists in YARN".r.unanchored, "10001", "会话创建失败,%s队列不存在,请检查队列设置是否正确"), + ErrorCode("User (\\S+) cannot submit applications to queue (\\S+)".r.unanchored, "10001", "会话创建失败,用户%s不能提交应用到队列:%s,请检查队列设置是否正确"), + ErrorCode("您本次向任务队列([a-zA-Z_0-9\\.]+)请求资源((.+)),任务队列最大可用资源(.+),任务队列剩余可用资源((.+))您已占用任务队列资源(.+)".r.unanchored, "20001", "Session创建失败,当前申请资源%s,队列可用资源%s,请检查资源配置是否合理"), + ErrorCode("远程服务器没有足够资源实例化[a-zA-Z]+ Session,通常是由于您设置【驱动内存】或【客户端内存】过高导致的,建议kill脚本,调低参数后重新提交!等待下次调度...".r.unanchored, "20002", "Session创建失败,服务器资源不足,请稍后再试"), + ErrorCode("request resources from ResourceManager has reached 560++ tries, give up and mark it as FAILED.".r.unanchored, "20003", "Session创建失败,队列资源不足,请稍后再试"), + ErrorCode("Caused by:\\s*java.io.FileNotFoundException".r.unanchored, "20003", "文件%s不存在"), + ErrorCode("OutOfMemoryError".r.unanchored, "20083", "Java进程内存溢出"), + ErrorCode("Permission denied:\\s*user=[a-zA-Z0-9_]+,\\s*access=[A-Z]+\\s*,\\s*inode=\"([a-zA-Z0-9/_\\.]+)\"".r.unanchored, "30001", "%s无权限访问,请申请开通数据表权限"), + ErrorCode("Database '([a-zA-Z_0-9]+)' not found".r.unanchored, "40001", "数据库%s不存在,请检查引用的数据库是否有误"), + ErrorCode("Database does not exist: ([a-zA-Z_0-9]+)".r.unanchored, "40001", "数据库%s不存在,请检查引用的数据库是否有误"), + ErrorCode("Table or view not found: ([`\\.a-zA-Z_0-9]+)".r.unanchored, "40002", "表%s不存在,请检查引用的表是否有误"), + ErrorCode("Table not found '([a-zA-Z_0-9]+)'".r.unanchored, "40002", "表%s不存在,请检查引用的表是否有误"), + ErrorCode("cannot resolve '`(.+)`' given input columns".r.unanchored, "40003", "字段%s不存在,请检查引用的字段是否有误"), + ErrorCode(" Invalid table alias or column reference '(.+)':".r.unanchored, "40003", "字段%s不存在,请检查引用的字段是否有误"), + ErrorCode("([a-zA-Z_0-9]+) is not a valid partition column in table ([`\\.a-zA-Z_0-9]+)".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表%s是否为分区表或分区字段有误"), + ErrorCode("Partition spec \\{(\\S+)\\} contains non-partition columns".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表是否为分区表或分区字段有误"), + ErrorCode("table is not partitioned but partition spec exists:\\{(.+)\\}".r.unanchored, "40004", "分区字段%s不存在,请检查引用的表是否为分区表或分区字段有误"), + ErrorCode("extraneous input '\\)'".r.unanchored, "50001", "括号不匹配,请检查代码中括号是否前后匹配"), + ErrorCode("missing EOF at '\\)'".r.unanchored, "50001", "括号不匹配,请检查代码中括号是否前后匹配"), + ErrorCode("expression '(\\S+)' is neither present in the group by".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("grouping expressions sequence is empty,\\s?and '(\\S+)' is not an aggregate function".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("Expression not in GROUP BY key '(\\S+)'".r.unanchored, "50002", "非聚合函数%s必须写在group by中,请检查代码的group by语法"), + ErrorCode("Undefined function: '(\\S+)'".r.unanchored, "50003", "未知函数%s,请检查代码中引用的函数是否有误"), + ErrorCode("Invalid function '(\\S+)'".r.unanchored, "50003", "未知函数%s,请检查代码中引用的函数是否有误"), + ErrorCode("Reference '(\\S+)' is ambiguous".r.unanchored, "50004", "字段%s存在名字冲突,请检查子查询内是否有同名字段"), + ErrorCode("Ambiguous column Reference '(\\S+)' in subquery".r.unanchored, "50004", "字段%s存在名字冲突,请检查子查询内是否有同名字段"), + ErrorCode("Column '(\\S+)' Found in more than One Tables/Subqueries".r.unanchored, "50005", "字段%s必须指定表或者子查询别名,请检查该字段来源"), + ErrorCode("Table or view '(\\S+)' already exists in database '(\\S+)'".r.unanchored, "50006", "表%s在数据库%s中已经存在,请删除相应表后重试"), + ErrorCode("Table (\\S+) already exists".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("Table already exists".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("""AnalysisException: (\S+) already exists""".r.unanchored, "50006", "表%s在数据库中已经存在,请删除相应表后重试"), + ErrorCode("java.io.FileNotFoundException: (\\S+) \\(No such file or directory\\)".r.unanchored,"64001","找不到导入文件地址:%s"), + ErrorCode("java.io.IOException: Permission denied(.+)at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet".r.unanchored,"64002","导出为excel时临时文件目录权限异常"), + ErrorCode("java.io.IOException: Mkdirs failed to create (\\S+) (.+)".r.unanchored,"64003","导出文件时无法创建目录:%s"), + ErrorCode("""ImportError: No module named (\S+)""".r.unanchored, "50008", "导入模块错误,系统没有%s模块,请联系运维人员安装"), + ErrorCode("""requires that the data to be inserted have the same number of columns as the target table""".r.unanchored, "50009", + "插入目标表字段数量不匹配,请检查代码!"), + ErrorCode("""missing \) at '(\S+)' near ''""".r.unanchored, "50010", "%s处括号不匹配,请检查代码!"), + ErrorCode("""due to data type mismatch: differing types in""".r.unanchored, + "50011", "数据类型不匹配,请检查代码!"), + ErrorCode("""Invalid column reference (\S+)""".r.unanchored, "50012", "字段%s引用有误,请检查字段是否存在!"), + ErrorCode("""Can't extract value from (\S+): need struct type but got string""".r.unanchored, "50013", "字段%s提取数据失败"), + ErrorCode("""mismatched input '(\S+)' expecting""".r.unanchored, "50014", "括号或者关键字不匹配,请检查代码!"), + ErrorCode("""GROUP BY position (\S+) is not in select list""".r.unanchored, "50015", "group by 位置2不在select列表中,请检查代码!"), + ErrorCode("""'NoneType' object""".r.unanchored, "50016", "代码中存在NoneType空类型变量,请检查代码"), + ErrorCode("""IndexError:List index out of range""".r.unanchored, "50017", "数组越界"), + ErrorCode("""Can't extract value from (\S+): need struct type but got string""".r.unanchored, "50013", "字段提取数据失败请检查字段类型"), + ErrorCode("""Cannot insert into target table because column number/types are different '(\S+)'""".r.unanchored, "50018", "插入数据未指定目标表字段%s,请检查代码!"), + ErrorCode("""Invalid table alias '(\S+)'""".r.unanchored, "50019", "表别名%s错误,请检查代码!"), + ErrorCode("""UDFArgumentException Argument expected""".r.unanchored, "50020", "UDF函数未指定参数,请检查代码!"), + ErrorCode("""aggregate functions are not allowed in GROUP BY""".r.unanchored, "50021", "聚合函数%s不能写在group by 中,请检查代码!"), + ErrorCode("SyntaxError".r.unanchored, "50007", "您的代码有语法错误,请您修改代码之后执行"), + ErrorCode("""Table not found""".r.unanchored, "40002", "表不存在,请检查引用的表是否有误"), + ErrorCode("""No matching method""".r.unanchored, "40003", "函数使用错误,请检查您使用的函数方式"), + ErrorCode("""is killed by user""".r.unanchored, "50032", "用户主动kill任务"), + ErrorCode("""name '(\S+)' is not defined""".r.unanchored, "60001", "python代码变量%s未定义"), + ErrorCode("""Undefined function:\s+'(\S+)'""".r.unanchored, "60002", "python udf %s 未定义"), + ErrorCode("FAILED: ParseException".r.unanchored, "50007", "您的sql代码可能有语法错误,请检查sql代码"), + ErrorCode("org.apache.spark.sql.catalyst.parser.ParseException".r.unanchored,"50007", "您的sql代码可能有语法错误,请检查sql代码"), + ErrorCode("""ParseException:""".r.unanchored, "60003", "脚本语法有误"), + ErrorCode("""Permission denied""".r.unanchored, "60010", "您可能没有相关权限"), + ErrorCode("""cannot concatenate '(\S+)' and '(\S+)'""".r.unanchored, "61027", "python执行不能将%s和%s两种类型进行连接"), + ErrorCode("""Py4JJavaError: An error occurred""".r.unanchored, "60020", "pyspark执行失败,可能是语法错误或stage失败"), + ErrorCode("""unexpected indent""".r.unanchored, "61028", "python代码缩进对齐有误"), + ErrorCode("""is exceeded""".r.unanchored, "60078", "个人库超过限制"), + ErrorCode("""unexpected indent""".r.unanchored, "69582", "python代码缩进有误"), + ErrorCode("""unexpected character after line""".r.unanchored, "69583", "python代码反斜杠后面必须换行"), + ErrorCode("""Invalid row number""".r.unanchored, "60091", "导出Excel表超过最大限制1048575"), + ErrorCode("""parquet.io.ParquetDecodingException""".r.unanchored, "60092", "python save as table未指定格式,默认用parquet保存,hive查询报错"), + ErrorCode("""errCode: 11011""".r.unanchored, "11011", "远程服务器内存资源不足"), + ErrorCode("""errCode: 11012""".r.unanchored, "11012", "远程服务器CPU资源不足"), + ErrorCode("""errCode: 11013""".r.unanchored, "11013", "远程服务器实例资源不足"), + ErrorCode("""errCode: 11014""".r.unanchored, "11014", "队列CPU资源不足"), + ErrorCode("""errCode: 11015""".r.unanchored, "11015", "队列内存资源不足"), + ErrorCode("""errCode: 11016""".r.unanchored, "11016", "队列实例数超过限制"), + ErrorCode("""errCode: 11017""".r.unanchored, "11017", "超出全局计算引擎实例限制"), + ErrorCode("""资源不足""".r.unanchored, "60035", "资源不足,启动引擎失败"), + ErrorCode("""获取Yarn队列信息异常""".r.unanchored, "60075", "获取Yarn队列信息异常,可能是您设置的yarn队列不存在") + ) + } +} + +/** + * errorCodeManager的单例对象,主要是用来生成固定的错误码 + */ +object FixedErrorCodeManager extends FileErrorCodeManager { + + override val errorCodeFile: String = "" + + override def getErrorCodes: Array[ErrorCode] = getCommonErrorCodes +} + + +object Main{ + def main(args: Array[String]): Unit = { + } +} + + +/** + * RefreshableErrorCodeManager corresponds to FixedErrorCodeManager, and refresheyeErrorCodeManager can update its own errorCodes through the query module. + * The purpose is to enable users to update the error code at any time by modifying the database. + * RefreshableErrorCodeManager 与 FixedErrorCodeManager 是对应的,refreshaleErrorCodeManager可以通过query模块进行更新自身的errorCodes + * 目的是为了能够让用户通过修改数据库随时更新错误码 + */ +// +//object RefreshableErrorCodeManager extends ErrorCodeManager{ +// private val sender:Sender = +// Sender.getSender(EntranceConfiguration.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME.getValue, 1000 * 60 * 60, 100) +// +// private val logger:Logger = LoggerFactory.getLogger(getClass) +// private var errorCodes:Array[ErrorCode] = _ +// +// class FetchErrorCodeThread extends Runnable{ +// override def run(): Unit = { +// val requestErrorCode = new RequestErrorCode +// val responseErrorCode = sender.send(requestErrorCode).asInstanceOf[ResponseErrorCode] +// Utils.tryAndWarnMsg{ +// val responseErrorCode = sender.send(requestErrorCode).asInstanceOf[ResponseErrorCode] +// val status = responseErrorCode.getStatus +// val message = responseErrorCode.getMessage +// if (status != 0){ +// logger.warn(s"Error encounters when retrieve errorCodes from query module, reason: $message") +// }else{ +// val errorCodeList = responseErrorCode.getResult +// val arrayBuffer = new ArrayBuffer[ErrorCode]() +// import scala.collection.JavaConversions._ +// errorCodeList foreach { errorCode => +// val regex = errorCode.getErrorRegex.r.unanchored +// val errorCode_ = errorCode.getErrorCode +// val errorDesc = errorCode.getErrorDesc +// arrayBuffer += ErrorCode(regex, errorCode_, errorDesc) +// } +// errorCodes = arrayBuffer.toArray +// } +// }("Query ErrorCodes failed. You may check the cause or just ignore it ") +// } +// } +// +// override def getErrorCodes: Array[ErrorCode] = errorCodes +//} + + + + + diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogFilter.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogHandler.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala new file mode 100644 index 0000000000..9db056eba1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogManager.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.log + +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.EntranceContext +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.scheduler.listener.LogListener +import com.webank.wedatasphere.linkis.scheduler.queue.Job + + +abstract class LogManager extends LogListener with Logging{ + + protected var errorCodeListener: Option[ErrorCodeListener] = None + protected var errorCodeManager: Option[ErrorCodeManager] = None + protected var entranceContext: EntranceContext = _ + + def setEntranceContext(entranceContext: EntranceContext): Unit = this.entranceContext = entranceContext + def setErrorCodeListener(errorCodeListener: ErrorCodeListener): Unit = this.errorCodeListener = Option(errorCodeListener) + def setErrorCodeManager(errorCodeManager: ErrorCodeManager): Unit = this.errorCodeManager = Option(errorCodeManager) + + def getLogReader(execId: String): LogReader + + def createLogWriter(job: Job): LogWriter + + override def onLogUpdate(job: Job, log: String): Unit = { + Utils.tryCatch{ + job match{ + case entranceExecutionJob: EntranceExecutionJob => + if (entranceExecutionJob.getLogWriter.isEmpty) entranceExecutionJob synchronized { + if (entranceExecutionJob.getLogWriter.isEmpty) createLogWriter(entranceExecutionJob) + } + entranceExecutionJob.getLogWriter.foreach(logWriter => logWriter.write(log)) + entranceExecutionJob.getWebSocketLogWriter.foreach(writer => writer.write(log)) + errorCodeManager.foreach(_.errorMatch(log).foreach { case (code, errorMsg) => + errorCodeListener.foreach(_.onErrorCodeCreated(job, code, errorMsg)) + }) + case _ => + } + }{ + case e: Exception => logger.warn(s"write log for job ${job.getId} failed", e) + case t: Throwable => logger.warn(s"write log for job ${job.getId} failed", t) + } + } +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala similarity index 82% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala index 6a85906d1c..2afa4733d7 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogReader.scala @@ -26,9 +26,7 @@ import org.apache.commons.lang.StringUtils import scala.util.matching.Regex -/** - * Created by enjoyyin on 2018/9/4. - */ + abstract class LogReader(charset: String) extends Closeable with Logging{ import LogReader._ @@ -70,6 +68,18 @@ abstract class LogReader(charset: String) extends Closeable with Logging{ if (!flag) concatLog(length, singleLog, warning, all) case INFO_HEADER1() | INFO_HEADER2() => val hiveLogSpecial:String = EntranceConfiguration.HIVE_SPECIAL_LOG_INCLUDE.getValue + val sparkLogSpecial:String = EntranceConfiguration.SPARK_SPECIAL_LOG_INCLUDE.getValue + val hiveCreateTableLog:String = EntranceConfiguration.HIVE_CREATE_TABLE_LOG.getValue + if (singleLog.contains(hiveLogSpecial) && singleLog.contains(hiveCreateTableLog)){ + val threadName = EntranceConfiguration.HIVE_THREAD_NAME.getValue + val printInfo = EntranceConfiguration.HIVE_PRINT_INFO_LOG.getValue + val start = singleLog.indexOf(threadName) + val end = singleLog.indexOf(printInfo) + printInfo.length + if(start > 0 && end > 0) { + val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) + concatLog(length, realLog, info, all) + } + } if (singleLog.contains(hiveLogSpecial) && singleLog.contains("map") && singleLog.contains("reduce")){ val start = singleLog.indexOf(EntranceConfiguration.HIVE_THREAD_NAME.getValue) val end = singleLog.indexOf(EntranceConfiguration.HIVE_STAGE_NAME.getValue) @@ -77,6 +87,15 @@ abstract class LogReader(charset: String) extends Closeable with Logging{ val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) concatLog(length, realLog, info, all) } + }else if (singleLog.contains(sparkLogSpecial)){ + val className = EntranceConfiguration.SPARK_PROGRESS_NAME.getValue + val endFlag = EntranceConfiguration.END_FLAG.getValue + val start = singleLog.indexOf(className) + val end = singleLog.indexOf(endFlag) + endFlag.length + if(start > 0 && end > 0) { + val realLog = singleLog.substring(0, start) + singleLog.substring(end, singleLog.length) + concatLog(length, realLog, info, all) + } }else{ val arr = EntranceConfiguration.LOG_EXCLUDE.getValue.split(",").map (word => word.trim) var flag = false diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala index 0d9e0cfece..6a56bdb858 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LogWriter.scala @@ -24,12 +24,10 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException import com.webank.wedatasphere.linkis.storage.FSFactory import com.webank.wedatasphere.linkis.storage.utils.FileSystemUtils -import org.apache.commons.io.IOUtils import org.apache.commons.lang.StringUtils +import org.apache.hadoop.hdfs.client.HdfsDataOutputStream + -/** - * Created by enjoyyin on 2018/9/4. - */ abstract class LogWriter(charset: String) extends Closeable with Flushable with Logging { private var firstWrite = true @@ -52,15 +50,25 @@ abstract class LogWriter(charset: String) extends Closeable with Flushable with - def flush(): Unit = Utils.tryQuietly(outputStream.flush(), t => { - warn("Error encounters when flush log,", t) - }) - + def flush(): Unit = Utils.tryAndWarnMsg[Unit] { + outputStream match { + case hdfs: HdfsDataOutputStream => + // todo check + hdfs.hsync() + case _ => + outputStream.flush() + } + }("Error encounters when flush log, ") def close(): Unit = { flush() - if (outputStream != null) IOUtils.closeQuietly(outputStream) - + if (outputStream != null) { + Utils.tryCatch{ + outputStream.close() + }{ + case t:Throwable => //ignore + } + } } } @@ -68,11 +76,11 @@ abstract class AbstractLogWriter(logPath: String, user: String, charset: String) extends LogWriter(charset) { if(StringUtils.isBlank(logPath)) throw new EntranceErrorException(20301, "logPath cannot be empty.") - protected val fileSystem = FSFactory.getFs(new FsPath(logPath)) + protected val fileSystem = FSFactory.getFsByProxyUser(new FsPath(logPath), user) fileSystem.init(new util.HashMap[String, String]()) protected val outputStream: OutputStream = { - FileSystemUtils.createNewFile(new FsPath(logPath), true) + FileSystemUtils.createNewFile(new FsPath(logPath), user, true) fileSystem.write(new FsPath(logPath), true) } diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/LoopArray.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketCacheLogReader.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/log/WebSocketLogWriter.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala new file mode 100644 index 0000000000..025da36543 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/parser/CommonEntranceParser.scala @@ -0,0 +1,219 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.parser + +import java.util +import java.util.Date + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.{EntranceErrorCode, EntranceIllegalParamException} +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.manager.label.builder.factory.{LabelBuilderFactory, LabelBuilderFactoryContext, StdLabelBuilderFactory} +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{EngineRunTypeLabel, EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.manager.label.utils.{EngineTypeLabelCreator, LabelUtils} +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.task.Task +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState +import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions.mapAsScalaMap +import scala.collection.JavaConverters._ + + +class CommonEntranceParser extends AbstractEntranceParser with Logging { + + private val labelBuilderFactory: LabelBuilderFactory = new StdLabelBuilderFactory + + /** + * parse params to be a task + * params json data from frontend + * + */ + override def parseToTask(params: util.Map[String, Any]): Task = { + if (!params.containsKey(TaskConstant.EXECUTION_CONTENT)) { + return parseToOldTask(params) + } + + val task = new RequestPersistTask + task.setCreatedTime(new Date(System.currentTimeMillis)) + task.setInstance(Sender.getThisInstance) + val umUser = params.get(TaskConstant.EXECUTE_USER).asInstanceOf[String] + val submitUser = params.get(TaskConstant.SUBMIT_USER).asInstanceOf[String] + task.setSubmitUser(submitUser) + if (StringUtils.isBlank(umUser)) task.setUmUser(submitUser) + task.setUmUser(umUser) + val executionContent = params.getOrDefault(TaskConstant.EXECUTION_CONTENT, null).asInstanceOf[util.Map[String, Object]] + val configMap = params.getOrDefault(TaskConstant.PARAMS, null).asInstanceOf[util.Map[String, Object]] + val labelMap = params.getOrDefault(TaskConstant.LABELS, null).asInstanceOf[util.Map[String, Object]] + val source = params.getOrDefault(TaskConstant.SOURCE, new util.HashMap[String, String]()).asInstanceOf[util.Map[String, String]] + val sourcePath = source.getOrDefault(TaskConstant.SCRIPTPATH, null) + if (null == sourcePath || null == labelMap) { + throw new EntranceIllegalParamException(EntranceErrorCode.PARAM_CANNOT_EMPTY.getErrCode, EntranceErrorCode.PARAM_CANNOT_EMPTY.getDesc + s", source : ${sourcePath}, labels : ${BDPJettyServerHelper.gson.toJson(labelMap)}") + } + + var code: String = null + var runType: String = null + if (executionContent.containsKey(TaskConstant.CODE)) { + code = executionContent.get(TaskConstant.CODE).asInstanceOf[String] + runType = executionContent.get(TaskConstant.RUNTYPE).asInstanceOf[String] + if (StringUtils.isEmpty(code)) + throw new EntranceIllegalParamException(20007, "param executionCode and scriptPath can not be empty at the same time") + } else { + // todo check + throw new EntranceIllegalParamException(20010, "Only code with runtype supported !") + } + val formatCode = params.get(TaskConstant.FORMATCODE).asInstanceOf[Boolean] + if (formatCode) code = format(code) + task.setExecutionCode(code) + var labels: util.Map[String, Label[_]] = buildLabel(labelMap) + val engineTypeLabel = labels.getOrElse(LabelKeyConstant.ENGINE_TYPE_KEY, null).asInstanceOf[EngineTypeLabel] + if (null == engineTypeLabel) { + val msg = s"Cannot create engineTypeLabel, labelMap : ${BDPJettyServerHelper.gson.toJson(labelMap)}" + error(msg) + throw new EntranceIllegalParamException(EntranceErrorCode.LABEL_PARAMS_INVALID.getErrCode, + EntranceErrorCode.LABEL_PARAMS_INVALID.getDesc + msg) + } else { + task.setEngineType(engineTypeLabel.getEngineType) + } + val engineRunTypeLabel = labels.getOrElse(LabelKeyConstant.ENGINE_RUN_TYPE_KEY, null).asInstanceOf[EngineRunTypeLabel] + if (null != engineRunTypeLabel) { + task.setRunType(engineRunTypeLabel.getRunType) + } else { + warn(s"RunType not set. EngineType : ${engineTypeLabel.getEngineType}") + } + var userCreatorLabel = labels.getOrElse(LabelKeyConstant.USER_CREATOR_TYPE_KEY, null).asInstanceOf[UserCreatorLabel] + + if (null == userCreatorLabel) { + userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + val creator = EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + userCreatorLabel.setUser(umUser) + userCreatorLabel.setCreator(creator) + labels.put(userCreatorLabel.getLabelKey, userCreatorLabel) + } + labels += (LabelKeyConstant.ENGINE_TYPE_KEY -> engineTypeLabel) + labels += (LabelKeyConstant.ENGINE_RUN_TYPE_KEY -> engineRunTypeLabel) + labels += (LabelKeyConstant.USER_CREATOR_TYPE_KEY -> userCreatorLabel) + task.setLabels(new util.ArrayList[Label[_]](labels.values())) + task.setSource(source) + task.setExecuteApplicationName(engineTypeLabel.getEngineType) + task.setRequestApplicationName(userCreatorLabel.getCreator) + task.setStatus(SchedulerEventState.Inited.toString) + task.setCreateService(EntranceConfiguration.DEFAULT_CREATE_SERVICE.getValue) + task.setParams(configMap) + task + } + + private def parseToOldTask(params: util.Map[String, Any]): Task = { + + val task = new RequestPersistTask + task.setCreatedTime(new Date(System.currentTimeMillis)) + task.setInstance(Sender.getThisInstance) + val umUser = params.get(TaskConstant.UMUSER).asInstanceOf[String] + val submitUser = params.get(TaskConstant.SUBMIT_USER).asInstanceOf[String] + task.setSubmitUser(submitUser) + if (umUser == null) throw new EntranceIllegalParamException(20005, "umUser can not be null") + task.setUmUser(umUser) + var executionCode = params.get(TaskConstant.EXECUTIONCODE).asInstanceOf[String] + val _params = params.get(TaskConstant.PARAMS) + _params match { + case mapParams: java.util.Map[String, Object] => task.setParams(mapParams) + case _ => + } + val formatCode = params.get(TaskConstant.FORMATCODE).asInstanceOf[Boolean] + var creator = params.get(TaskConstant.REQUESTAPPLICATIONNAME).asInstanceOf[String] + val source = params.getOrDefault(TaskConstant.SOURCE, new util.HashMap[String, String]()).asInstanceOf[util.Map[String, String]] + val executeApplicationName = params.get(TaskConstant.EXECUTEAPPLICATIONNAME).asInstanceOf[String] + if (StringUtils.isEmpty(creator)) creator = EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + //if (StringUtils.isEmpty(executeApplicationName)) throw new EntranceIllegalParamException(20006, "param executeApplicationName can not be empty or null") + /* When the execution type is IDE, executionCode and scriptPath cannot be empty at the same time*/ + /*当执行类型为IDE的时候,executionCode和scriptPath不能同时为空*/ + if (EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue.equals(creator) && StringUtils.isEmpty(source.get(TaskConstant.SCRIPTPATH)) && + StringUtils.isEmpty(executionCode)) + throw new EntranceIllegalParamException(20007, "param executionCode and scriptPath can not be empty at the same time") + var runType: String = null + if (StringUtils.isNotEmpty(executionCode)) { + runType = params.get(TaskConstant.RUNTYPE).asInstanceOf[String] + if (StringUtils.isEmpty(runType)) runType = EntranceConfiguration.DEFAULT_RUN_TYPE.getValue + //If formatCode is not empty, we need to format it(如果formatCode 不为空的话,我们需要将其进行格式化) + if (formatCode) executionCode = format(executionCode) + task.setExecutionCode(executionCode) + } + task.setSource(source) + task.setEngineType(runType) + //为了兼容代码,让engineType和runType都有同一个属性 + task.setRunType(runType) + task.setExecuteApplicationName(executeApplicationName) + task.setRequestApplicationName(creator) + task.setStatus(SchedulerEventState.Inited.toString) + task.setCreateService(EntranceConfiguration.DEFAULT_CREATE_SERVICE.getValue) + //封装Labels + task.setLabels(buildLabel(task)) + task + } + + private def buildLabel(task: RequestPersistTask): util.List[Label[_]] = { + val labelsList = new util.ArrayList[Label[_]]() + val labelBuilderFactory = LabelBuilderFactoryContext.getLabelBuilderFactory + if (StringUtils.isNotBlank(task.getUmUser) && StringUtils.isNotBlank(task.getRequestApplicationName)) { + val userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + userCreatorLabel.setCreator(task.getRequestApplicationName) + userCreatorLabel.setUser(task.getUmUser) + labelsList.add(userCreatorLabel) + } + + if (StringUtils.isNotBlank(task.getExecuteApplicationName)) { + val engineTypeLabel = EngineTypeLabelCreator.createEngineTypeLabel(task.getExecuteApplicationName) + labelsList.add(engineTypeLabel) + } + + if (StringUtils.isNotBlank(task.getRunType)) { + val runTypeLabel = labelBuilderFactory.createLabel(classOf[EngineRunTypeLabel]) + runTypeLabel.setRunType(task.getRunType) + labelsList.add(runTypeLabel) + } + + val labels = TaskUtils.getLabelsMap(task.getParams.asInstanceOf[util.Map[String, Any]]) + if (null != labels) { + LabelUtils.distinctLabel(labelBuilderFactory.getLabels(labels.asInstanceOf[util.Map[String, AnyRef]]), labelsList) + } else { + labelsList + } + } + + private def buildLabel(labelMap: util.Map[String, Object]): util.Map[String, Label[_]] = { + val labelKeyValueMap = new util.HashMap[String, Label[_]]() + if (null != labelMap && !labelMap.isEmpty) { + val list: util.List[Label[_]] = labelBuilderFactory.getLabels(labelMap.asInstanceOf[util.Map[String, AnyRef]]) + if (null != list) { + list.asScala.foreach { + label => labelKeyValueMap.put(label.getLabelKey, label) + } + } + } + labelKeyValueMap + } + + //todo to format code using proper way + private def format(code: String): String = code + +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala new file mode 100644 index 0000000000..d64747bda6 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/EntranceResultSetEngine.scala @@ -0,0 +1,97 @@ +/* + * Copyright 2019 WeBank + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.persistence + +import com.webank.wedatasphere.linkis.common.io.resultset.ResultSet +import com.webank.wedatasphere.linkis.common.io.{FsPath, MetaData, Record} +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} +import com.webank.wedatasphere.linkis.entrance.execute.StorePathExecuteRequest +import com.webank.wedatasphere.linkis.entrance.job.EntranceExecutionJob +import com.webank.wedatasphere.linkis.entrance.scheduler.cache.CacheOutputExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.executer.{AliasOutputExecuteResponse, OutputExecuteResponse} +import com.webank.wedatasphere.linkis.scheduler.queue.Job +import com.webank.wedatasphere.linkis.storage.resultset.{ResultSetFactory, ResultSetWriter} +import com.webank.wedatasphere.linkis.storage.utils.FileSystemUtils +import org.apache.commons.io.IOUtils + + +class EntranceResultSetEngine extends ResultSetEngine with Logging { + override def persistResultSet(job: Job, executeCompleted: OutputExecuteResponse): String = { + + + executeCompleted match { + case AliasOutputExecuteResponse(alias, output) => + if (ResultSetFactory.getInstance.isResultSetPath(output)) output + else { + val resultSet = ResultSetFactory.getInstance.getResultSetByContent(output) + writeResult(alias, output, job, resultSet) + } + case CacheOutputExecuteResponse(alias, output) => + if(ResultSetFactory.getInstance.isResultSet(output)){ + val resultSet = ResultSetFactory.getInstance.getResultSetByContent(output) + writeResult(alias, output, job, resultSet) + } else { + val resultSet = ResultSetFactory.getInstance.getResultSetByPath(FsPath.getFsPath(output)) + copyResult(alias, output, job, resultSet) + } + } + } + + private def copyResult(alias: String, output: String, job: Job, resultSet:ResultSet[_ <: MetaData, _ <: Record]) : String = { + var user:String="hadoop" + val storePath = job match { + case j: EntranceExecutionJob => j.jobToExecuteRequest() match { + case s: StorePathExecuteRequest => { + user = j.getUser + s.storePath + } + case _ => null + } + case _ => null + } + if(storePath != null) { + val path = if(alias.contains("_")) resultSet.getResultSetPath(new FsPath(storePath), alias) else resultSet.getResultSetPath(new FsPath(storePath), "_" + alias) + FileSystemUtils.copyFile(path, FsPath.getFsPath(output), user) + path.getSchemaPath + } else null + } + + private def writeResult(alias: String, output: String, job: Job, resultSet:ResultSet[_ <: MetaData, _ <: Record]) = { + var user:String="hadoop" + val storePath = job match { + case j: EntranceExecutionJob => j.jobToExecuteRequest() match { + case s: StorePathExecuteRequest => { + user = j.getUser + s.storePath + } + case _ => null + } + case _ => null + } + if(storePath != null) { + //TODO Remove _ stitching(去掉_拼接) + val path = if(alias.contains("_")) resultSet.getResultSetPath(new FsPath(storePath), alias) else resultSet.getResultSetPath(new FsPath(storePath), "_" + alias) + + FileSystemUtils.createNewFile(path, user,true) + val writer = ResultSetWriter.getResultSetWriter(resultSet, 0, path, user) + Utils.tryFinally { + writer.addMetaDataAndRecordString(output) + writer.flush() + }{ + IOUtils.closeQuietly(writer) + } + path.getSchemaPath + } else null + } +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/HaPersistenceTask.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/JobCompletedListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceEngine.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/PersistenceManager.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetEngine.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/persistence/ResultSetListener.scala diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala similarity index 90% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala index 620af1c46a..6c1aa10e72 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/restful/EntranceRestfulRemote.scala @@ -23,15 +23,16 @@ import javax.ws.rs.QueryParam import javax.ws.rs.core.{Context, Response} import org.springframework.web.bind.annotation.{PathVariable, RequestBody, RequestMapping, RequestMethod} -/** - * Created by enjoyyin on 2018/9/3. - */ + trait EntranceRestfulRemote { @RequestMapping(value = Array("/entrance/execute"), method = Array(RequestMethod.POST)) def execute(@Context req: HttpServletRequest, @RequestBody json: util.Map[String, Any]): Response -// @RequestMapping(value = Array("/api/entrance/{id}"), method = Array(RequestMethod.GET)) + @RequestMapping(value = Array("/entrance/submit"), method = Array(RequestMethod.POST)) + def submit(@Context req: HttpServletRequest, @RequestBody json: util.Map[String, Any]): Response + + // @RequestMapping(value = Array("/api/entrance/{id}"), method = Array(RequestMethod.GET)) // def get(@PathVariable("id") id: String): Response @RequestMapping(value = Array("/entrance/{id}/status"), method = Array(RequestMethod.GET)) diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala new file mode 100644 index 0000000000..1300086e1b --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceGroupFactory.scala @@ -0,0 +1,152 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler + +import java.util + +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration +import com.webank.wedatasphere.linkis.entrance.exception.EntranceErrorException +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.entrance.persistence.HaPersistenceTask +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.governance.common.protocol.conf.{RequestQueryEngineConfig, ResponseQueryConfig} +import com.webank.wedatasphere.linkis.manager.label.builder.factory.LabelBuilderFactoryContext +import com.webank.wedatasphere.linkis.manager.label.entity.Label +import com.webank.wedatasphere.linkis.manager.label.entity.engine.{ConcurrentEngineConnLabel, EngineTypeLabel, UserCreatorLabel} +import com.webank.wedatasphere.linkis.manager.label.utils.EngineTypeLabelCreator +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.rpc.Sender +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelGroup +import com.webank.wedatasphere.linkis.scheduler.queue.{Group, GroupFactory, SchedulerEvent} +import com.webank.wedatasphere.linkis.server.JMap +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + + +class EntranceGroupFactory extends GroupFactory with Logging { + + private val groupNameToGroups = new JMap[String, Group] + private val labelBuilderFactory = LabelBuilderFactoryContext.getLabelBuilderFactory + + override def getOrCreateGroup(groupName: String): Group = { + if (!groupNameToGroups.containsKey(groupName)) synchronized { + val initCapacity = 100 + val maxCapacity = 100 + var maxRunningJobs = EntranceConfiguration.WDS_LINKIS_INSTANCE.getValue + val maxAskExecutorTimes = EntranceConfiguration.MAX_ASK_EXECUTOR_TIME.getValue.toLong + if (groupName.startsWith(EntranceGroupFactory.CONCURRENT)) { + if (null == groupNameToGroups.get(groupName)) synchronized { + if (null == groupNameToGroups.get(groupName)) { + val group = new ParallelGroup(groupName, 100, EntranceConfiguration.CONCURRENT_FACTORY_MAX_CAPACITY.getValue) + group.setMaxRunningJobs(EntranceConfiguration.CONCURRENT_MAX_RUNNING_JOBS.getValue) + group.setMaxAskExecutorTimes(EntranceConfiguration.CONCURRENT_EXECUTOR_TIME.getValue) + groupNameToGroups.put(groupName, group) + return group + } + } + } + val groupNameSplits = groupName.split("_") + if (groupNameSplits.length < 3) { + logger.warn(s"name style of group: $groupName is not correct, we will set default value for the group") + } else { + val sender: Sender = Sender.getSender(EntranceConfiguration.CLOUD_CONSOLE_CONFIGURATION_SPRING_APPLICATION_NAME.getValue) + val creator = groupNameSplits(0) + val username = groupNameSplits(1) + val engineType = groupNameSplits(2) + + logger.info(s"Getting parameters for $groupName(正在为 $groupName 获取参数) username: $username, creator:$creator, engineType: $engineType") + val userCreatorLabel = labelBuilderFactory.createLabel(classOf[UserCreatorLabel]) + userCreatorLabel.setUser(username) + userCreatorLabel.setCreator(creator) + val engineTypeLabel = EngineTypeLabelCreator.createEngineTypeLabel(engineType) + try { + val keyAndValue = sender.ask(RequestQueryEngineConfig(userCreatorLabel, engineTypeLabel)).asInstanceOf[ResponseQueryConfig].getKeyAndValue + + maxRunningJobs = Integer.parseInt(keyAndValue.get(EntranceConfiguration.WDS_LINKIS_INSTANCE.key)) + } catch { + case t: Throwable => logger.warn("Get maxRunningJobs from configuration server failed! Next use the default value to continue.") + } + } + logger.info("groupName: {} => maxRunningJobs is {}", groupName, maxRunningJobs) + val group = new ParallelGroup(groupName, initCapacity, maxCapacity) + group.setMaxRunningJobs(maxRunningJobs) + group.setMaxAskExecutorTimes(maxAskExecutorTimes) + if (!groupNameToGroups.containsKey(groupName)) groupNameToGroups.put(groupName, group) + } + groupNameToGroups.get(groupName) + } + + + override def getGroupNameByEvent(event: SchedulerEvent): String = event match { + case job: EntranceJob => + job.getTask match { + case HaPersistenceTask(task) => + "HA" + case requestPersistTask: RequestPersistTask => { + val labels = requestPersistTask.getLabels + EntranceGroupFactory.getGroupNameByLabels(labels, job.getParams) + } + case _ => EntranceGroupFactory.getGroupName(job.getCreator, job.getUser, job.getParams) + } + } +} + +object EntranceGroupFactory { + + val CACHE = "_Cache" + + val CONCURRENT = "Concurrent_" + + def getGroupName(creator: String, user: String, params: util.Map[String, Any] = new util.HashMap[String, Any]): String = { + val runtime = TaskUtils.getRuntimeMap(params) + val cache = if (runtime.get(TaskConstant.READ_FROM_CACHE) != null && runtime.get(TaskConstant.READ_FROM_CACHE).asInstanceOf[Boolean]) CACHE else "" + if (StringUtils.isNotEmpty(creator)) creator + "_" + user + cache + else EntranceConfiguration.DEFAULT_REQUEST_APPLICATION_NAME.getValue + "_" + user + cache + } + + def getGroupNameByLabels(labels: java.util.List[Label[_]], params: util.Map[String, Any] = new util.HashMap[String, Any]): String = { + + val userCreator = labels.find(_.isInstanceOf[UserCreatorLabel]) + val engineType = labels.find(_.isInstanceOf[EngineTypeLabel]) + val concurrent = labels.find(_.isInstanceOf[ConcurrentEngineConnLabel]) + if (userCreator.isEmpty || engineType.isEmpty) { + throw new EntranceErrorException(20001, "userCreator label or engineType label cannot null") + } + + if (concurrent.isDefined) { + + val engineTypeLabel = engineType.get.asInstanceOf[EngineTypeLabel] + val groupName = CONCURRENT + engineTypeLabel.getEngineType + groupName + + } else { + val userCreatorLabel = userCreator.get.asInstanceOf[UserCreatorLabel] + + val engineTypeLabel = engineType.get.asInstanceOf[EngineTypeLabel] + + val runtime = TaskUtils.getRuntimeMap(params) + val cache = if (runtime.get(TaskConstant.READ_FROM_CACHE) != null && runtime.get(TaskConstant.READ_FROM_CACHE).asInstanceOf[Boolean]) CACHE else "" + val groupName = userCreatorLabel.getCreator + "_" + userCreatorLabel.getUser + "_" + engineTypeLabel.getEngineType + cache + groupName + } + } + + +} \ No newline at end of file diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala similarity index 100% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/EntranceSchedulerContext.scala diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala new file mode 100644 index 0000000000..6b53a773b1 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/CacheOutputExecuteResponse.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import com.webank.wedatasphere.linkis.scheduler.executer.OutputExecuteResponse + +case class CacheOutputExecuteResponse(alias: String, output: String) extends OutputExecuteResponse{ + override def getOutput: String = output +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala new file mode 100644 index 0000000000..8a8091161d --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumer.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import java.util.concurrent.ExecutorService + +import com.google.common.collect.Lists +import com.webank.wedatasphere.linkis.common.io.FsPath +import com.webank.wedatasphere.linkis.common.utils.Utils +import com.webank.wedatasphere.linkis.entrance.execute.EntranceJob +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.entrance.utils.JobHistoryHelper +import com.webank.wedatasphere.linkis.governance.common.entity.task.RequestPersistTask +import com.webank.wedatasphere.linkis.protocol.constants.TaskConstant +import com.webank.wedatasphere.linkis.protocol.utils.TaskUtils +import com.webank.wedatasphere.linkis.scheduler.SchedulerContext +import com.webank.wedatasphere.linkis.scheduler.exception.SchedulerErrorException +import com.webank.wedatasphere.linkis.scheduler.executer.SuccessExecuteResponse +import com.webank.wedatasphere.linkis.scheduler.queue.Group +import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer +import com.webank.wedatasphere.linkis.storage.FSFactory +import com.webank.wedatasphere.linkis.storage.fs.FileSystem +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + +class ReadCacheConsumer(schedulerContext: SchedulerContext, + executeService: ExecutorService, private var group: Group, persistenceManager: PersistenceManager) extends FIFOUserConsumer(schedulerContext, executeService, group) { + + override protected def loop(): Unit = { + val event = Option(getConsumeQueue.take()) + event.foreach{ + case job: EntranceJob => + job.getTask match { + case task: RequestPersistTask => + Utils.tryCatch { + val readCacheBefore = TaskUtils.getRuntimeMap(job.getParams).getOrDefault(TaskConstant.READ_CACHE_BEFORE, 300L).asInstanceOf[Long] + val cacheResult = JobHistoryHelper.getCache(task.getExecutionCode, task.getExecuteApplicationName, task.getUmUser, readCacheBefore) + if (cacheResult != null && StringUtils.isNotBlank(cacheResult.getResultLocation)) { + val resultSets = listResults(cacheResult.getResultLocation, job.getUser) + if (resultSets.size() > 0) { + for (resultSet: FsPath <- resultSets) { + val alias = FilenameUtils.getBaseName(resultSet.getPath) + val output = FsPath.getFsPath(cacheResult.getResultLocation, FilenameUtils.getName(resultSet.getPath)).getSchemaPath + persistenceManager.onResultSetCreated(job, new CacheOutputExecuteResponse(alias, output)) + } + persistenceManager.onResultSizeCreated(job, resultSets.size()) + } + val runtime = TaskUtils.getRuntimeMap(job.getParams) + runtime.put(TaskConstant.CACHE, false) + TaskUtils.addRuntimeMap(job.getParams, runtime) + job.transitionCompleted(new SuccessExecuteResponse(), "Result found in cache") + } else { + info("Cache not found, submit to normal consumer.") + submitToExecute(job) + } + }{ + case t: Throwable => + warn("Read cache failed, submit to normal consumer: ", t) + submitToExecute(job) + } + case _ => + } + case _ => + } + } + + private def listResults(resultLocation: String, user: String) = { + val dirPath = FsPath.getFsPath(resultLocation) + val fileSystem = FSFactory.getFsByProxyUser(dirPath, user).asInstanceOf[FileSystem] + Utils.tryFinally { + fileSystem.init(null) + if (fileSystem.exists(dirPath)) { + fileSystem.listPathWithError(dirPath).getFsPaths + } else { + Lists.newArrayList[FsPath](); + } + }(Utils.tryQuietly(fileSystem.close())) + } + + private def submitToExecute(job: EntranceJob) = { + val runtime = TaskUtils.getRuntimeMap(job.getParams) + runtime.put(TaskConstant.READ_FROM_CACHE, false) + TaskUtils.addRuntimeMap(job.getParams, runtime) + val groupName = schedulerContext.getOrCreateGroupFactory.getGroupNameByEvent(job) + val consumer = schedulerContext.getOrCreateConsumerManager.getOrCreateConsumer(groupName) + val index = consumer.getConsumeQueue.offer(job) + //index.map(getEventId(_, groupName)).foreach(job.setId) + if (index.isEmpty) throw new SchedulerErrorException(12001, "The submission job failed and the queue is full!(提交作业失败,队列已满!)") + } + + private def getEventId(index: Int, groupName: String): String = groupName + "_" + index +} diff --git a/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala new file mode 100644 index 0000000000..b4c39f1042 --- /dev/null +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/scheduler/cache/ReadCacheConsumerManager.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.entrance.scheduler.cache + +import com.webank.wedatasphere.linkis.entrance.persistence.PersistenceManager +import com.webank.wedatasphere.linkis.entrance.scheduler.EntranceGroupFactory +import com.webank.wedatasphere.linkis.scheduler.queue.fifoqueue.FIFOUserConsumer +import com.webank.wedatasphere.linkis.scheduler.queue.parallelqueue.ParallelConsumerManager + +class ReadCacheConsumerManager(maxParallelismUsers: Int, persistenceManager: PersistenceManager) extends ParallelConsumerManager(maxParallelismUsers){ + + override protected def createConsumer(groupName: String): FIFOUserConsumer = { + val group = getSchedulerContext.getOrCreateGroupFactory.getOrCreateGroup(groupName) + if(groupName.endsWith(EntranceGroupFactory.CACHE)){ + info("Create cache consumer with group: " + groupName) + new ReadCacheConsumer(getSchedulerContext, getOrCreateExecutorService, group, persistenceManager) + } else { + info("Create normal consumer with group: " + groupName) + new FIFOUserConsumer(getSchedulerContext, getOrCreateExecutorService, group) + } + } + +} diff --git a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala similarity index 78% rename from ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala rename to linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala index f330fcd4bf..17dcb8d145 100644 --- a/ujes/entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala +++ b/linkis-computation-governance/linkis-entrance/src/main/scala/com/webank/wedatasphere/linkis/entrance/utils/JobHistoryHelper.scala @@ -1,21 +1,33 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.entrance.utils import java.util -import com.google.gson.Gson import com.webank.wedatasphere.linkis.common.exception.ErrorException import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.entrance.conf.EntranceConfiguration import com.webank.wedatasphere.linkis.entrance.exception.JobHistoryFailedException +import com.webank.wedatasphere.linkis.governance.common.entity.task.{RequestPersistTask, RequestQueryTask, RequestUpdateTask, ResponsePersist} import com.webank.wedatasphere.linkis.protocol.query.cache.{CacheTaskResult, RequestReadCache} -import com.webank.wedatasphere.linkis.protocol.query.{RequestPersistTask, RequestQueryTask, RequestUpdateTask, ResponsePersist} import com.webank.wedatasphere.linkis.rpc.Sender import com.webank.wedatasphere.linkis.scheduler.queue.SchedulerEventState -/** - * created by cooperyang on 2020/1/2 - * Description: - */ + object JobHistoryHelper extends Logging{ private val sender = Sender.getSender(EntranceConfiguration.QUERY_PERSISTENCE_SPRING_APPLICATION_NAME.getValue) @@ -61,13 +73,7 @@ object JobHistoryHelper extends Logging{ }else{ val data = responsePersist.getData data.get(TASK_MAP_KEY) match { - case tasks:util.List[util.Map[String, Object]] => tasks.get(0) match { - case map:util.Map[String, Object] => val gson = new Gson() - val json = gson.toJson(map) - val requestPersistTask = gson.fromJson(json, classOf[RequestPersistTask]) - requestPersistTask - case _ => throw JobHistoryFailedException(s"query from jobhistory not a correct RequestPersistTask type taskId is $taskID") - } + case tasks: util.List[RequestPersistTask] => tasks.get(0) case _ => throw JobHistoryFailedException(s"query from jobhistory not a correct List type taskId is $taskID") } } diff --git a/linkis-computation-governance/linkis-jdbc-driver/pom.xml b/linkis-computation-governance/linkis-jdbc-driver/pom.xml new file mode 100644 index 0000000000..d9ce050d0e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/pom.xml @@ -0,0 +1,80 @@ + + + + + + 4.0.0 + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + + linkis-jdbc-driver + + + + com.webank.wedatasphere.linkis + linkis-computation-client + ${linkis.version} + + + junit + junit + RELEASE + test + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + maven-assembly-plugin + + + jar-with-dependencies + + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + **/*.yml + **/*.properties + **/*.sh + **/log4j2.xml + + + + + + + src/main/resources + + + ${project.artifactId}-${project.version} + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java new file mode 100644 index 0000000000..dcedfa50a1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisBaseResultSet.java @@ -0,0 +1,1088 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.math.MathContext; +import java.net.URL; +import java.sql.*; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +/** + * Data independed base class which implements the common part of + * all hive resultsets. + */ +public abstract class LinkisBaseResultSet implements ResultSet{ + protected SQLWarning warningChain = null; + protected boolean wasNull = false; + protected List row; + protected List columnNames; + protected List columnTypes; + + @Override + public boolean absolute(int row) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void afterLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void beforeFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void cancelRowUpdates() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void deleteRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int findColumn(String columnName) throws SQLException { + int columnIndex = columnNames.indexOf(columnName); + if (columnIndex==-1) { + throw new SQLException(); + } else { + return ++columnIndex; + } + } + + @Override + public boolean first() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Array getArray(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Array getArray(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getAsciiStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getAsciiStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + if (obj instanceof BigDecimal) { + return ((BigDecimal) obj); + } + throw new SQLException("Cannot convert column " + columnIndex + + " to BigDecimal. Found data of type: " + + obj.getClass()+", value: " + obj.toString()); + } + + @Override + public BigDecimal getBigDecimal(String columnName) throws SQLException { + return getBigDecimal(findColumn(columnName)); + } + + @Override + public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { + MathContext mc = new MathContext(scale); + return getBigDecimal(columnIndex).round(mc); + } + + @Override + public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { + return getBigDecimal(findColumn(columnName), scale); + } + + @Override + public InputStream getBinaryStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getBinaryStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Blob getBlob(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Blob getBlob(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean getBoolean(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (Boolean.class.isInstance(obj)) { + return (Boolean) obj; + } else if (obj == null) { + return false; + } else if (Number.class.isInstance(obj)) { + return ((Number) obj).intValue() != 0; + } else if (String.class.isInstance(obj)) { + return !((String) obj).equals("0"); + } + throw new SQLException("Cannot convert column " + columnIndex + " to boolean"); + } + + @Override + public boolean getBoolean(String columnName) throws SQLException { + return getBoolean(findColumn(columnName)); + } + + @Override + public byte getByte(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).byteValue(); + } else if (obj == null) { + return 0; + } + throw new SQLException("Cannot convert column " + columnIndex + " to byte"); + } + + @Override + public byte getByte(String columnName) throws SQLException { + return getByte(findColumn(columnName)); + } + + @Override + public byte[] getBytes(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public byte[] getBytes(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getCharacterStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getCharacterStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Clob getClob(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Clob getClob(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getConcurrency() throws SQLException { + return ResultSet.CONCUR_READ_ONLY; + } + + @Override + public String getCursorName() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Date getDate(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + + if (obj instanceof Date) { + return (Date) obj; + } + + try { + if (obj instanceof String) { + return Date.valueOf((String)obj); + } + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to date: " + e.toString()); + } + + throw new SQLException("Illegal conversion"); + } + + @Override + public Date getDate(String columnName) throws SQLException { + return getDate(findColumn(columnName)); + } + + @Override + public Date getDate(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Date getDate(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public double getDouble(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).doubleValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Double.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to double: " + e.toString()); + } + } + + @Override + public double getDouble(String columnName) throws SQLException { + return getDouble(findColumn(columnName)); + } + + @Override + public int getFetchDirection() throws SQLException { + return ResultSet.FETCH_FORWARD; + } + + @Override + public int getFetchSize() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public float getFloat(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).floatValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Float.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to float: " + e.toString()); + } + } + + @Override + public float getFloat(String columnName) throws SQLException { + return getFloat(findColumn(columnName)); + } + + @Override + public int getHoldability() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getInt(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).intValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Integer.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + " to integer" + e.toString()); + } + } + + @Override + public int getInt(String columnName) throws SQLException { + return getInt(findColumn(columnName)); + } + + @Override + public long getLong(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).longValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Long.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + " to long: " + e.toString()); + } + } + + @Override + public long getLong(String columnName) throws SQLException { + return getLong(findColumn(columnName)); + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException { + UJESSQLResultSetMetaData resultSetMetaData = new UJESSQLResultSetMetaData(); + if (null != columnNames) { + for (int i=0; i< columnNames.size(); i++ ) { + resultSetMetaData.setColumnNameProperties(i +1 , columnNames.get(i)); + resultSetMetaData.setDataTypeProperties(i + 1 , columnTypes.get(i)); + } + } + return resultSetMetaData; + } + + @Override + public Reader getNCharacterStream(int arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Reader getNCharacterStream(String arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public NClob getNClob(int arg0) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public NClob getNClob(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public String getNString(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public String getNString(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(int columnIndex) throws SQLException { + if (row == null) { + throw new SQLException("No row found."); + } + + if (columnIndex > row.size()) { + throw new SQLException("Invalid columnIndex: " + columnIndex); + } + + try { + wasNull = false; + if (row.get(columnIndex - 1) == null) { + wasNull = true; + } + + return row.get(columnIndex - 1); + } catch (Exception e) { + throw new SQLException(e.toString()); + } + } + + + @Override + public Object getObject(String columnName) throws SQLException { + return getObject(findColumn(columnName)); + } + + @Override + public T getObject(int columnIndex, Class type) throws SQLException { + // TODO method required by JDK 1.7 + throw new SQLException("Method not supported"); + } + + @Override + public T getObject(String columnLabel, Class type) throws SQLException { + // TODO method required by JDK 1.7 + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(int i, Map> map) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Object getObject(String colName, Map> map) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Ref getRef(int i) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Ref getRef(String colName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public RowId getRowId(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public RowId getRowId(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public SQLXML getSQLXML(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public SQLXML getSQLXML(String columnLabel) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public short getShort(int columnIndex) throws SQLException { + try { + Object obj = getObject(columnIndex); + if (Number.class.isInstance(obj)) { + return ((Number) obj).shortValue(); + } else if (obj == null) { + return 0; + } else if (String.class.isInstance(obj)) { + return Short.valueOf((String)obj); + } + throw new Exception("Illegal conversion"); + } catch (Exception e) { + throw new SQLException("Cannot convert column " + columnIndex + + " to short: " + e.toString()); + } + } + + @Override + public short getShort(String columnName) throws SQLException { + return getShort(findColumn(columnName)); + } + + @Override + public Statement getStatement() throws SQLException { + throw new SQLException("Method not supported"); + } + + /** + * @param columnIndex - the first column is 1, the second is 2, ... + * @see ResultSet#getString(int) + */ + @Override + public String getString(int columnIndex) throws SQLException { + // Column index starts from 1, not 0. + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + + return obj.toString(); + } + + @Override + public String getString(String columnName) throws SQLException { + return getString(findColumn(columnName)); + } + + @Override + public Time getTime(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Time getTime(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Timestamp getTimestamp(int columnIndex) throws SQLException { + Object obj = getObject(columnIndex); + if (obj == null) { + return null; + } + if (obj instanceof Timestamp) { + return (Timestamp) obj; + } + if (obj instanceof String) { + return Timestamp.valueOf((String)obj); + } + throw new SQLException("Illegal conversion"); + } + + @Override + public Timestamp getTimestamp(String columnName) throws SQLException { + return getTimestamp(findColumn(columnName)); + } + + @Override + public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public int getType() throws SQLException { + return ResultSet.TYPE_FORWARD_ONLY; + } + + @Override + public URL getURL(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public URL getURL(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getUnicodeStream(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public InputStream getUnicodeStream(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void insertRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isAfterLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isBeforeFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isClosed() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isFirst() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean isLast() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean last() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void moveToCurrentRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void moveToInsertRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean previous() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void refreshRow() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean relative(int rows) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowDeleted() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowInserted() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public boolean rowUpdated() throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void setFetchDirection(int direction) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void setFetchSize(int rows) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateArray(int columnIndex, Array x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateArray(String columnName, Array x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnName, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnName, InputStream x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, Blob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnName, Blob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(int columnIndex, InputStream inputStream, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBlob(String columnLabel, InputStream inputStream, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBoolean(int columnIndex, boolean x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBoolean(String columnName, boolean x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateByte(int columnIndex, byte x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateByte(String columnName, byte x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBytes(int columnIndex, byte[] x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateBytes(String columnName, byte[] x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnName, Reader reader, int length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(int columnIndex, Reader x, long length) + throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Clob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnName, Clob x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDate(int columnIndex, Date x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDate(String columnName, Date x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDouble(int columnIndex, double x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateDouble(String columnName, double x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateFloat(int columnIndex, float x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateFloat(String columnName, float x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateInt(int columnIndex, int x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateInt(String columnName, int x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateLong(int columnIndex, long x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateLong(String columnName, long x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNCharacterStream(String columnLabel, Reader reader, + long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, NClob clob) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, NClob clob) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, Reader reader) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNString(int columnIndex, String string) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNString(String columnLabel, String string) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNull(int columnIndex) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateNull(String columnName) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(int columnIndex, Object x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(String columnName, Object x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(int columnIndex, Object x, int scale) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateObject(String columnName, Object x, int scale) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRef(int columnIndex, Ref x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRef(String columnName, Ref x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRow() throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRowId(int columnIndex, RowId x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateRowId(String columnLabel, RowId x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateShort(int columnIndex, short x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateShort(String columnName, short x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateString(int columnIndex, String x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateString(String columnName, String x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTime(int columnIndex, Time x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTime(String columnName, Time x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public void updateTimestamp(String columnName, Timestamp x) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public SQLWarning getWarnings() throws SQLException { + return warningChain; + } + @Override + public void clearWarnings() throws SQLException { + warningChain = null; + } + @Override + public void close() throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public boolean wasNull() throws SQLException { + return wasNull; + } + @Override + public boolean isWrapperFor(Class> iface) throws SQLException { + throw new SQLException("Method not supported"); + } + @Override + public T unwrap(Class iface) throws SQLException { + throw new SQLException("Method not supported"); + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java new file mode 100644 index 0000000000..77505cb830 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisMetaDataResultSet.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public abstract class LinkisMetaDataResultSet extends LinkisBaseResultSet { + + protected final List data; + + @SuppressWarnings("unchecked") + public LinkisMetaDataResultSet(final List columnNames + , final List columnTypes + , final List data) throws SQLException { + if (data!=null) { + this.data = new ArrayList(data); + } else { + this.data = new ArrayList(); + } + if (columnNames!=null) { + this.columnNames = new ArrayList(columnNames); + } else { + this.columnNames = new ArrayList(); + } + if (columnTypes!=null) { + this.columnTypes = new ArrayList(columnTypes); + } else { + this.columnTypes = new ArrayList(); + } + } + + @Override + public void close() throws SQLException { + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java new file mode 100644 index 0000000000..a8c0466538 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/TableType.java @@ -0,0 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +public enum TableType { + TABLE, VIEW, TMP_TABLE +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java new file mode 100644 index 0000000000..02b4c9abfd --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriver.java @@ -0,0 +1,59 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class UJESSQLDriver extends UJESSQLDriverMain implements Driver { + static { + try { + DriverManager.registerDriver(new UJESSQLDriver()); + } catch (SQLException e) { + Logger logger = LoggerFactory.getLogger(UJESSQLDriver.class); + logger.info("Load driver failed",e); + } + } + + static String URL_PREFIX = "jdbc:linkis://"; + static String URL_REGEX = "jdbc:linkis://([^:]+)(:\\d+)?(/[^\\?]+)?(\\?\\S*)?"; + + static String HOST = "HOST"; + static String PORT = "PORT"; + static String DB_NAME = "DBNAME"; + static String PARAMS = "PARAMS"; + + static String USER = "user"; + static String PASSWORD = "password"; + + static String VERSION = "version"; + static int DEFAULT_VERSION = 1; + static String MAX_CONNECTION_SIZE = "maxConnectionSize"; + static String READ_TIMEOUT = "readTimeout"; + static String ENABLE_DISCOVERY = "enableDiscovery"; + static String ENABLE_LOADBALANCER = "enableLoadBalancer"; + static String CREATOR = "creator"; + + static String VARIABLE_HEADER = "var:"; + static String PARAM_SPLIT = "&"; + static String KV_SPLIT = "="; + +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java new file mode 100644 index 0000000000..758c59fd20 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLErrorCode.java @@ -0,0 +1,56 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +public enum UJESSQLErrorCode { + BAD_URL(80000,"bad url"), + NOSUPPORT_DRIVER(80001,"this method not supported in driver"), + NOSUPPORT_CONNECTION(80002, "this method not supported in connection"), + NOSUPPORT_STATEMENT(80003,"this method not supported in statement"), + CONNECTION_CLOSED(80004,"Connection is closed!"), + STATEMENT_CLOSED(80005,"statement is closed!"), + SCHEMA_EMPTY(80006,"schema is empty!"), + SCHEMA_FAILED(80007,"Get schema failed!"), + QUERY_TIMEOUT(80008,"query has been timeout!"), + FILETYPE_ERROR(80009,"file type error"), + METADATATYPE_ERROR(80010,"metadata type error"), + NOSUPPORT_METADATA(80011, "this method not supported in DatabaseMetaData"), + NOPERMITION(80012,"This user has no permission to read this file!"), + PARAMS_NOT_FOUND(80013, "Parameter not found"), + ERRORINFO_FROM_JOBINFO(80014,"get errorinfo from jobInfo"), + RESULTSET_ROWERROR(80015,"row message error"), + NOSUPPORT_RESULTSET(80016,"this method not supported in resultSet"), + RESULTSET_NULL(80017,"resultset is null,try to run next() firstly to init ResultSet and MetaData"), + PREPARESTATEMENT_TYPEERROR(80018,"parameter type error"), + METADATA_EMPTY(80019,"data is empty") + ; + private String msg; + private int code; + + UJESSQLErrorCode(int code,String msg) { + this.code = code; + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public int getCode() { + return code; + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java new file mode 100644 index 0000000000..4fe9b9becb --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/entity/JdbcColumn.java @@ -0,0 +1,188 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.entity; + +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLTypeParser; + +import java.sql.SQLException; +import java.sql.Types; + +/** + * Column metadata. + */ +public class JdbcColumn { + + private final String columnName; + private final String tableName; + private final String tableCatalog; + private final String type; + private final String comment; + private final int ordinalPos; + + public JdbcColumn(String columnName, String tableName, String tableCatalog + , String type, String comment, int ordinalPos) { + this.columnName = columnName; + this.tableName = tableName; + this.tableCatalog = tableCatalog; + this.type = type; + this.comment = comment; + this.ordinalPos = ordinalPos; + } + + public String getColumnName() { + return columnName; + } + + public String getTableName() { + return tableName; + } + + public String getTableCatalog() { + return tableCatalog; + } + + public String getType() { + return type; + } + + public Integer getSqlType() throws SQLException { + return UJESSQLTypeParser.parserFromName(type); + } + + static int columnDisplaySize(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + return columnPrecision(columnType); + case Types.VARCHAR: + return Integer.MAX_VALUE; // hive has no max limit for strings + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + return columnPrecision(columnType) + 1; // allow +/- + case Types.DATE: + return 10; + case Types.TIMESTAMP: + return columnPrecision(columnType); + // see http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Float.MAX_EXPONENT + case Types.FLOAT: + return 24; // e.g. -(17#).e-### + // see http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Double.MAX_EXPONENT + case Types.DOUBLE: + return 25; // e.g. -(17#).e-#### + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + static int columnPrecision(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + return 1; + case Types.VARCHAR: + case Types.CHAR: + return Integer.MAX_VALUE; // hive has no max limit for strings + case Types.TINYINT: + return 3; + case Types.SMALLINT: + return 5; + case Types.INTEGER: + return 10; + case Types.BIGINT: + return 19; + case Types.FLOAT: + return 7; + case Types.DOUBLE: + return 15; + case Types.DATE: + return 10; + case Types.TIMESTAMP: + return 29; + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + static int columnScale(int columnType) throws SQLException { + // according to hiveTypeToSqlType possible options are: + switch (columnType) { + case Types.BOOLEAN: + case Types.VARCHAR: + case Types.CHAR: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.DATE: + return 0; + case Types.FLOAT: + return 7; + case Types.DOUBLE: + return 15; + case Types.TIMESTAMP: + return 9; + case Types.DECIMAL: + return Integer.MAX_VALUE; + default: + throw new SQLException("Invalid column type: " + columnType); + } + } + + public Integer getColumnSize() throws SQLException { + int precision = columnPrecision(UJESSQLTypeParser.parserFromName(type)); + + return precision == 0 ? null : precision; + } + + public Integer getDecimalDigits() throws SQLException { + return columnScale(UJESSQLTypeParser.parserFromName(type)); + } + + public Integer getNumPrecRadix() { + if (type.equalsIgnoreCase("tinyint")) { + return 10; + } else if (type.equalsIgnoreCase("smallint")) { + return 10; + } else if (type.equalsIgnoreCase("int")) { + return 10; + } else if (type.equalsIgnoreCase("bigint")) { + return 10; + } else if (type.equalsIgnoreCase("decimal")) { + return 10; + } else if (type.equalsIgnoreCase("float")) { + return 2; + } else if (type.equalsIgnoreCase("double")) { + return 2; + } else { // anything else including boolean and string is null + return null; + } + } + + public String getComment() { + return comment; + } + + public int getOrdinalPos() { + return ordinalPos; + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java new file mode 100644 index 0000000000..7ddfdce5cc --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/java/com/webank/wedatasphere/linkis/ujes/jdbc/utils/JDBCUtils.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.utils; + +public class JDBCUtils { + + + private static final char SEARCH_STRING_ESCAPE = '\\'; + + public static String convertPattern(final String pattern) { + if (pattern==null) { + return ".*"; + } else { + StringBuilder result = new StringBuilder(pattern.length()); + + boolean escaped = false; + for (int i = 0, len = pattern.length(); i < len; i++) { + char c = pattern.charAt(i); + if (escaped) { + if (c != SEARCH_STRING_ESCAPE) { + escaped = false; + } + result.append(c); + } else { + if (c == SEARCH_STRING_ESCAPE) { + escaped = true; + continue; + } else if (c == '%') { + result.append(".*"); + } else if (c == '_') { + result.append('.'); + } else { + result.append(Character.toLowerCase(c)); + } + } + } + + return result.toString(); + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver b/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver new file mode 100644 index 0000000000..f8934f31c2 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver @@ -0,0 +1,17 @@ +# +# Copyright 2019 WeBank +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala new file mode 100644 index 0000000000..58cb335d8f --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/LinkisParameterMetaData.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.ParameterMetaData + +class LinkisParameterMetaData(parameterCount: Int) extends ParameterMetaData{ + + override def getParameterCount: Int = parameterCount + + override def isNullable(param: Int): Int = 1 + + override def isSigned(param: Int): Boolean = true + + override def getPrecision(param: Int): Int = Int.MaxValue + + override def getScale(param: Int): Int = 10 + + override def getParameterType(param: Int): Int = 12 + + override def getParameterTypeName(param: Int): String = "VARCHAR" + + override def getParameterClassName(param: Int): String = "java.lang.String" + + override def getParameterMode(param: Int): Int = 1 + + override def unwrap[T](iface: Class[T]): T = iface.cast(this) + + override def isWrapperFor(iface: Class[_]): Boolean = iface.isInstance(this) +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala similarity index 79% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala index a29fcd9f18..10dd9268f5 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESClientFactory.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.util @@ -6,12 +22,9 @@ import java.util.Properties import com.webank.wedatasphere.linkis.httpclient.dws.authentication.StaticAuthenticationStrategy import com.webank.wedatasphere.linkis.httpclient.dws.config.DWSClientConfigBuilder import com.webank.wedatasphere.linkis.ujes.client.UJESClient -import UJESSQLDriverMain._ +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriverMain._ import org.apache.commons.lang.StringUtils -/** - * Created by enjoyyin on 2019/5/27. - */ object UJESClientFactory { private val ujesClients = new util.HashMap[String, UJESClient] diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala similarity index 89% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala index 7360bfe35c..ae7703309c 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLConnection.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Blob, CallableStatement, Clob, Connection, DatabaseMetaData, NClob, PreparedStatement, ResultSet, SQLException, SQLWarning, SQLXML, Savepoint, Statement, Struct} @@ -12,9 +28,6 @@ import org.apache.commons.lang.StringUtils import scala.collection.{JavaConversions, mutable} -/** - * Created by enjoyyin on 2019/5/27. - */ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Properties) extends Connection with Logging { private[jdbc] var creator = "IDE" private[jdbc] val variableMap = { @@ -31,19 +44,32 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert } map.toMap } - private[jdbc] val dbName = props.getProperty(DB_NAME) + private[jdbc] val dbName = if (StringUtils.isNotBlank(props.getProperty(DB_NAME))) props.getProperty(DB_NAME) else "default" + private val runningSQLStatements = new util.LinkedList[Statement] + private var closed = false + + private var inited = false + private[jdbc] val user = props.getProperty(USER) + private[jdbc] val serverURL = props.getProperty("URL") + + private[jdbc] def throwWhenClosed[T](op: => T): T = if(isClosed) throw new UJESSQLException(UJESSQLErrorCode.CONNECTION_CLOSED) else op private def createStatementAndAdd[T<:Statement](op: => T): T = throwWhenClosed { + val statement = op runningSQLStatements.add(statement) + if (! inited) { + inited = true + Utils.tryAndWarn(statement.execute(s"USE $dbName")) + } statement } def getProps : Properties = props @@ -52,7 +78,11 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def createStatement(): Statement = createStatementAndAdd(new UJESSQLStatement(this)) - override def prepareStatement(sql: String): UJESSQLPreparedStatement = createStatementAndAdd(new UJESSQLPreparedStatement(this, sql)) + override def prepareStatement(sql: String): UJESSQLPreparedStatement = { + val statement = createStatementAndAdd(new UJESSQLPreparedStatement(this, sql)) + statement.clearQuery() + statement + } override def createStatement(resultSetType: Int, resultSetConcurrency: Int): Statement = { if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) @@ -92,11 +122,11 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def clearWarnings(): Unit = {} - override def setAutoCommit(autoCommit: Boolean): Unit = if(autoCommit) throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "setAutoCommit not supported") + override def setAutoCommit(autoCommit: Boolean): Unit = {} override def getAutoCommit: Boolean = true - override def commit(): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "commit not supported") + override def commit(): Unit = {} override def prepareCall(sql: String): CallableStatement = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "prepareCall not supported") @@ -152,7 +182,7 @@ class UJESSQLConnection(private[jdbc] val ujesClient: UJESClient, props: Propert override def createSQLXML(): SQLXML = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "createSQLXML not supported") - override def isValid(timeout: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "isValid not supported") + override def isValid(timeout: Int): Boolean = true override def setClientInfo(name: String, value: String): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_CONNECTION, "setClientInfo not supported") diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala new file mode 100644 index 0000000000..40407fda2e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaData.scala @@ -0,0 +1,561 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.{Connection, DatabaseMetaData, ResultSet, RowIdLifetime} +import java.util + +import com.webank.wedatasphere.linkis.ujes.client.request.{GetColumnsAction, GetDBSAction, GetTablesAction} +import com.webank.wedatasphere.linkis.ujes.jdbc.entity.JdbcColumn +import com.webank.wedatasphere.linkis.ujes.jdbc.utils.JDBCUtils +import org.apache.commons.lang.StringUtils + +import scala.collection.JavaConversions._ + +class UJESSQLDatabaseMetaData(ujesSQLConnection: UJESSQLConnection) extends DatabaseMetaData { + override def allProceduresAreCallable(): Boolean = false + + override def allTablesAreSelectable(): Boolean = false + + override def getURL: String = ujesSQLConnection.getProps.getProperty("URL") + + override def getUserName: String = + if (ujesSQLConnection.getProps.containsKey("user")) + ujesSQLConnection.getProps.getProperty("user") + else throw new UJESSQLException(UJESSQLErrorCode.PARAMS_NOT_FOUND, "Missing user information") + + override def isReadOnly: Boolean = false + + override def nullsAreSortedHigh(): Boolean = false + + override def nullsAreSortedLow(): Boolean = false + + override def nullsAreSortedAtStart(): Boolean = false + + override def nullsAreSortedAtEnd(): Boolean = false + + override def getDatabaseProductName: String = "linkis" + + override def getDatabaseProductVersion: String = "" + + override def getDriverName: String = "Linkis JDBC Driver" + + override def getDriverVersion: String = UJESSQLDriverMain.DEFAULT_VERSION.toString + + override def getDriverMajorVersion: Int = UJESSQLDriverMain.DEFAULT_VERSION + + override def getDriverMinorVersion: Int = UJESSQLDriverMain.DEFAULT_VERSION + + override def usesLocalFiles(): Boolean = false + + override def usesLocalFilePerTable(): Boolean = false + + override def supportsMixedCaseIdentifiers(): Boolean = false + + override def storesUpperCaseIdentifiers(): Boolean = false + + override def storesLowerCaseIdentifiers(): Boolean = false + + override def storesMixedCaseIdentifiers(): Boolean = false + + override def supportsMixedCaseQuotedIdentifiers(): Boolean = false + + override def storesUpperCaseQuotedIdentifiers(): Boolean = false + + override def storesLowerCaseQuotedIdentifiers(): Boolean = false + + override def storesMixedCaseQuotedIdentifiers(): Boolean = false + + override def getIdentifierQuoteString: String = " " + + override def getSQLKeywords: String = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSQLKeywords not supported") + + override def getNumericFunctions: String = "" + + override def getStringFunctions: String = "" + + override def getSystemFunctions: String = "" + + override def getTimeDateFunctions: String = "" + + override def getSearchStringEscape: String = "\\" + + override def getExtraNameCharacters: String = "" + + override def supportsAlterTableWithAddColumn(): Boolean = true + + override def supportsAlterTableWithDropColumn(): Boolean = false + + override def supportsColumnAliasing(): Boolean = true + + override def nullPlusNonNullIsNull(): Boolean = false + + override def supportsConvert(): Boolean = false + + override def supportsConvert(fromType: Int, toType: Int): Boolean = false + + override def supportsTableCorrelationNames(): Boolean = false + + override def supportsDifferentTableCorrelationNames(): Boolean = false + + override def supportsExpressionsInOrderBy(): Boolean = false + + override def supportsOrderByUnrelated(): Boolean = false + + override def supportsGroupBy(): Boolean = true + + override def supportsGroupByUnrelated(): Boolean = false + + override def supportsGroupByBeyondSelect(): Boolean = false + + override def supportsLikeEscapeClause(): Boolean = false + + override def supportsMultipleResultSets(): Boolean = false + + override def supportsMultipleTransactions(): Boolean = false + + override def supportsNonNullableColumns(): Boolean = false + + override def supportsMinimumSQLGrammar(): Boolean = false + + override def supportsCoreSQLGrammar(): Boolean = false + + override def supportsExtendedSQLGrammar(): Boolean = false + + override def supportsANSI92EntryLevelSQL(): Boolean = false + + override def supportsANSI92IntermediateSQL(): Boolean = false + + override def supportsANSI92FullSQL(): Boolean = false + + override def supportsIntegrityEnhancementFacility(): Boolean = false + + override def supportsOuterJoins(): Boolean = true + + override def supportsFullOuterJoins(): Boolean = true + + override def supportsLimitedOuterJoins(): Boolean = true + + override def getSchemaTerm: String = "database" + + override def getProcedureTerm: String = new String("UDF") + + override def getCatalogTerm: String = "instance" + + override def isCatalogAtStart: Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "isCatalogAtStart not supported") + + override def getCatalogSeparator: String = "." + + override def supportsSchemasInDataManipulation(): Boolean = true + + override def supportsSchemasInProcedureCalls(): Boolean = false + + override def supportsSchemasInTableDefinitions(): Boolean = true + + override def supportsSchemasInIndexDefinitions(): Boolean = false + + override def supportsSchemasInPrivilegeDefinitions(): Boolean = false + + override def supportsCatalogsInDataManipulation(): Boolean = false + + override def supportsCatalogsInProcedureCalls(): Boolean = false + + override def supportsCatalogsInTableDefinitions(): Boolean = false + + override def supportsCatalogsInIndexDefinitions(): Boolean = false + + override def supportsCatalogsInPrivilegeDefinitions(): Boolean = false + + override def supportsPositionedDelete(): Boolean = false + + override def supportsPositionedUpdate(): Boolean = false + + override def supportsSelectForUpdate(): Boolean = false + + override def supportsStoredProcedures(): Boolean = false + + override def supportsSubqueriesInComparisons(): Boolean = false + + override def supportsSubqueriesInExists(): Boolean = false + + override def supportsSubqueriesInIns(): Boolean = false + + override def supportsSubqueriesInQuantifieds(): Boolean = false + + override def supportsCorrelatedSubqueries(): Boolean = false + + override def supportsUnion(): Boolean = false + + override def supportsUnionAll(): Boolean = true + + override def supportsOpenCursorsAcrossCommit(): Boolean = false + + override def supportsOpenCursorsAcrossRollback(): Boolean = false + + override def supportsOpenStatementsAcrossCommit(): Boolean = false + + override def supportsOpenStatementsAcrossRollback(): Boolean = false + + override def getMaxBinaryLiteralLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxBinaryLiteralLength not supported") + + override def getMaxCharLiteralLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCharLiteralLength not supported") + + override def getMaxColumnNameLength: Int = 128 + + override def getMaxColumnsInGroupBy: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInGroupBy not supported") + + override def getMaxColumnsInIndex: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInIndex not supported") + + override def getMaxColumnsInOrderBy: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInOrderBy not supported") + + override def getMaxColumnsInSelect: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInSelect not supported") + + override def getMaxColumnsInTable: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxColumnsInTable not supported") + + override def getMaxConnections: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxConnections not supported") + + override def getMaxCursorNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCursorNameLength not supported") + + override def getMaxIndexLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxIndexLength not supported") + + override def getMaxSchemaNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxSchemaNameLength not supported") + + override def getMaxProcedureNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxProcedureNameLength not supported") + + override def getMaxCatalogNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxCatalogNameLength not supported") + + override def getMaxRowSize: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxRowSize not supported") + + override def doesMaxRowSizeIncludeBlobs(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "doesMaxRowSizeIncludeBlobs not supported") + + override def getMaxStatementLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxStatementLength not supported") + + override def getMaxStatements: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxStatements not supported") + + override def getMaxTableNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxTableNameLength not supported") + + override def getMaxTablesInSelect: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxTablesInSelect not supported") + + override def getMaxUserNameLength: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getMaxUserNameLength not supported") + + override def getDefaultTransactionIsolation: Int = 0 + + override def supportsTransactions(): Boolean = false + + override def supportsTransactionIsolationLevel(level: Int): Boolean = false + + override def supportsDataDefinitionAndDataManipulationTransactions(): Boolean = false + + override def supportsDataManipulationTransactionsOnly(): Boolean = false + + override def dataDefinitionCausesTransactionCommit(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "dataDefinitionCausesTransactionCommit not supported") + + override def dataDefinitionIgnoredInTransactions(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "dataDefinitionIgnoredInTransactions not supported") + + override def getProcedures(catalog: String, schemaPattern: String, procedureNamePattern: String): ResultSet = null + + override def getProcedureColumns(catalog: String, schemaPattern: String, procedureNamePattern: String, columnNamePattern: String): ResultSet = null + + override def getTables(catalog: String, schemaPattern: String, tableNamePattern: String, types: Array[String]): ResultSet = { + val resultCatalog = if (StringUtils.isNotBlank(catalog)) { + catalog + } else { + s"${getUserName}_ind" + } + val getTableAction = GetTablesAction.builder().setUser(getUserName).setDatabase(resultCatalog).build() + val result = ujesSQLConnection.ujesClient.getTables(getTableAction) + val tables = result.getTables + val resultTables = new util.ArrayList[util.Map[String, String]]() + tables.foreach { table => + val tableType = if (table.get("isView").asInstanceOf[Boolean]) TableType.VIEW.name() else TableType.TABLE.name() + val resultTable = new util.HashMap[String, String]() + resultTable.put("catalog", resultCatalog) + resultTable.put("tableName", table.get("tableName").asInstanceOf[String]) + resultTable.put("tableType", tableType) + if (null == types || types.contains(tableType)) { + resultTables.add(resultTable) + } + } + new LinkisMetaDataResultSet[util.Map[String, String]](util.Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS"), util.Arrays.asList("string", "string", "string", "string", "string"), resultTables) { + + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val resultTable = new util.ArrayList[Object](5) + val table = data.get(cnt) + resultTable.add(table.get("catalog")) + resultTable.add(null) + resultTable.add(table.get("tableName")) + resultTable.add(table.get("tableType")) + resultTable.add(table.get("")) + row = resultTable + cnt = cnt + 1 + true + } else { + false + } + } + } + + } + + override def getSchemas: ResultSet = { + new LinkisMetaDataResultSet(util.Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"), util.Arrays.asList("string", "string"), null) { + override def next(): Boolean = false + } + } + + override def getCatalogs: ResultSet = { + val getDBSAction = GetDBSAction.builder().setUser(getUserName).build() + val dBSResult = ujesSQLConnection.ujesClient.getDBS(getDBSAction) + val dbsName = dBSResult.getDBSName() + new LinkisMetaDataResultSet[String](util.Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"), util.Arrays.asList("string", "string"), dbsName) { + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val db = new util.ArrayList[Object](2) + db.add(null) + db.add(data.get(cnt)) + row = db + cnt = cnt + 1 + true + } else { + false + } + } + } + } + + override def getTableTypes: ResultSet = { + val typesList = TableType.values() + new LinkisMetaDataResultSet[TableType](util.Arrays.asList("TABLE_TYPE"), util.Arrays.asList("string"), typesList.toList) { + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val types = new util.ArrayList[Object](1) + types.add(data.get(cnt).name()) + row = types + cnt = cnt + 1 + true + } else { + false + } + } + } + } + + + override def getColumns(catalog: String, schemaPattern: String, tableNamePattern: String, columnNamePattern: String): ResultSet = { + val resultCatalog = if (StringUtils.isNotBlank(catalog)) { + catalog + } else { + s"${getUserName}_ind" + } + + val getColumnsAction = GetColumnsAction.builder().setUser(getUserName).setDatabase(resultCatalog).setTable(JDBCUtils.convertPattern(tableNamePattern)).build() + val result = ujesSQLConnection.ujesClient.getColumns(getColumnsAction) + val columns = result.getColumns + val resultColumns = new util.ArrayList[JdbcColumn]() + var ordinalPos = 1 + columns.foreach { column => + val jdbcColumn = new JdbcColumn(column.get("columnName").asInstanceOf[String], + tableNamePattern, + resultCatalog, + column.get("columnType").asInstanceOf[String], + column.get("columnComment").asInstanceOf[String], + ordinalPos + ) + resultColumns.add(jdbcColumn) + ordinalPos = ordinalPos + 1 + } + new LinkisMetaDataResultSet[JdbcColumn](util.Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE" + , "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS" + , "NUM_PREC_RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE" + , "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION" + , "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE" + , "SOURCE_DATA_TYPE"), + util.Arrays.asList("string", "string", "string", "string", "int", "string" + , "int", "int", "int", "int", "int", "string" + , "string", "int", "int", "int", "int" + , "string", "string", "string", "string", "int"), resultColumns) { + + private var cnt = 0 + + override def next(): Boolean = { + if (cnt < data.size()) { + val jdbcColumn = new util.ArrayList[Object](20) + val column = data.get(cnt) + jdbcColumn.add(column.getTableCatalog) // TABLE_CAT String => table catalog (may be null) + + jdbcColumn.add(null) // TABLE_SCHEM String => table schema (may be null) + + jdbcColumn.add(column.getTableName) // TABLE_NAME String => table name + + jdbcColumn.add(column.getColumnName) // COLUMN_NAME String => column name + + jdbcColumn.add(column.getSqlType) // DATA_TYPE short => SQL type from java.sql.Types + + jdbcColumn.add(column.getType) // TYPE_NAME String => Data source dependent type name. + + jdbcColumn.add(column.getColumnSize) // COLUMN_SIZE int => column size. + + jdbcColumn.add(null) // BUFFER_LENGTH is not used. + + jdbcColumn.add(column.getDecimalDigits) // DECIMAL_DIGITS int => number of fractional digits + + jdbcColumn.add(column.getNumPrecRadix) // NUM_PREC_RADIX int => typically either 10 or 2 + + jdbcColumn.add(DatabaseMetaData.columnNullable.asInstanceOf[Object]) // NULLABLE int => is NULL allowed? + + jdbcColumn.add(column.getComment) // REMARKS String => comment describing column (may be null) + + jdbcColumn.add(null) // COLUMN_DEF String => default value (may be null) + + jdbcColumn.add(null) // SQL_DATA_TYPE int => unused + + jdbcColumn.add(null) // SQL_DATETIME_SUB int => unused + + jdbcColumn.add(null) // CHAR_OCTET_LENGTH int + + jdbcColumn.add(column.getOrdinalPos.asInstanceOf[Object]) // ORDINAL_POSITION int + + jdbcColumn.add("YES") // IS_NULLABLE String + + jdbcColumn.add(null) // SCOPE_CATLOG String + + jdbcColumn.add(null) // SCOPE_SCHEMA String + + jdbcColumn.add(null) // SCOPE_TABLE String + + jdbcColumn.add(null) // SOURCE_DATA_TYPE short + + row = jdbcColumn + cnt = cnt + 1 + true + } else { + false + } + } + } + + } + + override def getColumnPrivileges(catalog: String, schema: String, table: String, columnNamePattern: String): ResultSet = null + + override def getTablePrivileges(catalog: String, schemaPattern: String, tableNamePattern: String): ResultSet = null + + override def getBestRowIdentifier(catalog: String, schema: String, table: String, scope: Int, nullable: Boolean): ResultSet = null + + override def getVersionColumns(catalog: String, schema: String, table: String): ResultSet = null + + override def getPrimaryKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getImportedKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getExportedKeys(catalog: String, schema: String, table: String): ResultSet = null + + override def getCrossReference(parentCatalog: String, parentSchema: String, parentTable: String, foreignCatalog: String, foreignSchema: String, foreignTable: String): ResultSet = null + + override def getTypeInfo: ResultSet = null + + override def getIndexInfo(catalog: String, schema: String, table: String, unique: Boolean, approximate: Boolean): ResultSet = null + + override def supportsResultSetType(`type`: Int): Boolean = true + + override def supportsResultSetConcurrency(`type`: Int, concurrency: Int): Boolean = false + + override def ownUpdatesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownUpdatesAreVisible not supported") + + override def ownDeletesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownDeletesAreVisible not supported") + + override def ownInsertsAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "ownInsertsAreVisible not supported") + + override def othersUpdatesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersUpdatesAreVisible not supported") + + override def othersDeletesAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersDeletesAreVisible not supported") + + override def othersInsertsAreVisible(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "othersInsertsAreVisible not supported") + + override def updatesAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "updatesAreDetected not supported") + + override def deletesAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "deletesAreDetected not supported") + + override def insertsAreDetected(`type`: Int): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "insertsAreDetected not supported") + + override def supportsBatchUpdates(): Boolean = false + + override def getUDTs(catalog: String, schemaPattern: String, typeNamePattern: String, types: Array[Int]): ResultSet = null + + override def getConnection: Connection = ujesSQLConnection + + override def supportsSavepoints(): Boolean = false + + override def supportsNamedParameters(): Boolean = false + + override def supportsMultipleOpenResults(): Boolean = false + + override def supportsGetGeneratedKeys(): Boolean = false + + override def getSuperTypes(catalog: String, schemaPattern: String, typeNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSuperTypes not supported") + + override def getSuperTables(catalog: String, schemaPattern: String, tableNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getSuperTables not supported") + + override def getAttributes(catalog: String, schemaPattern: String, typeNamePattern: String, attributeNamePattern: String): ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getAttributes not supported") + + override def supportsResultSetHoldability(holdability: Int): Boolean = false + + override def getResultSetHoldability: Int = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getResultSetHoldability not supported") + + override def getDatabaseMajorVersion: Int = 1 + + override def getDatabaseMinorVersion: Int = 1 + + override def getJDBCMajorVersion: Int = 3 + + override def getJDBCMinorVersion: Int = 0 + + override def getSQLStateType: Int = 2 + + override def locatorsUpdateCopy(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "locatorsUpdateCopy not supported") + + override def supportsStatementPooling(): Boolean = false + + override def getRowIdLifetime: RowIdLifetime = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getRowIdLifetime not supported") + + override def getSchemas(catalog: String, schemaPattern: String): ResultSet = null + + override def supportsStoredFunctionsUsingCallSyntax(): Boolean = false + + override def autoCommitFailureClosesAllResultSets(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "autoCommitFailureClosesAllResultSets not supported") + + override def getClientInfoProperties: ResultSet = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "getClientInfoProperties not supported") + + override def getFunctions(catalog: String, schemaPattern: String, functionNamePattern: String): ResultSet = null + + override def getFunctionColumns(catalog: String, schemaPattern: String, functionNamePattern: String, columnNamePattern: String): ResultSet = null + + override def getPseudoColumns(catalog: String, schemaPattern: String, tableNamePattern: String, columnNamePattern: String): ResultSet = null + + override def generatedKeyAlwaysReturned(): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "generatedKeyAlwaysReturned not supported") + + override def unwrap[T](iface: Class[T]): T = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "unwrap not supported") + + override def isWrapperFor(iface: Class[_]): Boolean = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA, "isWrapperFor not supported") +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala similarity index 85% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala index ddd04031c4..3fc3a1dc16 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDriverMain.scala @@ -1,21 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Connection, Driver, DriverManager, DriverPropertyInfo, SQLFeatureNotSupportedException} import java.util.Properties import java.util.logging.Logger -import UJESSQLDriverMain._ +import com.webank.wedatasphere.linkis.common.utils.Logging +import com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriverMain._ import org.apache.commons.lang.StringUtils import scala.collection.JavaConversions -/** - * Created by enjoyyin on 2019/5/27. - */ -class UJESSQLDriverMain extends Driver { - override def connect(url: String, info: Properties): Connection = if(acceptsURL(url)) { - val props = if(info != null) info else new Properties +class UJESSQLDriverMain extends Driver with Logging{ + + override def connect(url: String, properties: Properties): Connection = if(acceptsURL(url)) { + val props = if(properties != null) properties else new Properties props.putAll(parseURL(url)) + info(s"input url:$url, properties:$properties") val ujesClient = UJESClientFactory.getUJESClient(props) new UJESSQLConnection(ujesClient, props) } else throw new UJESSQLException(UJESSQLErrorCode.BAD_URL, "bad url: " + url) diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala new file mode 100644 index 0000000000..48675b7e7e --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLException.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import com.webank.wedatasphere.linkis.common.exception.ErrorException + +class UJESSQLException (errorCode: UJESSQLErrorCode) extends ErrorException(errorCode.getCode,errorCode.getMsg) { + def this(errorCode: UJESSQLErrorCode, msg: String) { + this(errorCode) + setErrCode(errorCode.getCode) + setDesc(msg) + } + + + /** + * add to deal with errorinfo derived from jobInfo + * @param errorCode + * @param msg + */ + def this(errorCode: Int,msg: String) { + this(UJESSQLErrorCode.ERRORINFO_FROM_JOBINFO) + setDesc(msg) + setErrCode(errorCode) + } + +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala similarity index 86% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala index f88ca4158f..8436e993e2 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatement.scala @@ -1,19 +1,35 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.io.{InputStream, Reader} import java.net.URL -import java.sql.{Blob, Clob, Connection, Date, NClob, ParameterMetaData, PreparedStatement, Ref, ResultSet, ResultSetMetaData, RowId, SQLWarning, SQLXML, Time, Timestamp} +import java.sql.{Blob, Clob, Date, NClob, ParameterMetaData, PreparedStatement, Ref, ResultSetMetaData, RowId, SQLXML, Time, Timestamp} import java.util import java.util.Calendar - -/** - * Created by leebai on 2019/8/16 - */ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String) extends UJESSQLStatement(ujesSQLConnection) with PreparedStatement { private val parameters = new util.HashMap[Int,Any] + private var parameterMetaData: ParameterMetaData = _ + + private var batchTimes = 0 + private def updateSql(sql: String, parameters: util.HashMap[Int,Any]) : String = { if(!sql.contains("?")){ sql @@ -153,11 +169,23 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String } override def execute(): Boolean = { - super.execute(updateSql(sql,parameters)) + val res = super.execute(updateSql(sql,parameters)) + for (i <- 1 to batchTimes) { + super.execute(updateSql(sql,parameters)) + } + res + } + + override def executeBatch(): Array[Int] = { + + for (i <- 0 to batchTimes) { + super.execute(updateSql(sql,parameters)) + } + Array(1,1) } override def addBatch(): Unit = { - throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT) + this.batchTimes = this.batchTimes + 1 } override def setCharacterStream(parameterIndex: Int, reader: Reader, length: Int): Unit = { @@ -182,7 +210,8 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String override def getMetaData: ResultSetMetaData = { if(super.getResultSet == null){ - throw new UJESSQLException(UJESSQLErrorCode.RESULTSET_NULL) + //TODO 这里应该返回的是获取到到的结果集元数据 + return new UJESSQLResultSetMetaData } super.getResultSet.getMetaData } @@ -208,7 +237,12 @@ class UJESSQLPreparedStatement(ujesSQLConnection: UJESSQLConnection, sql: String } override def getParameterMetaData: ParameterMetaData = { - throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT) + synchronized { + if (null == this.parameterMetaData) { + this.parameterMetaData = new LinkisParameterMetaData(sql.count(_ =='?' )) + } + } + this.parameterMetaData } override def setRowId(parameterIndex: Int, x: RowId): Unit = { diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala similarity index 94% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala index e4fe963653..557878d1e7 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSet.scala @@ -1,19 +1,31 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.io.{InputStream, Reader} import java.math.MathContext import java.net.URL -import java.sql.{Blob, Clob, Connection, Date, NClob, Ref, ResultSet, ResultSetMetaData, RowId, SQLWarning, SQLXML, Statement, Time, Timestamp} +import java.sql.{Blob, Clob, Connection, Date, NClob, Ref, ResultSet, RowId, SQLWarning, SQLXML, Statement, Time, Timestamp} import java.util.Calendar import java.{sql, util} + import com.webank.wedatasphere.linkis.ujes.client.request.ResultSetAction import com.webank.wedatasphere.linkis.ujes.client.response.ResultSetResult - - - -/** - * Created by leebai on 2019/8/14. - */ +import org.apache.commons.lang.StringUtils class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLStatement, maxRows: Int, fetchSize: Int) extends ResultSet { @@ -26,7 +38,6 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var resultSetMetaData: UJESSQLResultSetMetaData = new UJESSQLResultSetMetaData - private var maxRowNum : Int = _ private var fetchSizeNum : Int = _ @@ -36,11 +47,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var path : String = null - private val page : Int = 1 - - private val pageSize : Int = 5000 - - private var metaData : util.ArrayList[String] = _ + private var metaData : util.List[util.Map[String, String]] = _ private val statement : UJESSQLStatement = ujesStatement @@ -50,28 +57,42 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState private var warningChain : SQLWarning = null + init() + private def getResultSetPath(resultSetList: Array[String]): String = { - resultSetList(resultSetList.length-1) + if (resultSetList.length > 0){ + resultSetList(resultSetList.length-1) + } else { + "" + } } private def resultSetResultInit(): Unit = { if (path == null) path = getResultSetPath(resultSetList) val user = connection.getProps.getProperty("user") - val resultAction = ResultSetAction.builder.setUser(user).setPath(path).build() - resultSetResult = connection.ujesClient.resultSet(resultAction) + if (StringUtils.isNotBlank(path)){ + val resultAction = ResultSetAction.builder.setUser(user).setPath(path).build() + resultSetResult = connection.ujesClient.resultSet(resultAction) + } } private def metaDataInit(): Unit = { - metaData = resultSetResult.getMetadata.asInstanceOf[util.ArrayList[String]] + if ( null == resultSetResult ){ + return + } + metaData = resultSetResult.getMetadata.asInstanceOf[util.List[util.Map[String, String]]] for(cursor <- 1 to metaData.size()){ - val str: Array[String] = metaData.get(cursor-1).split(",") - resultSetMetaData.setColumnNameProperties(cursor,str(0).split(":")(1)) - resultSetMetaData.setDataTypeProperties(cursor,str(1).split(":")(1)) - resultSetMetaData.setCommentPropreties(cursor,str(2).split(":")(1)) + val col = metaData.get(cursor - 1) + resultSetMetaData.setColumnNameProperties(cursor, col.get("columnName")) + resultSetMetaData.setDataTypeProperties(cursor, col.get("dataType")) + resultSetMetaData.setCommentPropreties(cursor, col.get("comment")) } } private def resultSetInit(): Unit = { + if ( null == resultSetResult ){ + return + } resultSetRow = resultSetResult.getFileContent.asInstanceOf[util.ArrayList[util.ArrayList[String]]] } @@ -90,7 +111,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState override def next(): Boolean = { if(metaData == null) init() currentRowCursor += 1 - if(currentRowCursor > resultSetRow.size()-1) false + if(null == resultSetRow || currentRowCursor > resultSetRow.size()-1) false else{ updateCurrentRow(currentRowCursor) true @@ -204,7 +225,10 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState if(wasNull()) { throw new UJESSQLException(UJESSQLErrorCode.RESULTSET_ROWERROR, "Type is null") }else{ - any.asInstanceOf[Long] + any match { + case i:Integer => i.longValue() + case _ => any.asInstanceOf[Long] + } } } @@ -356,6 +380,7 @@ class UJESSQLResultSet(resultSetList: Array[String], ujesStatement: UJESSQLState } override def getMetaData: UJESSQLResultSetMetaData = { + if(metaData == null) init() resultSetMetaData } diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala new file mode 100644 index 0000000000..d910932bd1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetMetaData.scala @@ -0,0 +1,115 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.ResultSetMetaData +import java.util + +class UJESSQLResultSetMetaData extends ResultSetMetaData { + private val columnNameProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private val dataTypeProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private val commentProperties: util.HashMap[Int,String] = new util.HashMap[Int,String]() + + private[jdbc] def setColumnNameProperties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + columnNameProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + private[jdbc] def setDataTypeProperties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + dataTypeProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + private[jdbc] def setCommentPropreties(column: Int,columnName: String): Unit ={ + if(column != null && columnName != null){ + commentProperties.put(column,columnName) + }else throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + } + + override def getColumnCount: Int = { + columnNameProperties.size + } + + override def isAutoIncrement(column: Int): Boolean = { + throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) + } + + override def isCaseSensitive(column: Int): Boolean = true + + override def isSearchable(column: Int): Boolean = true + + override def isCurrency(column: Int): Boolean = true + + override def isNullable(column: Int): Int = 1 + + override def isSigned(column: Int): Boolean = true + + override def getColumnDisplaySize(column: Int): Int = 1 + + override def getColumnLabel(column: Int): String = { + if(columnNameProperties.get(column) == null) { + throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + }else columnNameProperties.get(column) + } + + override def getColumnName(column: Int): String = { + getColumnLabel(column) + } + + override def getSchemaName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + //TODO 修改该参数 + override def getPrecision(column: Int): Int = 2147483647 + + override def getScale(column: Int): Int = { + columnNameProperties.size + } + + override def getTableName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getCatalogName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getColumnType(column: Int): Int = { + UJESSQLTypeParser.parserFromName(getColumnTypeName(column)) + } + + override def getColumnTypeName(column: Int): String = { + if(dataTypeProperties.get(column) == null) { + throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + }else dataTypeProperties.get(column) + } + + override def isReadOnly(column: Int): Boolean = { + true + } + + override def isWritable(column: Int): Boolean = { + false + } + + override def isDefinitelyWritable(column: Int): Boolean = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def getColumnClassName(column: Int): String = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def unwrap[T](iface: Class[T]): T = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } + + override def isWrapperFor(iface: Class[_]): Boolean = { throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_METADATA) } +} diff --git a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala similarity index 88% rename from ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala rename to linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala index e9021afa53..d5d93ab3fa 100644 --- a/ujes/jdbc/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatement.scala @@ -1,3 +1,19 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc import java.sql.{Connection, ResultSet, SQLWarning, Statement} @@ -8,14 +24,12 @@ import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction import com.webank.wedatasphere.linkis.ujes.client.request.JobExecuteAction.EngineType import com.webank.wedatasphere.linkis.ujes.client.response.JobExecuteResult +import com.webank.wedatasphere.linkis.ujes.jdbc.hook.JDBCDriverPreExecutionHook import scala.collection.JavaConversions import scala.concurrent.TimeoutException import scala.concurrent.duration.Duration -/** - * Created by owenxu on 2019/8/19 - */ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) extends Statement with Logging{ private var jobExecuteResult: JobExecuteResult = _ @@ -25,6 +39,8 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e private var fetchSize = 100 private var queryTimeout = 0 + private var queryEnd = false + private[jdbc] def throwWhenClosed[T](op: => T): T = ujesSQLConnection.throwWhenClosed { if(isClosed) throw new UJESSQLException(UJESSQLErrorCode.STATEMENT_CLOSED) else op @@ -46,7 +62,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e } def clearQuery(): Unit = { - if(jobExecuteResult != null) { + if(jobExecuteResult != null && ! queryEnd) { Utils.tryAndWarn(ujesSQLConnection.ujesClient.kill(jobExecuteResult)) jobExecuteResult = null } @@ -79,10 +95,17 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e override def setCursorName(name: String): Unit = throw new UJESSQLException(UJESSQLErrorCode.NOSUPPORT_STATEMENT, "setCursorName not supported") override def execute(sql: String): Boolean = throwWhenClosed { - val action = JobExecuteAction.builder().setEngineType(EngineType.SPARK).addExecuteCode(sql) + var parsedSQL = sql + JDBCDriverPreExecutionHook.getPreExecutionHooks.foreach{ + preExecution => + parsedSQL = preExecution.callPreExecutionHook(parsedSQL) + } + val action = JobExecuteAction.builder().setEngineType(EngineType.SPARK).addExecuteCode(parsedSQL) .setCreator(ujesSQLConnection.creator).setUser(ujesSQLConnection.user) + if(ujesSQLConnection.variableMap.nonEmpty) action.setVariableMap(JavaConversions.mapAsJavaMap(ujesSQLConnection.variableMap)) jobExecuteResult = ujesSQLConnection.ujesClient.execute(action.build()) + queryEnd = false var status = ujesSQLConnection.ujesClient.status(jobExecuteResult) val atMost = if(queryTimeout > 0) Duration(queryTimeout, TimeUnit.MILLISECONDS) else Duration.Inf if(!status.isCompleted) Utils.tryThrow{ @@ -99,7 +122,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e if(!closed) { var jobInfo = ujesSQLConnection.ujesClient.getJobInfo(jobExecuteResult) if(status.isFailed) throw new ErrorException(jobInfo.getRequestPersistTask.getErrCode,jobInfo.getRequestPersistTask.getErrDesc) - var jobInfoStatus = jobInfo.getJobStatus + val jobInfoStatus = jobInfo.getJobStatus if(!jobInfoStatus.equals("Succeed")) Utils.tryThrow{ Utils.waitUntil(() => { jobInfo = ujesSQLConnection.ujesClient.getJobInfo(jobExecuteResult) @@ -116,6 +139,7 @@ class UJESSQLStatement(private[jdbc] val ujesSQLConnection: UJESSQLConnection) e case t => t } val resultSetList = jobInfo.getResultSetList(ujesSQLConnection.ujesClient) + queryEnd = true if(resultSetList != null) { resultSet = new UJESSQLResultSet(resultSetList, this, maxRows, fetchSize) true diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala new file mode 100644 index 0000000000..094a7bd64b --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLTypeParser.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc + +import java.sql.{SQLException, Timestamp, Types} + +object UJESSQLTypeParser { + def parserFromName(typeName: String): Int = { + typeName.toLowerCase match { + case null => throw new UJESSQLException(UJESSQLErrorCode.METADATA_EMPTY) + case "string" => Types.CHAR + case "short" => Types.SMALLINT + case "int" => Types.INTEGER + case "long" => Types.BIGINT + case "float" => Types.FLOAT + case "double" => Types.DOUBLE + case "boolean" => Types.BOOLEAN + case "byte" => Types.TINYINT + case "char" => Types.CHAR + case "timestamp" => Types.TIMESTAMP + case _ => throw new SQLException( s"parameter type error,Type:$typeName") + } + } + + def parserFromVal(obj: Any): Int ={ + obj match { + case _: String => Types.CHAR + case _: Short => Types.SMALLINT + case _: Int => Types.INTEGER + case _: Long => Types.BIGINT + case _: Float => Types.FLOAT + case _: Double => Types.DOUBLE + case _: Boolean => Types.BOOLEAN + case _: Byte => Types.TINYINT + case _: Char => Types.CHAR + case _: Timestamp => Types.TIMESTAMP + case _ => throw new UJESSQLException(UJESSQLErrorCode.PREPARESTATEMENT_TYPEERROR) + } + } + def parserFromMetaData(dataType: Int): String = { + dataType match { + case Types.CHAR => "string" + case Types.SMALLINT => "short" + case Types.INTEGER => "int" + case Types.BIGINT => "long" + case Types.FLOAT => "float" + case Types.DOUBLE => "double" + case Types.BOOLEAN => "boolean" + case Types.TINYINT => "byte" + case Types.CHAR => "char" + case Types.TIMESTAMP => "timestamp" + case _ => throw new UJESSQLException(UJESSQLErrorCode.PREPARESTATEMENT_TYPEERROR) + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala new file mode 100644 index 0000000000..792d55c045 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/JDBCDriverPreExecutionHook.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.hook + +import com.webank.wedatasphere.linkis.common.conf.CommonVars +import com.webank.wedatasphere.linkis.common.utils.{Logging, Utils} + +import scala.collection.mutable.ArrayBuffer + +trait JDBCDriverPreExecutionHook { + + def callPreExecutionHook(sql: String): String + +} + +object JDBCDriverPreExecutionHook extends Logging{ + + private val preExecutionHooks:Array[JDBCDriverPreExecutionHook] = { + val hooks = new ArrayBuffer[JDBCDriverPreExecutionHook]() + CommonVars("wds.linkis.jdbc.pre.hook.class", "com.webank.wedatasphere.linkis.ujes.jdbc.hook.impl.TableauPreExecutionHook").getValue.split(",") foreach { + hookStr => Utils.tryCatch{ + val clazz = Class.forName(hookStr.trim) + val obj = clazz.newInstance() + obj match { + case hook:JDBCDriverPreExecutionHook => hooks += hook + case _ => warn(s"obj is not a engineHook obj is ${obj.getClass}") + } + }{ + case e:Exception => error(s"failed to load class ${hookStr}", e) + } + } + hooks.toArray + } + + def getPreExecutionHooks = preExecutionHooks +} \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala new file mode 100644 index 0000000000..ff5d9e4a0d --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/main/scala/com/webank/wedatasphere/linkis/ujes/jdbc/hook/impl/TableauPreExecutionHook.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc.hook.impl + +import com.webank.wedatasphere.linkis.ujes.jdbc.hook.JDBCDriverPreExecutionHook + +class TableauPreExecutionHook extends JDBCDriverPreExecutionHook{ + override def callPreExecutionHook(sql: String): String = { + if (sql.contains("LOCAL TEMPORARY")){ + sql.replace("LOCAL TEMPORARY", "").replace("ON COMMIT PRESERVE ROWS", "") + } else if (sql.contains("GROUP BY 2")){ + sql.replace("GROUP BY 2","") + } else if (sql.contains("`#")) { + sql.replace("`#", "`") + } else if (sql.startsWith("INSERT")) { + sql.replace("(COL)", "").replaceAll("VALUES (.*)", "VALUES (1)") + } else if (sql.contains("CREATE INDEX")) { + "select 1" + } else{ + sql.replace("TOP", "").replace("CHECKTOP","") + } + } +} diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java new file mode 100644 index 0000000000..cba8812fa8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/CreateConnection.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +/* + * Notice: + * if you want to test this module,you must rewrite default parameters and SQL we used for local test + * */ + +import java.sql.DriverManager; +import java.sql.SQLException; + +public class CreateConnection { + + private static UJESSQLConnection conn; + + public static UJESSQLConnection getConnection() throws ClassNotFoundException, SQLException { + Class.forName("com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver"); + conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://hostname:port","username","password"); + return conn; + } +} + diff --git a/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java new file mode 100644 index 0000000000..9266cad771 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/JDBCSpiTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.ujes.jdbc; + +import org.junit.Assert; +import org.junit.Test; + +import java.sql.DriverManager; +import java.sql.SQLException; + +/* + * Notice: + * if you want to test this module,you must rewrite default parameters and SQL we used for local test + * */ + +public class JDBCSpiTest { + private static UJESSQLConnection conn; + public static UJESSQLConnection getConnection() throws ClassNotFoundException, SQLException { + Class.forName("com.webank.wedatasphere.linkis.ujes.jdbc.UJESSQLDriver"); + conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://127.0.0.1:9001", "shanhuang", "Abcd1234@"); + return conn; + } + @Test + public void spiTest(){ + try { + UJESSQLConnection conn = (UJESSQLConnection) DriverManager.getConnection("jdbc:linkis://hostname:port","username","password"); + Assert.assertNotNull(conn); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java similarity index 86% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java index 1b712ed938..11c30b285f 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLDatabaseMetaDataTest.java @@ -1,8 +1,21 @@ -package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by owenxu on 2019/8/23. +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ +package com.webank.wedatasphere.linkis.ujes.jdbc; + /* * Notice: * if you want to test this module,you must rewrite default parameters and SQL we used for local test diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java similarity index 78% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java index 8f7ce56f4a..0046a5db8d 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLPreparedStatementTest.java @@ -1,14 +1,30 @@ -package com.webank.wedatasphere.linkis.ujes.jdbc; - -/** - * Created by leebai on 2019/8/23. +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ +package com.webank.wedatasphere.linkis.ujes.jdbc; + /* * Notice: * if you want to test this module,you must rewrite default SQL we used for local test * */ -import org.junit.*; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; import java.sql.SQLException; @@ -66,7 +82,7 @@ public void execute() { @Test public void selectTest(){ - preStatement = conn.prepareStatement("select * from bdp_test"); + preStatement = conn.prepareStatement("select * from shanhuang_ind.testjohn1 limit 10"); UJESSQLResultSet resultSet = preStatement.executeQuery(); showResult(resultSet); Assert.assertTrue(resultSet.isAfterLast()); diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java similarity index 82% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java index 573156c35e..9a93fe73b7 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLResultSetTest.java @@ -1,8 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by leebai on 2019/8/23. - */ import org.junit.*; import java.sql.SQLException; diff --git a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java similarity index 84% rename from ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java rename to linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java index e7c21ee277..801ee11ac4 100644 --- a/ujes/jdbc/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java +++ b/linkis-computation-governance/linkis-jdbc-driver/src/test/java/com/webank/wedatasphere/linkis/ujes/jdbc/UJESSQLStatementTest.java @@ -1,8 +1,21 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.webank.wedatasphere.linkis.ujes.jdbc; -/** - * Created by owenxu on 2019/8/23. - */ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd new file mode 100644 index 0000000000..ef1f01a1bd --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connection-dialog.tcd @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js new file mode 100644 index 0000000000..218f5759b8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionBuilder.js @@ -0,0 +1,5 @@ +(function dsbuilder(attr) { + var urlBuilder = "jdbc:linkis://" + attr[connectionHelper.attributeServer] + ":" + attr[connectionHelper.attributePort] + "/" + attr[connectionHelper.attributeDatabase]; + + return [urlBuilder]; +}) diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js new file mode 100644 index 0000000000..14949bfec1 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionProperties.js @@ -0,0 +1,12 @@ +(function propertiesbuilder(attr) { + var props = {}; + props["user"] = attr[connectionHelper.attributeUsername]; + props["password"] = attr[connectionHelper.attributePassword]; + + if (attr[connectionHelper.attributeSSLMode] == "require") { + props["ssl"] = "true"; + props["sslmode"] = "require"; + } + + return props; +}) diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr new file mode 100644 index 0000000000..bc17b3ef52 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/connectionResolver.tdr @@ -0,0 +1,24 @@ + + + + + + + + + + + server + port + dbname + username + password + sslmode + + + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd new file mode 100644 index 0000000000..c6b6c714e8 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/dialect.tdd @@ -0,0 +1,1205 @@ + + + + ABS(%1) + + + + ABS(%1) + + + + ACOS(%1) + + + + ASIN(%1) + + + + ATAN(%1) + + + + CEILING(%1) + + + + COS(%1) + + + + IF(%1 != 0, COS(%1)/SIN(%1), NULL) + + + + DEGREES(%1) + + + + CASE WHEN %2 = 0 THEN NULL ELSE ( %1 / %2 ) END + + + + + EXP(%1) + + + + FLOOR(%1) + + + + (((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN 1.5 ELSE 0.0 END) - (CASE WHEN ((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0) < 0.0) AND ((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN 1.5 ELSE 0.0 END) > 0.0) THEN 3.0 ELSE 0.0 END)) + (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0)) + + + + + ROUND(((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN SQRT(3.0) / 2.0 ELSE 0.0 END) - (CASE WHEN ((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)) < 0.0) AND ((CASE WHEN (ABS((%2) - (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)))) + SQRT(3.0) * ((ABS((%1) - (CAST( ( (%1) / 3.0 ) AS DECIMAL(18, 0) ) * 3.0))) - 1.0) > 0.0 THEN SQRT(3.0) / 2.0 ELSE 0.0 END) > 0.0) THEN SQRT(3.0) ELSE 0.0 END)) + (CAST( ( (%2) / SQRT(3.0) ) AS DECIMAL(18, 0) ) * SQRT(3.0)),3) + + + + + (CASE WHEN %1 > 0 THEN LN(%1) ELSE CAST(NULL AS DOUBLE) END) + + + + (CASE WHEN %1 > 0 THEN LOG10(%1) ELSE CAST(NULL AS DOUBLE) END) + + + + (CASE WHEN %1 > 0 THEN LOG10(%1) / LOG10(%2) ELSE NULL END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + PI() + + + (CASE WHEN %1 < 0 AND FLOOR(%2) <> %2 THEN NULL ELSE POW(%1,%2) END) + + + + + POW(%1,%2) + + + + + POW(CAST(%1 AS DOUBLE),%2) + + + + + RADIANS(%1) + + + + ROUND(%1) + + + + ROUND(%1,CAST(%2 AS BIGINT)) + + + + + ROUND(%1,%2) + + + + + SIGN(%1) + + + + SIN(%1) + + + + (CASE WHEN %1 < 0 THEN CAST(NULL AS DOUBLE) ELSE SQRT(%1) END) + + + + POW(%1,2) + + + + (SIN(%1)/COS(%1)) + + + + XPATH_DOUBLE(%1,%2) + + + + + XPATH_FLOAT(%1,%2) + + + + + XPATH_INT(%1,%2) + + + + + XPATH_LONG(%1,%2) + + + + + XPATH_SHORT(%1,%2) + + + + + COALESCE(CAST(%1 AS DOUBLE), 0.0) + + + + COALESCE(CAST(%1 AS BIGINT), CAST(0 AS BIGINT)) + + + + ASCII(%1) + + + + %1 RLIKE CONCAT('.*', %2, '.*') + + + + + (CASE WHEN ((CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) IS NULL) OR (LENGTH(%2) IS NULL) THEN NULL WHEN LENGTH(%2) < 1 THEN '' WHEN (CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) < 1 THEN SUBSTRING(RTRIM(%1),CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) ELSE SUBSTRING(RTRIM(%1),CAST((CASE WHEN (LENGTH(%1) - LENGTH(%2)) < 0 THEN 1 ELSE LENGTH(%1) - LENGTH(%2) + 1 END) AS INT),CAST(LENGTH(%2) AS INT)) END) = %2 + + + + + INSTR( %1, %2 ) + + + + + (CASE WHEN (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN INSTR( %1, %2 ) WHEN 0 = INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) THEN 0 ELSE INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) + CAST(%3 AS BIGINT) - 1 END) + + + + + + (CASE WHEN (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN INSTR( %1, %2 ) WHEN 0 = INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) THEN 0 ELSE INSTR( SUBSTRING(%1,CAST(%3 AS INT),CAST(LENGTH(%1) - (%3) + 1 AS INT)), %2 ) + %3 - 1 END) + + + + + + GET_JSON_OBJECT(%1,%2) + + + + + CASE WHEN %2 >= 0 THEN SUBSTRING(%1,1,CAST(CAST(%2 AS BIGINT) AS INT)) ELSE NULL END + + + + + CASE WHEN %2 >= 0 THEN SUBSTRING(%1,1,CAST(%2 AS INT)) ELSE NULL END + + + + + LENGTH(%1) + + + + LOWER(%1) + + + + LTRIM(%1) + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 > %2 THEN %1 ELSE %2 END) + + + + + (CASE WHEN (%2 IS NULL) OR %2 < 1 THEN NULL ELSE SUBSTRING(%1,CAST(CAST(%2 AS BIGINT) AS INT),CAST(LENGTH(%1) - (CAST(%2 AS BIGINT)) + 1 AS INT)) END) + + + + + (CASE WHEN (%2 IS NULL) OR %2 < 1 THEN NULL ELSE SUBSTRING(%1,CAST(%2 AS INT),CAST(LENGTH(%1) - (%2) + 1 AS INT)) END) + + + + + (CASE WHEN (%2 IS NULL) OR (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN '' WHEN %2 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(CAST(%3 AS BIGINT) AS INT)) ELSE SUBSTRING(%1,CAST(CAST(%2 AS BIGINT) AS INT),CAST(CAST(%3 AS BIGINT) AS INT)) END) + + + + + + (CASE WHEN (%2 IS NULL) OR (%3 IS NULL) THEN NULL WHEN %3 < 1 THEN '' WHEN %2 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(%3 AS INT)) ELSE SUBSTRING(%1,CAST(%2 AS INT),CAST(%3 AS INT)) END) + + + + + + (CASE WHEN (%1 IS NULL) OR (%2 IS NULL) THEN NULL WHEN %1 < %2 THEN %1 ELSE %2 END) + + + + + PARSE_URL(%1,%2) + + + + + PARSE_URL(%1,'QUERY',%2) + + + + + REGEXP_EXTRACT(%1,%2,1) + + + + + REGEXP_EXTRACT(%1,%2,%3) + + + + + + REGEXP_REPLACE(%1,%2,%3) + + + + + + REGEXP_REPLACE(%1,%2,%3) + + + + + + (CASE WHEN %2 >= 0 THEN IF(LENGTH(%1) < %2 + 1, %1, SUBSTRING(%1, LENGTH(%1) - CAST(%2 AS INT) + 1)) ELSE NULL END) + + + + + (CASE WHEN %2 >= 0 THEN IF(LENGTH(%1) < %2 + 1, %1, SUBSTRING(%1, LENGTH(%1) - CAST(%2 AS INT) + 1)) ELSE NULL END) + + + + + RTRIM(%1) + + + + (CASE WHEN CAST(%1 AS BIGINT) >= 0 THEN SPACE(CAST(CAST(%1 AS BIGINT) AS INT)) ELSE CAST(NULL AS STRING) END) + + + + (CASE WHEN %1 >= 0 THEN SPACE(CAST(%1 AS INT)) ELSE CAST(NULL AS STRING) END) + + + + SPLIT(%1,%2)[%3] + + + + + + (CASE WHEN (1 IS NULL) OR (LENGTH(%2) IS NULL) THEN NULL WHEN LENGTH(%2) < 1 THEN '' WHEN 1 < 1 THEN SUBSTRING(%1,CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) ELSE SUBSTRING(%1,CAST(1 AS INT),CAST(LENGTH(%2) AS INT)) END) = %2 + + + + + TRIM(%1) + + + + UPPER(%1) + + + + XPATH_STRING(%1,%2) + + + + + %1 + + + + %1 + + + + CAST (TO_DATE(%1) AS DATE) + + + + CAST (%1 AS DATE) + + + + CAST (%1 AS DATE) + + + + %1 + + + + CAST(%1 AS TIMESTAMP) + + + + %1 + + + + CAST(%1 AS TIMESTAMP) + + + + (CASE WHEN %1 THEN 1.0 WHEN NOT %1 THEN 0.0 ELSE NULL END) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(%1 AS DOUBLE) + + + + CAST(UNIX_TIMESTAMP(%1) AS DOUBLE) + + + + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END) + + + + CAST(%1 AS BIGINT) + + + + CAST(%1 AS BIGINT) + + + + CAST(CAST(%1 AS DOUBLE) AS BIGINT) + + + + CAST(%1 AS BIGINT) + + + + CAST(UNIX_TIMESTAMP(%1) AS INT) + + + + (CASE WHEN %1 THEN '1' WHEN NOT %1 THEN '0' ELSE NULL END) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + CAST(%1 AS STRING) + + + + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE (CASE WHEN %2 THEN 1 WHEN NOT %2 THEN 0 ELSE NULL END) END)=1 + + + + + COALESCE(CAST(%1 AS DOUBLE), CAST(%2 AS DOUBLE)) + + + + + COALESCE(CAST(%1 AS BIGINT), CAST(%2 AS BIGINT)) + + + + + COALESCE(%1, %2) + + + + + COALESCE(%1, %2) + + + + + COALESCE(%1, %2) + + + + + ((%1 AND %2) OR ((NOT %1) AND %3)) + + + + + + (CASE WHEN %1 THEN CAST(%2 AS DOUBLE) WHEN NOT %1 THEN CAST(%3 AS DOUBLE) ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE NULL END) + + + + + + (CASE WHEN %1 THEN %2 WHEN NOT %1 THEN %3 ELSE %4 END) + + + + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + (%1 IS NULL) + + + + XPATH_BOOLEAN(%1,%2) + + + + + AVG(%1) + %1 + + + + AVG(CAST(%1 AS DOUBLE)) + %1 + + + + CORR(%1, %2) + CAST(NULL AS DOUBLE) + + + + + COUNT(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END) + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 1 ELSE 0 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(%1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)) + (CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 1 ELSE 0 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COUNT(DISTINCT %1) + (CASE WHEN (%1 IS NULL) THEN 0 ELSE 1 END) + + + + COVAR_SAMP(%1, %2) + CAST(NULL AS DOUBLE) + + + + + COVAR_POP(%1, %2) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) WHEN %2 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END + + + + + (MAX(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)=1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + MAX(%1) + %1 + + + + percentile_approx(%1, 0.5) + %1 + + + + (MIN(CASE WHEN %1 THEN 1 WHEN NOT %1 THEN 0 ELSE NULL END)=1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + MIN(%1) + %1 + + + + PERCENTILE_APPROX(%1, %2) + %1 + + + + + PERCENTILE(%1, %2) + %1 + + + + + (CASE WHEN COUNT(%1) > 1 THEN STDDEV_SAMP(%1) ELSE NULL END) + CAST(NULL AS DOUBLE) + + + + STDDEV_POP(%1) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END) + + + + SUM(%1) + %1 + + + + SUM(%1) + %1 + + + + (CASE WHEN COUNT(%1) > 1 THEN VAR_SAMP(%1) ELSE NULL END) + CAST(NULL AS DOUBLE) + + + + VAR_POP(%1) + (CASE WHEN %1 IS NULL THEN CAST(NULL AS DOUBLE) ELSE 0.0 END) + + + + (NOT %1) + + + + (%1 AND NOT %2 OR NOT %1 AND %2) + + + + + (%1 <> %2) + + + + + (%1 <> %2) + + + + + (%1 <> %2) + + + + + (%1 <> CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) <> %2) + + + + + (%1 <> %2) + + + + + PMOD(%1, %2) + + + + + PMOD(%1, %2) + + + + + (%1 AND %2) + + + + + (%1 * %2) + + + + + (%1 * %2) + + + + + (%1 + %2) + + + + + (%1 + %2) + + + + + CONCAT(%1,%2) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(%1 AS BIGINT) + (%2 * 86400) AS BIGINT)) AS TIMESTAMP) + + + + + CAST(CONCAT(DATE_ADD(%1, CAST(%2 AS INT)), SUBSTR(CAST(%1 AS TIMESTAMP), 11)) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(CAST(%1 AS TIMESTAMP) AS BIGINT) + (%2 * 86400) AS BIGINT)) AS TIMESTAMP) + + + + + CAST(DATE_ADD(%1, CAST(%2 AS INT)) AS DATE) + + + + + (-%1) + + + + (%1 - %2) + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (UNIX_TIMESTAMP(%1) - UNIX_TIMESTAMP(%2)) / 86400.0 + + + + + (-%1) + + + + (%1 - %2) + + + + + CAST(FROM_UNIXTIME(CAST(%1 AS BIGINT) - CAST((%2) * 86400 AS INT)) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(%1 AS BIGINT) - (%2) * 86400) AS TIMESTAMP) + + + + + CAST(FROM_UNIXTIME(CAST(CAST(%1 AS TIMESTAMP) AS BIGINT) - CAST((%2) * 86400 AS INT)) AS TIMESTAMP) + + + + + CAST(DATE_ADD(%1, CAST(-(%2) AS INT)) AS DATE) + + + + + (CASE WHEN %2 = 0 THEN NULL ELSE %1 / %2 END) + + + + + (CASE WHEN %2 = 0 THEN NULL ELSE CAST(%1 AS DOUBLE) / %2 END) + + + + + (%1 < %2) + + + + + (%1 < %2) + + + + + (%1 < %2) + + + + + (%1 < CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) < %2) + + + + + (%1 < %2) + + + + + (%1 <= %2) + + + + + (%1 <= %2) + + + + + (%1 <= %2) + + + + + (%1 <= CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) <= %2) + + + + + (%1 <= %2) + + + + + (%1 AND %2 OR NOT %1 AND NOT %2) + + + + + (%1 = %2) + + + + + (%1 = %2) + + + + + (%1 = %2) + + + + + (%1 = CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) = %2) + + + + + (%1 = %2) + + + + + (%1 > %2) + + + + + (%1 > %2) + + + + + (%1 > %2) + + + + + (%1 > CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) > %2) + + + + + (%1 > %2) + + + + + (%1 >= %2) + + + + + (%1 >= %2) + + + + + (%1 >= %2) + + + + + (%1 >= CAST(%2 AS TIMESTAMP)) + + + + + (CAST(%1 AS TIMESTAMP) >= %2) + + + + + (%1 >= %2) + + + + + (CASE WHEN %1 < 0 AND FLOOR(%2) <> %2 THEN NULL ELSE POW(%1,%2) END) + + + + + POW(%1,%2) + + + + + POW(CAST(%1 AS DOUBLE),%2) + + + + + (%1 OR %2) + + + + + DAY(%1) + + + + DAY(%1) + + + + MONTH(%1) + + + + MONTH(%1) + + + + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP()) AS TIMESTAMP) + + + CAST((MONTH(%1) - 1) / 3 + 1 AS BIGINT) + + + + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd 00:00:00') AS TIMESTAMP) + + + FLOOR((14 + DATEDIFF(%1, TRUNC(%1,'YY')) + DATEDIFF(TRUNC(%1,'YY'),NEXT_DAY(TRUNC(%1,'YY'),'SU')))/7) + + + + YEAR(%1) + + + + YEAR(%1) + + + + CAST(CONCAT(YEAR(%3)+%2, SUBSTR(CAST(%3 AS TIMESTAMP), 5)) AS TIMESTAMP) + CAST(CONCAT(ADD_MONTHS(%3,(%2 * 3)),SUBSTR(CAST(%3 AS TIMESTAMP),11)) AS TIMESTAMP) + CAST(CONCAT(ADD_MONTHS(%3,%2),SUBSTR(CAST(%3 AS TIMESTAMP),11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(%2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(CONCAT(DATE_ADD(CAST(%3 AS TIMESTAMP), CAST(7 * %2 AS INT)), SUBSTR(CAST(CAST(%3 AS TIMESTAMP) AS TIMESTAMP), 11)) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2*3600) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2*60) AS TIMESTAMP) + CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(%3) + %2) AS TIMESTAMP) + + + + + + + FLOOR(DATEDIFF(NEXT_DAY(%2,'SU'),NEXT_DAY(%1,'SU'))/7) + + + + + + + CAST(YEAR(%2) AS STRING) + CAST(CAST((MONTH(%2) - 1) / 3 + 1 AS BIGINT) AS STRING) + CAST(MONTH(%2) AS STRING) + CAST(DATEDIFF(TO_DATE(%2), TO_DATE(CAST(TRUNC(%2,'YY') AS DATE))) + 1 AS STRING) + CAST(DAY(%2) AS STRING) + CAST((8 + DATEDIFF(CAST(%2 AS DATE),NEXT_DAY(%2,'SU'))) AS STRING) + FORMAT_NUMBER(FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7),0) + CAST(HOUR(%2) AS STRING) + COALESCE(CAST(MINUTE(%2) AS STRING), '') + COALESCE(CAST(SECOND(%2) AS STRING), '') + + + + + FORMAT_NUMBER(FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7),0) + + + + + + YEAR(%2) + CAST((MONTH(%2) - 1) / 3 + 1 AS BIGINT) + MONTH(%2) + DATEDIFF(TO_DATE(%2), TO_DATE(CAST(TRUNC(%2,'YY') AS DATE))) + 1 + DAY(%2) + (8 + DATEDIFF(%2,NEXT_DAY(CAST(%2 AS DATE),'SU'))) + FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7) + HOUR(%2) + MINUTE(%2) + SECOND(%2) + + + + + FLOOR((14 + DATEDIFF(%2, TRUNC(%2,'YY')) + DATEDIFF(TRUNC(%2,'YY'),NEXT_DAY(TRUNC(%2,'YY'),'SU')))/7) + + + + + + diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml new file mode 100644 index 0000000000..b4d6fe2973 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/manifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt new file mode 100644 index 0000000000..afaf360d37 --- /dev/null +++ b/linkis-computation-governance/linkis-jdbc-driver/tableau_plugin/version.txt @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file diff --git a/linkis-computation-governance/linkis-manager/label-common/pom.xml b/linkis-computation-governance/linkis-manager/label-common/pom.xml new file mode 100644 index 0000000000..e6e0c609d5 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/pom.xml @@ -0,0 +1,88 @@ + + + + + + linkis + com.webank.wedatasphere.linkis + 1.0.0-RC1 + ../../pom.xml + + 4.0.0 + + linkis-label-common + + + + com.webank.wedatasphere.linkis + linkis-common + ${linkis.version} + provided + + + + + org.reflections + reflections + ${reflections.version} + + + com.google.code.gson + gson + + + com.google.guava + guava + + + + + + + com.webank.wedatasphere.linkis + linkis-protocol + ${linkis.version} + provided + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + + net.alchim31.maven + scala-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + + + + + + + + + + + \ No newline at end of file diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java new file mode 100644 index 0000000000..7d7d1e3786 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/AbstractGenericLabelBuilder.java @@ -0,0 +1,343 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.webank.wedatasphere.linkis.manager.label.entity.CloneableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.InheritableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.*; +import java.util.function.Function; + +import static com.webank.wedatasphere.linkis.manager.label.utils.LabelUtils.Jackson.*; + +@SuppressWarnings("rawtypes") +public abstract class AbstractGenericLabelBuilder implements ExtensibleLabelBuilder { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractGenericLabelBuilder.class); + + /** + * Transform value object + * @param rawValue value + * @param parameterTypes parameters + * @param Any + * @return result + */ + @SuppressWarnings("unchecked") + protected V transformValueToConcreteType(Object rawValue, Type concreteType, Type[] parameterTypes, Function deserializer){ + if(null != rawValue){ + try { + Class> sourceClass = rawValue.getClass(); + Class> concreteClass = (Class>)concreteType; + if (concreteClass.isAssignableFrom(sourceClass)) { + if (CloneableLabel.class.isAssignableFrom(sourceClass)) { + //Just clone label + return (V) ((CloneableLabel) rawValue).clone(); + } + } else if (LabelUtils.isBasicType(concreteClass)) { + //Serialize the raw value first + return (V) convert(toJson(rawValue, null), concreteClass); + } else if (LabelUtils.isBasicType(rawValue.getClass())) { + String rawString = String.valueOf(rawValue); + if(null != deserializer){ + return deserializer.apply(rawString); + } + JavaType javaType = getJavaType(concreteType, parameterTypes); + if (concreteClass.equals(Map.class)) { + try { + return (V) convert(fromJson(rawString, Map.class, Object.class, Object.class), javaType); + } catch (Exception e) { + LOG.trace("Transform raw value fail, return empty object", e); + return fromJson("{}", javaType); + } + }else if (concreteClass.equals(List.class)) { + try { + return (V) convert(fromJson(rawString, List.class, Object.class), javaType); + } catch (Exception e) { + //Ignore + LOG.trace("Transform raw value fail, return empty list", e); + return fromJson("[]", javaType); + } + } + + } + //Try to convert value directly + return (V) LabelUtils.Jackson.convert(rawValue, getJavaType(concreteType, parameterTypes)); + }catch(Exception e){ + //Ignore + LOG.trace("Transform raw value fail, return null", e); + } + } + return null; + } + + + /** + * Find label's value class + * @param labelClass label class provided + * @return class array + */ + public Class>[] findActualLabelValueClass(Class extends Label> labelClass){ + Map, Type[]> classTypeVariableMap = new HashMap<>(); + Type[] classTypes = recurseToFindActualLabelValueType(labelClass, classTypeVariableMap); + if(null != classTypes) { + //Transform to class object + List> classesReturn = new ArrayList<>(); + //Expand combine types + classTypes = expandParameterizedType(classTypes); + for (Type classType : classTypes) { + if (classType instanceof Class) { + classesReturn.add((Class>) classType); + } else if (classType instanceof WildcardType) { + classesReturn.add(Object.class); + } + } + return classesReturn.toArray(new Class>[0]); + } + return null; + } + + /** + * Find label's value type + * @param labelType label class provided + * @return type array + */ + public Type[] findActualLabelValueType(Class extends Label> labelType){ + Map, Type[]> classTypeVariableMap = new HashMap<>(); + return recurseToFindActualLabelValueType(labelType, classTypeVariableMap); + } + /** + * Recurse to find label's value type + * @param labelClass label class + * @param classTypeVariableMap use to store the mapping relation between class and type + * @return value type array + */ + private Type[] recurseToFindActualLabelValueType(Class extends Label> labelClass, Map, Type[]> classTypeVariableMap){ + if(null == labelClass){ + return null; + } + //Store the reflect relation between parameter variable like 'T' and type like 'java.lang.String' + Map typeVariableReflect = new HashMap<>(); + Type[] typeParameters = labelClass.getTypeParameters(); + if(typeParameters.length > 0){ + Type[] classTypes = classTypeVariableMap.get(labelClass); + if(null == classTypes){ + return null; + } + for(int i = 0; i < classTypes.length; i ++ ){ + typeVariableReflect.put(typeParameters[i].getTypeName(), classTypes[i]); + } + } + if(labelClass.equals(Label.class) || labelClass.equals(InheritableLabel.class)){ + return classTypeVariableMap.get(labelClass); + } + // Search from interfaces to super class + Type[] valueTypes = findValueTypeFromInterface(labelClass, classTypeVariableMap, typeVariableReflect); + if(null == valueTypes){ + valueTypes = findValueTypeFromSuperclass(labelClass, classTypeVariableMap, typeVariableReflect); + } + return valueTypes; + } + + /** + * Find label's value type from interfaces + * @param labelClass label class + * @param classTypeVariableMap stored the mapping relation between class and type + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return value type array + */ + @SuppressWarnings("unchecked") + private Type[] findValueTypeFromInterface(Class extends Label> labelClass, + Map, Type[]> classTypeVariableMap, Map typeVariableReflect){ + Class>[] interfaces = labelClass.getInterfaces(); + if(interfaces.length > 0){ + for(int i = 0; i < interfaces.length; i ++){ + Class> interfaceClass = interfaces[i]; + if(Label.class.isAssignableFrom(interfaceClass)){ + //As the jdk doc, getInterfaces() and getGenericInterfaces() method has the same order + Type interfaceType = labelClass.getGenericInterfaces()[i]; + //If the interface type has type arguments, transform and store into 'classTypeVariableMap' + if(interfaceType instanceof ParameterizedType){ + Type[] actualTypes = ((ParameterizedType)interfaceType).getActualTypeArguments(); + actualTypes = transformParameterizedType(actualTypes, typeVariableReflect); + classTypeVariableMap.put(interfaceClass, actualTypes); + } + return recurseToFindActualLabelValueType((Class extends Label>)interfaceClass, classTypeVariableMap); + } + } + + } + return null; + } + + /** + * Find label's value type from super class + * @param label label class + * @param classTypeVariableMap stored the mapping relation between class and type + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return value type array + */ + @SuppressWarnings("unchecked") + private Type[] findValueTypeFromSuperclass(Class extends Label> label, + Map, Type[]> classTypeVariableMap, Map typeVariableReflect){ + Type superclassType = label.getGenericSuperclass(); + if(superclassType instanceof ParameterizedType){ + Type[] actualTypes = ((ParameterizedType)superclassType).getActualTypeArguments(); + actualTypes = transformParameterizedType(actualTypes, typeVariableReflect); + classTypeVariableMap.put(label.getSuperclass(), actualTypes); + } + return recurseToFindActualLabelValueType((Class extends Label>)label.getSuperclass(), classTypeVariableMap); + } + + /** + * Do transform + * @param rawTypes raw types + * @param typeVariableReflect stored the mapping relation between type variables and actually types + * @return result + */ + private Type[] transformParameterizedType(Type[] rawTypes, Map typeVariableReflect){ + return resolveParameterizedType(rawTypes, (rawType)->{ + if(rawType instanceof TypeVariable){ + return typeVariableReflect.getOrDefault(rawType.getTypeName(), rawType); + } + return rawType; + }); + } + + /** + * Resolve parameterized type (parameterized type -> combined type) + * @param rawTypes unresolved types + * @param resolveFunc resolve function + * @return resolved types + */ + private Type[] resolveParameterizedType(Type[] rawTypes, Function resolveFunc){ + Queue queue = new LinkedList<>(); + List resolvedTypes = new ArrayList<>(); + CombineType combineType = null; + for(Type rawType : rawTypes){ + queue.add(rawType); + while(!queue.isEmpty()){ + Type typeInQueue = queue.poll(); + //Change the combineType used currently + if(typeInQueue instanceof CombineType){ + combineType = (CombineType)typeInQueue; + continue; + } + if(typeInQueue instanceof ParameterizedType){ + //Construct a new combine type and add to queue + CombineType newCombineType = new CombineType(((ParameterizedType) typeInQueue).getRawType()); + queue.add(newCombineType); + Type[] actualTypes = ((ParameterizedType) typeInQueue).getActualTypeArguments(); + //Add the type arguments to queue + queue.addAll(Arrays.asList(actualTypes)); + //Add the combineType exist to the queue + if(null != combineType){ + combineType.childTypes.add(newCombineType); + queue.add(combineType); + }else{ + resolvedTypes.add(newCombineType); + } + }else if (null != combineType){ + combineType.childTypes.add(resolveFunc.apply(typeInQueue)); + }else{ + resolvedTypes.add(resolveFunc.apply(typeInQueue)); + } + } + combineType = null; + } + return resolvedTypes.toArray(new Type[0]); + } + + /** + * Expand combined types to array + * @param resolvedTypes combined types + * @return types + */ + private Type[] expandParameterizedType(Type[] resolvedTypes){ + Queue queue = new LinkedList<>(); + List expandTypes = new ArrayList<>(); + for(Type expandType : resolvedTypes){ + queue.add(expandType); + while(!queue.isEmpty()){ + Type typeInQueue = queue.poll(); + if(typeInQueue instanceof CombineType){ + CombineType combineType = (CombineType)typeInQueue; + expandTypes.add(combineType.actual); + queue.addAll(combineType.childTypes); + }else{ + expandTypes.add(typeInQueue); + } + } + } + return expandTypes.toArray(new Type[0]); + } + + /** + * Transform to Jackson's JavaType + * @param concreteType concrete type + * @param parameterTypes parameter type + * @return + */ + private JavaType getJavaType(Type concreteType, Type... parameterTypes){ + List javaTypes = new ArrayList<>(); + for (Type parameterType : parameterTypes) { + if (parameterType instanceof CombineType) { + CombineType combineType = (CombineType) parameterType; + javaTypes.add(getJavaType(combineType.actual, combineType.childTypes.toArray(new Type[0]))); + } else { + javaTypes.add(getJavaType(parameterType)); + } + } + if(javaTypes.size() > 0){ + Class> rawClass = Object.class; + if (concreteType instanceof Class) { + rawClass = (Class>) concreteType; + } + return TypeFactory.defaultInstance().constructParametricType(rawClass, javaTypes.toArray(new JavaType[0])); + } + return TypeFactory.defaultInstance().constructType(concreteType); + } + + /** + * Combine different type object + */ + protected static class CombineType implements Type{ + + /** + * Actual type + */ + protected Type actual; + + /** + * Children types + */ + protected List childTypes = new ArrayList<>(); + + CombineType(Type actual){ + this.actual = actual; + } + } +} diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java new file mode 100644 index 0000000000..1d16c8e116 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/CombinedLabelBuilder.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.webank.wedatasphere.linkis.manager.label.constant.LabelConstant; +import com.webank.wedatasphere.linkis.manager.label.constant.LabelKeyConstant; +import com.webank.wedatasphere.linkis.manager.label.entity.CombinedLabelImpl; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.exception.LabelErrorException; + +import javax.annotation.Nullable; +import java.util.List; + +public class CombinedLabelBuilder implements LabelBuilder { + + + @Override + public boolean canBuild(String labelKey) { + if (labelKey.startsWith(LabelKeyConstant.COMBINED_LABEL_KEY_PREFIX)) { + return true; + } + return false; + } + + @Override + public Label> build(String labelKey, @Nullable Object valueObj) throws LabelErrorException { + if (null != valueObj || valueObj instanceof List) { + try { + List> labels = (List>) valueObj; + return new CombinedLabelImpl(labels); + } catch (Throwable e) { + throw new LabelErrorException(LabelConstant.LABEL_BUILDER_ERROR_CODE, "Failed to build combinedLabel", e); + } + } + return null; + } +} diff --git a/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java new file mode 100644 index 0000000000..02eff9ff94 --- /dev/null +++ b/linkis-computation-governance/linkis-manager/label-common/src/main/java/com/webank/wedatasphere/linkis/manager/label/builder/DefaultGlobalLabelBuilder.java @@ -0,0 +1,253 @@ +/* + * Copyright 2019 WeBank + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.webank.wedatasphere.linkis.manager.label.builder; + +import com.webank.wedatasphere.linkis.manager.label.conf.LabelCommonConfig; +import com.webank.wedatasphere.linkis.manager.label.constant.LabelConstant; +import com.webank.wedatasphere.linkis.manager.label.entity.InheritableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.Label; +import com.webank.wedatasphere.linkis.manager.label.entity.SerializableLabel; +import com.webank.wedatasphere.linkis.manager.label.entity.annon.KeyMethod; +import com.webank.wedatasphere.linkis.manager.label.exception.LabelErrorException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.reflections.Reflections; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.*; +import java.util.function.Function; + +/** + * To build different types of label + */ +@SuppressWarnings(value= {"unchecked", "rawtypes"}) +public class DefaultGlobalLabelBuilder extends AbstractGenericLabelBuilder{ + + private static final Logger LOG = LoggerFactory.getLogger(DefaultGlobalLabelBuilder.class); + + private static final Reflections LABEL_ENTITY_REFLECTS; + + private static final Function DEFAULT_STRING_DESERIALIZER = stringValue -> stringValue; + + private static final Map>> LABEL_KEY_TYPE_MAP = new HashMap<>(); + + static{ + List packagesPath = new ArrayList<>(); + packagesPath.add(Label.class.getPackage().getName()); + String definedEntityPackages = LabelCommonConfig.LABEL_ENTITY_PACKAGES.getValue(); + if(StringUtils.isNotBlank(definedEntityPackages)){ + packagesPath.addAll(Arrays.asList(definedEntityPackages.split(","))); + } + LABEL_ENTITY_REFLECTS = new Reflections(packagesPath.toArray()); + //Lazy load all label keys of label entities + //Scan methods in Label to find annotation @LabelKey + Method[] methods = Label.class.getMethods(); + Method getKeyMethod = null; + for(Method method : methods){ + if(method.isAnnotationPresent(KeyMethod.class)){ + getKeyMethod = method; + } + } + if(null != getKeyMethod) { + @SuppressWarnings("rawtypes") + Set> labelEntities = LABEL_ENTITY_REFLECTS.getSubTypesOf(Label.class); + Method finalGetKeyMethod = getKeyMethod; + labelEntities.forEach((labelEntity) -> { + //New instance and then invoke get_key method + if(!Modifier.isInterface(labelEntity.getModifiers()) && + !Modifier.isAbstract(labelEntity.getModifiers())) { + try { + Label> label = labelEntity.newInstance(); + String labelKey = (String) finalGetKeyMethod.invoke(label); + if (StringUtils.isNotBlank(labelKey)) { + LABEL_KEY_TYPE_MAP.put(labelKey, (Class extends Label>>) labelEntity); + } + } catch (InstantiationException | IllegalAccessException e) { + LOG.info("Fail to reflect to new a label instance: [" + labelEntity.getSimpleName() + "]", e); + } catch (InvocationTargetException e) { + LOG.info("Fail to invoke method: [" + finalGetKeyMethod.getName() + + "] of label instance: [" + labelEntity.getSimpleName() + "]", e); + } + } + }); + } + } + + @Override + public boolean canBuild(String labelKey, Class> labelClass) { + //Support all sub classes/interfaces of Label + return null == labelClass || Label.class.isAssignableFrom(labelClass); + } + + @Override + public > T build(String labelKey, Object valueObj, Class> labelClass, Type... valueTypes) throws LabelErrorException { + Class extends Label> suitableLabelClass = getSuitableLabelClass(labelKey, labelClass); + if(null != suitableLabelClass){ + Type suitableValueType = getSuitableValueType(suitableLabelClass, valueTypes); + if(null != suitableValueType){ + return buildInner(labelKey, valueObj, suitableLabelClass, suitableValueType); + } + } + return null; + } + + + @Override + public > T build(String labelKey, Object valueObj, Class labelType) throws LabelErrorException { + return build(labelKey, valueObj, (Class>)labelType); + } + + @Override + public