diff --git a/.gitignore b/.gitignore index d3bc67d0..afd66f5e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,10 @@ target/ !**/node_modules/ !**/dist/ +### Agent ### +/hippo4j-agent/hippo4j-agent/ +**/dependency-reduced-pom.xml + ### STS ### .apt_generated .classpath diff --git a/docs/docs/user_docs/getting_started/config/hippo4j-config-more.md b/docs/docs/user_docs/getting_started/config/hippo4j-config-more.md index 2511b4f3..09452013 100644 --- a/docs/docs/user_docs/getting_started/config/hippo4j-config-more.md +++ b/docs/docs/user_docs/getting_started/config/hippo4j-config-more.md @@ -32,7 +32,7 @@ sidebar_position: 3 spring: dynamic: thread-pool: - tomcat: + web: enable: true executors: - thread-pool-id: message-consume @@ -50,7 +50,7 @@ spring: spring: dynamic: thread-pool: - tomcat: + web: nodes: 192.168.1.5:*,192.168.1.6:8080 executors: - thread-pool-id: message-consume diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 857f2106..2c6faa93 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -6,215 +6,215 @@ const darkCodeTheme = require('prism-react-renderer/themes/dracula'); /** @type {import('@docusaurus/types').Config} */ const config = { - title: 'Hippo4j', - tagline: '动态可观测线程池框架,为业务系统提高线上运行保障能力', - url: 'https://hippo4j.cn', - baseUrl: '/', - onBrokenLinks: 'throw', - onBrokenMarkdownLinks: 'warn', - favicon: 'img/hippo4j_favicon.ico', - // GitHub pages deployment config. - // If you aren't using GitHub pages, you don't need these. - organizationName: 'hippo4j', // Usually your GitHub org/user name. - projectName: 'hippo4j.github.io', // Usually your repo name. - deploymentBranch: "main", + title: 'Hippo4j', + tagline: '动态可观测线程池框架,为业务系统提高线上运行保障能力', + url: 'https://hippo4j.cn', + baseUrl: '/', + onBrokenLinks: 'throw', + onBrokenMarkdownLinks: 'warn', + favicon: 'img/hippo4j_favicon.ico', + // GitHub pages deployment config. + // If you aren't using GitHub pages, you don't need these. + organizationName: 'hippo4j', // Usually your GitHub org/user name. + projectName: 'hippo4j.github.io', // Usually your repo name. + deploymentBranch: 'main', - // Even if you don't use internalization, you can use this field to set useful - // metadata like html lang. For example, if your site is Chinese, you may want - // to replace "en" with "zh-Hans". + // Even if you don't use internalization, you can use this field to set useful + // metadata like html lang. For example, if your site is Chinese, you may want + // to replace "en" with "zh-Hans". i18n: { - defaultLocale: "en", - locales: ["en", "zh"], + defaultLocale: 'en', + locales: ['en', 'zh'], localeConfigs: { en: { - label: "English", - direction: "ltr", + label: 'English', + direction: 'ltr', }, zh: { - label: "简体中文", - direction: "ltr", + label: '简体中文', + direction: 'ltr', }, }, }, - presets: [ - [ - 'classic', - /** @type {import('@docusaurus/preset-classic').Options} */ - ({ - docs: { - sidebarPath: require.resolve('./sidebars.js'), - // Please change this to your repo. - // Remove this to remove the "edit this page" links. - sidebarCollapsed: false, - /*editUrl: 'https://github.com/longtai-cn',*/ - }, - blog: { - showReadingTime: true, - // Please change this to your repo. - // Remove this to remove the "edit this page" links. - editUrl: - 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', - }, - theme: { - customCss: require.resolve('./src/css/custom.css'), - }, - }), - ], + presets: [ + [ + 'classic', + /** @type {import('@docusaurus/preset-classic').Options} */ + ({ + docs: { + sidebarPath: require.resolve('./sidebars.js'), + // Please change this to your repo. + // Remove this to remove the "edit this page" links. + sidebarCollapsed: false, + /*editUrl: 'https://github.com/longtai-cn',*/ + }, + blog: { + showReadingTime: true, + // Please change this to your repo. + // Remove this to remove the "edit this page" links. + editUrl: + 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', + }, + theme: { + customCss: require.resolve('./src/css/custom.css'), + }, + }), ], - - plugins: [ - [ - "@docusaurus/plugin-content-docs", - { - id: "community", - path: "community", - routeBasePath: "community", - sidebarPath: require.resolve("./sidebarsCommunity.js"), - }, - ], + ], + + plugins: [ + [ + '@docusaurus/plugin-content-docs', + { + id: 'community', + path: 'community', + routeBasePath: 'community', + sidebarPath: require.resolve('./sidebarsCommunity.js'), + }, ], + ], - themeConfig: + themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ - ({ - autoCollapseCategories: true, - announcementBar: { - id: 'announcementBar-1', // Increment on change - // content: `⭐️ If you like hippo4j, give it a star on Gitee, thanks.`, - // content: `⭐️ 如果您喜欢 hippo4j,请在 GiteeGitHub 上给它一个 star,谢谢!`, - content: `⭐️ 开源不易,hippo4j 如果对您工作有帮助,请在 GitHub 上给它一个 🌟`, - // content: `👉 《小马哥的代码实战课》官方知识星球来啦!!!`, - }, - navbar: { - title: '', - logo: { - alt: 'Hippo4j 动态可观测线程池框架', - src: 'img/hippo4j.png', - }, - items: [ - { - type: 'docSidebar', - docId: 'intro', - position: 'left', - sidebarId: 'user_docs', - label: '文档', - }, - { - to: "/community/contributor-guide", - label: "社区", - position: "left", - activeBaseRegex: `/community/`, - }, - /*{ to: "/team", label: "团队", position: "left" },*/ - { to: "/users", label: "采用公司", position: "left" }, - { to: "/group", label: "加群沟通", position: "left" }, - /*{to: '/blog', label: '博客', position: 'left'},*/ - { - href: 'http://console.hippo4j.cn/index.html', - label: '控制台样例', - position: 'left', - }, - { - href: 'https://gitee.com/opengoofy/congomall', - label: '👉 刚果商城', - position: 'left', - }, - { - type: 'docsVersionDropdown', - position: 'right', - dropdownActiveClassDisabled: true, - }, + ({ + autoCollapseCategories: true, + announcementBar: { + id: 'announcementBar-1', // Increment on change + // content: `⭐️ If you like hippo4j, give it a star on Gitee, thanks.`, + // content: `⭐️ 如果您喜欢 hippo4j,请在 GiteeGitHub 上给它一个 star,谢谢!`, + content: `⭐️ 开源不易,如果 Hippo4j 对您有帮助,请在 GitHub 上给它一个 Star 🌟`, + // content: `👉 《小马哥的代码实战课》官方知识星球来啦!!!`, + }, + navbar: { + title: '', + logo: { + alt: 'Hippo4j 动态可观测线程池框架', + src: 'img/hippo4j.png', + }, + items: [ + { + type: 'docSidebar', + docId: 'intro', + position: 'left', + sidebarId: 'user_docs', + label: '文档', + }, + { + to: '/community/contributor-guide', + label: '社区', + position: 'left', + activeBaseRegex: `/community/`, + }, + /*{ to: "/team", label: "团队", position: "left" },*/ + { to: '/users', label: '采用公司', position: 'left' }, + { to: '/group', label: '加群沟通', position: 'left' }, + /*{to: '/blog', label: '博客', position: 'left'},*/ + { + href: 'http://console.hippo4j.cn/index.html', + label: '控制台样例', + position: 'left', + }, + { + href: 'https://gitee.com/opengoofy/congomall', + label: '👉 刚果商城', + position: 'left', + }, + { + type: 'docsVersionDropdown', + position: 'right', + dropdownActiveClassDisabled: true, + }, - {type: 'localeDropdown', position: 'right'}, - /*{ + { type: 'localeDropdown', position: 'right' }, + /*{ href: 'https://gitee.com/mabaiwancn/hippo4j', label: 'Gitee', position: 'right', },*/ - { - href: 'https://github.com/opengoofy/hippo4j', - className: 'header-github-link', - 'aria-label': 'GitHub repository', - position: 'right', - }, + { + href: 'https://github.com/opengoofy/hippo4j', + className: 'header-github-link', + 'aria-label': 'GitHub repository', + position: 'right', + }, - /*{ + /*{ href: 'https://github.com/opengoofy/hippo4j', label: 'GitHub', position: 'right', },*/ - ], - }, - footer: { - style: 'dark', - links: [ - { - title: 'Docs', - items: [ - { - label: 'Intro', - to: '/docs/user_docs/intro', - }, - { - label: 'Config Mode', - to: '/docs/user_docs/getting_started/config/hippo4j-config-start', - }, - { - label: 'Server Mode', - to: '/docs/user_docs/getting_started/server/hippo4j-server-start', - }, - ], - }, - { - title: 'Community', - items: [ - { - label: 'Group', - href: 'https://hippo4j.cn/group', - }, - { - label: 'WeChat', - href: 'https://mp.weixin.qq.com/s/diVHYvwiuYH9aWpZDPc27g', - }, - ], - }, - { - title: 'More', - items: [ - { - label: 'Gitee', - href: 'https://gitee.com/opengoofy/hippo4j', - }, - { - label: 'GitHub', - href: 'https://github.com/opengoofy/hippo4j', - }, - ], - }, - { - title: 'Links', - items: [ - { - label: '书源', - href: 'https://bookyuan.cn/', - }, - { - label: '推广合作', - href: 'https://hippo4j.cn/docs/user_docs/other/operation', - }, - ], - }, - ], - copyright: `Copyright © 2021-2022 马丁版权所有 京ICP备2021038095号 + ], + }, + footer: { + style: 'dark', + links: [ + { + title: 'Docs', + items: [ + { + label: 'Intro', + to: '/docs/user_docs/intro', + }, + { + label: 'Config Mode', + to: '/docs/user_docs/getting_started/config/hippo4j-config-start', + }, + { + label: 'Server Mode', + to: '/docs/user_docs/getting_started/server/hippo4j-server-start', + }, + ], + }, + { + title: 'Community', + items: [ + { + label: 'Group', + href: 'https://hippo4j.cn/group', + }, + { + label: 'WeChat', + href: 'https://mp.weixin.qq.com/s/diVHYvwiuYH9aWpZDPc27g', + }, + ], + }, + { + title: 'More', + items: [ + { + label: 'Gitee', + href: 'https://gitee.com/opengoofy/hippo4j', + }, + { + label: 'GitHub', + href: 'https://github.com/opengoofy/hippo4j', + }, + ], + }, + { + title: 'Links', + items: [ + { + label: '书源', + href: 'https://bookyuan.cn/', + }, + { + label: '推广合作', + href: 'https://hippo4j.cn/docs/user_docs/other/operation', + }, + ], + }, + ], + copyright: `Copyright © 2021-2022 马丁版权所有 京ICP备2021038095号 `, - }, - prism: { - theme: lightCodeTheme, - darkTheme: darkCodeTheme, - additionalLanguages: ['java'], - }, - }), + }, + prism: { + theme: lightCodeTheme, + darkTheme: darkCodeTheme, + additionalLanguages: ['java'], + }, + }), }; module.exports = config; diff --git a/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/getting_started/config/hippo4j-config-more.md b/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/getting_started/config/hippo4j-config-more.md index 2511b4f3..09452013 100644 --- a/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/getting_started/config/hippo4j-config-more.md +++ b/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/getting_started/config/hippo4j-config-more.md @@ -32,7 +32,7 @@ sidebar_position: 3 spring: dynamic: thread-pool: - tomcat: + web: enable: true executors: - thread-pool-id: message-consume @@ -50,7 +50,7 @@ spring: spring: dynamic: thread-pool: - tomcat: + web: nodes: 192.168.1.5:*,192.168.1.6:8080 executors: - thread-pool-id: message-consume diff --git a/docs/src/components/HomepageFeatures/index.js b/docs/src/components/HomepageFeatures/index.js index 10b5d288..1cd3ab96 100644 --- a/docs/src/components/HomepageFeatures/index.js +++ b/docs/src/components/HomepageFeatures/index.js @@ -3,59 +3,60 @@ import clsx from 'clsx'; import styles from './styles.module.css'; const FeatureList = [ - { - title: '动态变更', - Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default, - description: ( - <> - 应用运行时动态变更线程池参数,包括不限于核心、最大线程、阻塞队列大小和拒绝策略等,支持应用集群下不同节点线程池配置差异化 - - ), - }, - { - title: '自定义报警', - Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default, - description: ( - <> - 应用线程池运行时埋点,提供四种报警维度,线程池过载、阻塞队列容量、运行超长以及拒绝策略报警,并支持自定义时间内不重复报警 - - ), - }, - { - title: '运行监控', - Svg: require('@site/static/img/undraw_docusaurus_react.svg').default, - description: ( - <> - 支持自定义时长线程池运行数据采集存储,同时也支持 Prometheus、InfluxDB 等采集监控,通过 Grafana 或内置监控页面提供可视化大屏监控运行指标 - - ), - }, + { + title: '动态变更', + Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default, + description: ( + <> + 应用运行时动态变更线程池参数,包括不限于核心、最大线程、阻塞队列大小和拒绝策略等,支持应用集群下不同节点线程池配置差异化 + + ), + }, + { + title: '自定义报警', + Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default, + description: ( + <> + 应用线程池运行时埋点,提供四种报警维度,线程池过载、阻塞队列容量、运行超长以及拒绝策略报警,并支持自定义时间内不重复报警 + + ), + }, + { + title: '运行监控', + Svg: require('@site/static/img/undraw_docusaurus_react.svg').default, + description: ( + <> + 支持自定义时长线程池运行数据采集存储,同时也支持 Prometheus、InfluxDB 等采集监控,通过 + Grafana 或内置监控页面提供可视化大屏监控运行指标 + + ), + }, ]; -function Feature({Svg, title, description}) { - return ( -
-
- -
-
-

{title}

-

{description}

-
-
- ); +function Feature({ Svg, title, description }) { + return ( +
+
+ +
+
+

{title}

+

{description}

+
+
+ ); } export default function HomepageFeatures() { - return ( -
-
-
- {FeatureList.map((props, idx) => ( - - ))} -
-
-
- ); + return ( +
+
+
+ {FeatureList.map((props, idx) => ( + + ))} +
+
+
+ ); } diff --git a/docs/src/pages/index.js b/docs/src/pages/index.js index a1bdfacc..0c5bdc7a 100644 --- a/docs/src/pages/index.js +++ b/docs/src/pages/index.js @@ -5,38 +5,48 @@ import Translate from '@docusaurus/Translate'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; +import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import styles from './index.module.css'; +if (ExecutionEnvironment.canUseDOM) { + var _hmt = _hmt || []; + (function () { + var hm = document.createElement('script'); + hm.src = 'https://hm.baidu.com/hm.js?473eaadc06f3d63771f303df1fc29b58'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(hm, s); + })(); +} + function HomepageHeader() { - const {siteConfig} = useDocusaurusContext(); - return ( -
-
-

{siteConfig.title}

-

{siteConfig.tagline}

-
- - 快速开始 - 5min ⏱️ - -
-
-
- ); + const { siteConfig } = useDocusaurusContext(); + return ( +
+
+

{siteConfig.title}

+

{siteConfig.tagline}

+
+ + 快速开始 - 5min ⏱️ + +
+
+
+ ); } export default function Home() { - const {siteConfig} = useDocusaurusContext(); - return ( - - -
- -
-
- ); + const { siteConfig } = useDocusaurusContext(); + return ( + + +
+ +
+
+ ); } diff --git a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/HystrixThreadPoolAdapter4Server.java b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/HystrixThreadPoolAdapter4Server.java index 0c8ec370..4a187a47 100644 --- a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/HystrixThreadPoolAdapter4Server.java +++ b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/HystrixThreadPoolAdapter4Server.java @@ -19,29 +19,20 @@ package cn.hippo4j.adapter.hystrix; import cn.hippo4j.adapter.base.ThreadPoolAdapter; import cn.hippo4j.adapter.base.ThreadPoolAdapterCacheConfig; -import cn.hippo4j.adapter.base.ThreadPoolAdapterParameter; import cn.hippo4j.adapter.base.ThreadPoolAdapterRegisterAction; import cn.hippo4j.adapter.base.ThreadPoolAdapterState; import cn.hippo4j.common.config.ApplicationContextHolder; -import cn.hippo4j.common.toolkit.CollectionUtil; -import com.netflix.hystrix.HystrixThreadPool; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationStartedEvent; -import org.springframework.context.ApplicationListener; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER; - /** * hystrix thread-pool adapter for hippo4j server. */ diff --git a/hippo4j-adapter/hippo4j-adapter-kafka/src/main/java/cn/hippo4j/adapter/kafka/KafkaThreadPoolAdapter.java b/hippo4j-adapter/hippo4j-adapter-kafka/src/main/java/cn/hippo4j/adapter/kafka/KafkaThreadPoolAdapter.java index 21e417ac..1a2be842 100644 --- a/hippo4j-adapter/hippo4j-adapter-kafka/src/main/java/cn/hippo4j/adapter/kafka/KafkaThreadPoolAdapter.java +++ b/hippo4j-adapter/hippo4j-adapter-kafka/src/main/java/cn/hippo4j/adapter/kafka/KafkaThreadPoolAdapter.java @@ -151,8 +151,8 @@ public class KafkaThreadPoolAdapter implements ThreadPoolAdapter, ApplicationLis ContainerProperties containerProperties = concurrentContainer.getContainerProperties(); TopicPartitionOffset[] topicPartitions = containerProperties.getTopicPartitions(); if (topicPartitions != null && concurrency > topicPartitions.length) { - log.warn("[{}] Kafka consuming thread pool not support modify. " + - "When specific partitions are provided, the concurrency must be less than or " + log.warn("[{}] Kafka consuming thread pool not support modify. " + + "When specific partitions are provided, the concurrency must be less than or " + "equal to the number of partitions;", threadPoolKey); return false; } diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/DefaultAbstractWebThreadPoolService.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/DefaultAbstractWebThreadPoolService.java index e519c5b6..4d472c23 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/DefaultAbstractWebThreadPoolService.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/DefaultAbstractWebThreadPoolService.java @@ -22,9 +22,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.context.WebServerApplicationContext; import org.springframework.boot.web.server.WebServer; import org.springframework.context.ApplicationContext; -import org.springframework.util.ReflectionUtils; -import java.lang.reflect.Field; import java.util.concurrent.Executor; /** diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolHandlerChoose.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolHandlerChoose.java index 3b08bdb2..1d94d379 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolHandlerChoose.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolHandlerChoose.java @@ -17,7 +17,6 @@ package cn.hippo4j.adapter.web; -import cn.hippo4j.adapter.web.WebThreadPoolService; import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.web.exception.ServiceException; import lombok.extern.slf4j.Slf4j; diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/tomcat/DefaultTomcatWebThreadPoolHandler.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/tomcat/DefaultTomcatWebThreadPoolHandler.java index 601385da..b2461990 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/tomcat/DefaultTomcatWebThreadPoolHandler.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/tomcat/DefaultTomcatWebThreadPoolHandler.java @@ -18,12 +18,6 @@ package cn.hippo4j.adapter.web.tomcat; import cn.hippo4j.adapter.web.DefaultAbstractWebThreadPoolService; -import cn.hippo4j.adapter.web.IWebThreadPoolHandlerSupport; -import cn.hippo4j.common.enums.WebContainerEnum; -import cn.hippo4j.common.model.ThreadPoolBaseInfo; -import cn.hippo4j.common.model.ThreadPoolParameter; -import cn.hippo4j.common.model.ThreadPoolParameterInfo; -import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; diff --git a/hippo4j-agent/config/agent.config b/hippo4j-agent/config/agent.config new file mode 100755 index 00000000..e3d54559 --- /dev/null +++ b/hippo4j-agent/config/agent.config @@ -0,0 +1,274 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The service name in UI +# ${service name} = [${group name}::]${logic name} +# The group name is optional only. +agent.service_name=${SW_AGENT_NAME:Your_ApplicationName} + +# The agent namespace +agent.namespace=${SW_AGENT_NAMESPACE:} + +# The agent cluster +agent.cluster=${SW_AGENT_CLUSTER:} + +# The number of sampled traces per 3 seconds +# Negative or zero means off, by default +agent.sample_n_per_3_secs=${SW_AGENT_SAMPLE:-1} + +# Authentication active is based on backend setting, see application.yml for more details. +agent.authentication=${SW_AGENT_AUTHENTICATION:} + +# The max number of TraceSegmentRef in a single span to keep memory cost estimatable. +agent.trace_segment_ref_limit_per_span=${SW_TRACE_SEGMENT_LIMIT:500} + +# The max amount of spans in a single segment. +# Through this config item, SkyWalking keep your application memory cost estimated. +agent.span_limit_per_segment=${SW_AGENT_SPAN_LIMIT:300} + +# If the operation name of the first span is included in this set, this segment should be ignored. Multiple values should be separated by `,`. +agent.ignore_suffix=${SW_AGENT_IGNORE_SUFFIX:.jpg,.jpeg,.js,.css,.png,.bmp,.gif,.ico,.mp3,.mp4,.html,.svg} + +# If true, SkyWalking agent will save all instrumented classes files in `/debugging` folder. +# SkyWalking team may ask for these files in order to resolve compatible problem. +agent.is_open_debugging_class=${SW_AGENT_OPEN_DEBUG:false} + +# If true, SkyWalking agent will cache all instrumented classes files to memory or disk files (decided by class cache mode), +# allow other javaagent to enhance those classes that enhanced by SkyWalking agent. +agent.is_cache_enhanced_class=${SW_AGENT_CACHE_CLASS:false} + +# The instrumented classes cache mode: MEMORY or FILE +# MEMORY: cache class bytes to memory, if instrumented classes is too many or too large, it may take up more memory +# FILE: cache class bytes in `/class-cache` folder, automatically clean up cached class files when the application exits +agent.class_cache_mode=${SW_AGENT_CLASS_CACHE_MODE:MEMORY} + +# Instance name is the identity of an instance, should be unique in the service. If empty, SkyWalking agent will +# generate an 32-bit uuid. BY Default, SkyWalking uses UUID@hostname as the instance name. Max length is 50(UTF-8 char) +agent.instance_name=${SW_AGENT_INSTANCE_NAME:} + +# service instance properties in json format. e.g. agent.instance_properties_json = {"org": "apache-skywalking"} +agent.instance_properties_json=${SW_INSTANCE_PROPERTIES_JSON:} + +# How depth the agent goes, when log all cause exceptions. +agent.cause_exception_depth=${SW_AGENT_CAUSE_EXCEPTION_DEPTH:5} + +# Force reconnection period of grpc, based on grpc_channel_check_interval. +agent.force_reconnection_period=${SW_AGENT_FORCE_RECONNECTION_PERIOD:1} + +# The operationName max length +# Notice, in the current practice, we don't recommend the length over 190. +agent.operation_name_threshold=${SW_AGENT_OPERATION_NAME_THRESHOLD:150} + +# Keep tracing even the backend is not available if this value is true. +agent.keep_tracing=${SW_AGENT_KEEP_TRACING:false} + +# The agent use gRPC plain text in default. +# If true, SkyWalking agent uses TLS even no CA file detected. +agent.force_tls=${SW_AGENT_FORCE_TLS:false} + +# gRPC SSL trusted ca file. +agent.ssl_trusted_ca_path=${SW_AGENT_SSL_TRUSTED_CA_PATH:/ca/ca.crt} + +# enable mTLS when ssl_key_path and ssl_cert_chain_path exist. +agent.ssl_key_path=${SW_AGENT_SSL_KEY_PATH:} + +agent.ssl_cert_chain_path=${SW_AGENT_SSL_CERT_CHAIN_PATH:} + +# Limit the length of the ipv4 list size. +osinfo.ipv4_list_size=${SW_AGENT_OSINFO_IPV4_LIST_SIZE:10} + +# grpc channel status check interval. +collector.grpc_channel_check_interval=${SW_AGENT_COLLECTOR_GRPC_CHANNEL_CHECK_INTERVAL:30} +# Agent heartbeat report period. Unit, second. +collector.heartbeat_period=${SW_AGENT_COLLECTOR_HEARTBEAT_PERIOD:30} +# The agent sends the instance properties to the backend every +# collector.heartbeat_period * collector.properties_report_period_factor seconds +collector.properties_report_period_factor=${SW_AGENT_COLLECTOR_PROPERTIES_REPORT_PERIOD_FACTOR:10} +# Backend service addresses. +collector.backend_service=${SW_AGENT_COLLECTOR_BACKEND_SERVICES:127.0.0.1:11800} +# How long grpc client will timeout in sending data to upstream. Unit is second. +collector.grpc_upstream_timeout=${SW_AGENT_COLLECTOR_GRPC_UPSTREAM_TIMEOUT:30} +# Sniffer get profile task list interval. +collector.get_profile_task_interval=${SW_AGENT_COLLECTOR_GET_PROFILE_TASK_INTERVAL:20} +# Sniffer get agent dynamic config interval. +collector.get_agent_dynamic_config_interval=${SW_AGENT_COLLECTOR_GET_AGENT_DYNAMIC_CONFIG_INTERVAL:20} +# If true, skywalking agent will enable periodically resolving DNS to update receiver service addresses. +collector.is_resolve_dns_periodically=${SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIODICALLY:false} + +# Logging level +logging.level=${SW_LOGGING_LEVEL:INFO} +# Logging file_name +logging.file_name=${SW_LOGGING_FILE_NAME:skywalking-api.log} +# Log output. Default is FILE. Use CONSOLE means output to stdout. +logging.output=${SW_LOGGING_OUTPUT:FILE} +# Log files directory. Default is blank string, meaning use "{theSkywalkingAgentJarDir}/logs " to output logs. +# {theSkywalkingAgentJarDir} is the directory where the skywalking agent jar file is located +logging.dir=${SW_LOGGING_DIR:} +# Logger resolver: PATTERN or JSON. The default is PATTERN, which uses logging.pattern to print traditional text logs. +# JSON resolver prints logs in JSON format. +logging.resolver=${SW_LOGGING_RESOLVER:PATTERN} +# Logging format. There are all conversion specifiers: +# * %level means log level. +# * %timestamp means now of time with format yyyy-MM-dd HH:mm:ss:SSS. +# * %thread means name of current thread. +# * %msg means some message which user logged. +# * %class means SimpleName of TargetClass. +# * %throwable means a throwable which user called. +# * %agent_name means agent.service_name. Only apply to the PatternLogger. +logging.pattern=${SW_LOGGING_PATTERN:%level %timestamp %thread %class : %msg %throwable} +# Logging max_file_size, default: 300 * 1024 * 1024 = 314572800 +logging.max_file_size=${SW_LOGGING_MAX_FILE_SIZE:314572800} +# The max history log files. When rollover happened, if log files exceed this number, +# then the oldest file will be delete. Negative or zero means off, by default. +logging.max_history_files=${SW_LOGGING_MAX_HISTORY_FILES:-1} + +# Listed exceptions would not be treated as an error. Because in some codes, the exception is being used as a way of controlling business flow. +# Besides, the annotation named IgnoredException in the trace toolkit is another way to configure ignored exceptions. +statuscheck.ignored_exceptions=${SW_STATUSCHECK_IGNORED_EXCEPTIONS:} +# The max recursive depth when checking the exception traced by the agent. Typically, we don't recommend setting this more than 10, which could cause a performance issue. Negative value and 0 would be ignored, which means all exceptions would make the span tagged in error status. +statuscheck.max_recursive_depth=${SW_STATUSCHECK_MAX_RECURSIVE_DEPTH:1} + +# Max element count in the correlation context +correlation.element_max_number=${SW_CORRELATION_ELEMENT_MAX_NUMBER:3} + +# Max value length of each element. +correlation.value_max_length=${SW_CORRELATION_VALUE_MAX_LENGTH:128} +# Tag the span by the key/value in the correlation context, when the keys listed here exist. +correlation.auto_tag_keys=${SW_CORRELATION_AUTO_TAG_KEYS:} +# The buffer size of collected JVM info. +jvm.buffer_size=${SW_JVM_BUFFER_SIZE:600} +# The buffer channel size. +buffer.channel_size=${SW_BUFFER_CHANNEL_SIZE:5} +# The buffer size. +buffer.buffer_size=${SW_BUFFER_BUFFER_SIZE:300} +# If true, skywalking agent will enable profile when user create a new profile task. Otherwise disable profile. +profile.active=${SW_AGENT_PROFILE_ACTIVE:true} +# Parallel monitor segment count +profile.max_parallel=${SW_AGENT_PROFILE_MAX_PARALLEL:5} +# Max monitor segment time(minutes), if current segment monitor time out of limit, then stop it. +profile.duration=${SW_AGENT_PROFILE_DURATION:10} +# Max dump thread stack depth +profile.dump_max_stack_depth=${SW_AGENT_PROFILE_DUMP_MAX_STACK_DEPTH:500} +# Snapshot transport to backend buffer size +profile.snapshot_transport_buffer_size=${SW_AGENT_PROFILE_SNAPSHOT_TRANSPORT_BUFFER_SIZE:4500} +# If true, the agent collects and reports metrics to the backend. +meter.active=${SW_METER_ACTIVE:true} +# Report meters interval. The unit is second +meter.report_interval=${SW_METER_REPORT_INTERVAL:20} +# Max size of the meter pool +meter.max_meter_size=${SW_METER_MAX_METER_SIZE:500} +# The max size of message to send to server.Default is 10 MB +log.max_message_size=${SW_GRPC_LOG_MAX_MESSAGE_SIZE:10485760} + +# Mount the specific folders of the plugins. Plugins in mounted folders would work. +plugin.mount=${SW_MOUNT_FOLDERS:plugins,activations} +# Peer maximum description limit. +plugin.peer_max_length=${SW_PLUGIN_PEER_MAX_LENGTH:200} +# Exclude some plugins define in plugins dir.Plugin names is defined in [Agent plugin list](Plugin-list.md) +plugin.exclude_plugins=${SW_EXCLUDE_PLUGINS:} +# If true, trace all the parameters in MongoDB access, default is false. Only trace the operation, not include parameters. +plugin.mongodb.trace_param=${SW_PLUGIN_MONGODB_TRACE_PARAM:false} +# If set to positive number, the `WriteRequest.params` would be truncated to this length, otherwise it would be completely saved, which may cause performance problem. +plugin.mongodb.filter_length_limit=${SW_PLUGIN_MONGODB_FILTER_LENGTH_LIMIT:256} +# If true, trace all the DSL(Domain Specific Language) in ElasticSearch access, default is false. +plugin.elasticsearch.trace_dsl=${SW_PLUGIN_ELASTICSEARCH_TRACE_DSL:false} +# If true, the fully qualified method name will be used as the endpoint name instead of the request URL, default is false. +plugin.springmvc.use_qualified_name_as_endpoint_name=${SW_PLUGIN_SPRINGMVC_USE_QUALIFIED_NAME_AS_ENDPOINT_NAME:false} +# If true, the fully qualified method name will be used as the operation name instead of the given operation name, default is false. +plugin.toolit.use_qualified_name_as_operation_name=${SW_PLUGIN_TOOLIT_USE_QUALIFIED_NAME_AS_OPERATION_NAME:false} +# If set to true, the parameters of the sql (typically `java.sql.PreparedStatement`) would be collected. +plugin.jdbc.trace_sql_parameters=${SW_JDBC_TRACE_SQL_PARAMETERS:false} +# If set to positive number, the `db.sql.parameters` would be truncated to this length, otherwise it would be completely saved, which may cause performance problem. +plugin.jdbc.sql_parameters_max_length=${SW_PLUGIN_JDBC_SQL_PARAMETERS_MAX_LENGTH:512} +# If set to positive number, the `db.statement` would be truncated to this length, otherwise it would be completely saved, which may cause performance problem. +plugin.jdbc.sql_body_max_length=${SW_PLUGIN_JDBC_SQL_BODY_MAX_LENGTH:2048} +# If true, trace all the query parameters(include deleteByIds and deleteByQuery) in Solr query request, default is false. +plugin.solrj.trace_statement=${SW_PLUGIN_SOLRJ_TRACE_STATEMENT:false} +# If true, trace all the operation parameters in Solr request, default is false. +plugin.solrj.trace_ops_params=${SW_PLUGIN_SOLRJ_TRACE_OPS_PARAMS:false} +# If true, trace all middleware/business handlers that are part of the Light4J handler chain for a request. +plugin.light4j.trace_handler_chain=${SW_PLUGIN_LIGHT4J_TRACE_HANDLER_CHAIN:false} +# If true, the transaction definition name will be simplified. +plugin.springtransaction.simplify_transaction_definition_name=${SW_PLUGIN_SPRINGTRANSACTION_SIMPLIFY_TRANSACTION_DEFINITION_NAME:false} +# Threading classes (`java.lang.Runnable` and `java.util.concurrent.Callable`) and their subclasses, including anonymous inner classes whose name match any one of the `THREADING_CLASS_PREFIXES` (splitted by `,`) will be instrumented, make sure to only specify as narrow prefixes as what you're expecting to instrument, (`java.` and `javax.` will be ignored due to safety issues) +plugin.jdkthreading.threading_class_prefixes=${SW_PLUGIN_JDKTHREADING_THREADING_CLASS_PREFIXES:} +# This config item controls that whether the Tomcat plugin should collect the parameters of the request. Also, activate implicitly in the profiled trace. +plugin.tomcat.collect_http_params=${SW_PLUGIN_TOMCAT_COLLECT_HTTP_PARAMS:false} +# This config item controls that whether the SpringMVC plugin should collect the parameters of the request, when your Spring application is based on Tomcat, consider only setting either `plugin.tomcat.collect_http_params` or `plugin.springmvc.collect_http_params`. Also, activate implicitly in the profiled trace. +plugin.springmvc.collect_http_params=${SW_PLUGIN_SPRINGMVC_COLLECT_HTTP_PARAMS:false} +# This config item controls that whether the HttpClient plugin should collect the parameters of the request +plugin.httpclient.collect_http_params=${SW_PLUGIN_HTTPCLIENT_COLLECT_HTTP_PARAMS:false} +# When `COLLECT_HTTP_PARAMS` is enabled, how many characters to keep and send to the OAP backend, use negative values to keep and send the complete parameters, NB. this config item is added for the sake of performance. +plugin.http.http_params_length_threshold=${SW_PLUGIN_HTTP_HTTP_PARAMS_LENGTH_THRESHOLD:1024} +# When `include_http_headers` declares header names, this threshold controls the length limitation of all header values. use negative values to keep and send the complete headers. Note. this config item is added for the sake of performance. +plugin.http.http_headers_length_threshold=${SW_PLUGIN_HTTP_HTTP_HEADERS_LENGTH_THRESHOLD:2048} +# Set the header names, which should be collected by the plugin. Header name must follow `javax.servlet.http` definition. Multiple names should be split by comma. +plugin.http.include_http_headers=${SW_PLUGIN_HTTP_INCLUDE_HTTP_HEADERS:} +# This config item controls that whether the Feign plugin should collect the http body of the request. +plugin.feign.collect_request_body=${SW_PLUGIN_FEIGN_COLLECT_REQUEST_BODY:false} +# When `COLLECT_REQUEST_BODY` is enabled, how many characters to keep and send to the OAP backend, use negative values to keep and send the complete body. +plugin.feign.filter_length_limit=${SW_PLUGIN_FEIGN_FILTER_LENGTH_LIMIT:1024} +# When `COLLECT_REQUEST_BODY` is enabled and content-type start with SUPPORTED_CONTENT_TYPES_PREFIX, collect the body of the request , multiple paths should be separated by `,` +plugin.feign.supported_content_types_prefix=${SW_PLUGIN_FEIGN_SUPPORTED_CONTENT_TYPES_PREFIX:application/json,text/} +# If true, trace all the influxql(query and write) in InfluxDB access, default is true. +plugin.influxdb.trace_influxql=${SW_PLUGIN_INFLUXDB_TRACE_INFLUXQL:true} +# Apache Dubbo consumer collect `arguments` in RPC call, use `Object#toString` to collect `arguments`. +plugin.dubbo.collect_consumer_arguments=${SW_PLUGIN_DUBBO_COLLECT_CONSUMER_ARGUMENTS:false} +# When `plugin.dubbo.collect_consumer_arguments` is `true`, Arguments of length from the front will to the OAP backend +plugin.dubbo.consumer_arguments_length_threshold=${SW_PLUGIN_DUBBO_CONSUMER_ARGUMENTS_LENGTH_THRESHOLD:256} +# Apache Dubbo provider collect `arguments` in RPC call, use `Object#toString` to collect `arguments`. +plugin.dubbo.collect_provider_arguments=${SW_PLUGIN_DUBBO_COLLECT_PROVIDER_ARGUMENTS:false} +# When `plugin.dubbo.collect_provider_arguments` is `true`, Arguments of length from the front will to the OAP backend +plugin.dubbo.provider_arguments_length_threshold=${SW_PLUGIN_DUBBO_PROVIDER_ARGUMENTS_LENGTH_THRESHOLD:256} +# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. +plugin.kafka.bootstrap_servers=${SW_KAFKA_BOOTSTRAP_SERVERS:localhost:9092} +# Timeout period of reading topics from the Kafka server, the unit is second. +plugin.kafka.get_topic_timeout=${SW_GET_TOPIC_TIMEOUT:10} +# Kafka producer configuration. Read [producer configure](http://kafka.apache.org/24/documentation.html#producerconfigs) +# to get more details. Check document for more details and examples. +plugin.kafka.producer_config=${sw_plugin_kafka_producer_config:} +# Configure Kafka Producer configuration in JSON format. Notice it will be overridden by plugin.kafka.producer_config[key], if the key duplication. +plugin.kafka.producer_config_json=${SW_PLUGIN_KAFKA_PRODUCER_CONFIG_JSON:} +# Specify which Kafka topic name for Meter System data to report to. +plugin.kafka.topic_meter=${SW_PLUGIN_KAFKA_TOPIC_METER:skywalking-meters} +# Specify which Kafka topic name for JVM metrics data to report to. +plugin.kafka.topic_metrics=${SW_PLUGIN_KAFKA_TOPIC_METRICS:skywalking-metrics} +# Specify which Kafka topic name for traces data to report to. +plugin.kafka.topic_segment=${SW_PLUGIN_KAFKA_TOPIC_SEGMENT:skywalking-segments} +# Specify which Kafka topic name for Thread Profiling snapshot to report to. +plugin.kafka.topic_profiling=${SW_PLUGIN_KAFKA_TOPIC_PROFILINGS:skywalking-profilings} +# Specify which Kafka topic name for the register or heartbeat data of Service Instance to report to. +plugin.kafka.topic_management=${SW_PLUGIN_KAFKA_TOPIC_MANAGEMENT:skywalking-managements} +# Specify which Kafka topic name for the logging data to report to. +plugin.kafka.topic_logging=${SW_PLUGIN_KAFKA_TOPIC_LOGGING:skywalking-logs} +# isolate multi OAP server when using same Kafka cluster (final topic name will append namespace before Kafka topics with `-` ). +plugin.kafka.namespace=${SW_KAFKA_NAMESPACE:} +# Match spring beans with regular expression for the class name. Multiple expressions could be separated by a comma. This only works when `Spring annotation plugin` has been activated. +plugin.springannotation.classname_match_regex=${SW_SPRINGANNOTATION_CLASSNAME_MATCH_REGEX:} +# Whether or not to transmit logged data as formatted or un-formatted. +plugin.toolkit.log.transmit_formatted=${SW_PLUGIN_TOOLKIT_LOG_TRANSMIT_FORMATTED:true} +# If set to true, the parameters of Redis commands would be collected by Lettuce agent. +plugin.lettuce.trace_redis_parameters=${SW_PLUGIN_LETTUCE_TRACE_REDIS_PARAMETERS:false} +# If set to positive number and `plugin.lettuce.trace_redis_parameters` is set to `true`, Redis command parameters would be collected and truncated to this length. +plugin.lettuce.redis_parameter_max_length=${SW_PLUGIN_LETTUCE_REDIS_PARAMETER_MAX_LENGTH:128} +# If set to true, the parameters of the cypher would be collected. +plugin.neo4j.trace_cypher_parameters=${SW_PLUGIN_NEO4J_TRACE_CYPHER_PARAMETERS:false} +# If set to positive number, the `db.cypher.parameters` would be truncated to this length, otherwise it would be completely saved, which may cause performance problem. +plugin.neo4j.cypher_parameters_max_length=${SW_PLUGIN_NEO4J_CYPHER_PARAMETERS_MAX_LENGTH:512} +# If set to positive number, the `db.statement` would be truncated to this length, otherwise it would be completely saved, which may cause performance problem. +plugin.neo4j.cypher_body_max_length=${SW_PLUGIN_NEO4J_CYPHER_BODY_MAX_LENGTH:2048} +# If set to a positive number and activate `trace sampler CPU policy plugin`, the trace would not be collected when agent process CPU usage percent is greater than `plugin.cpupolicy.sample_cpu_usage_percent_limit`. +plugin.cpupolicy.sample_cpu_usage_percent_limit=${SW_SAMPLE_CPU_USAGE_PERCENT_LIMIT:-1} diff --git a/hippo4j-agent/dist-material/LICENSE b/hippo4j-agent/dist-material/LICENSE new file mode 100755 index 00000000..f84d20b7 --- /dev/null +++ b/hippo4j-agent/dist-material/LICENSE @@ -0,0 +1,232 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +======================================================================= +Apache SkyWalking Subcomponents: + +The Apache SkyWalking project contains subcomponents with separate copyright +notices and license terms. Your use of the source code for the these +subcomponents is subject to the terms and conditions of the following +licenses. + +======================================================================== +Apache 2.0 licenses +======================================================================== + +The following components are provided under the Apache License. See project link for details. +The text of each license is the standard Apache 2.0 license. + + raphw (byte-buddy) 1.12.13: http://bytebuddy.net/ , Apache 2.0 + Google: grpc-java 1.44.0: https://github.com/grpc/grpc-java, Apache 2.0 + Google: gson 2.8.9: https://github.com/google/gson , Apache 2.0 + Google: proto-google-common-protos 2.0.1: https://github.com/googleapis/googleapis , Apache 2.0 + Google: jsr305 3.0.2: http://central.maven.org/maven2/com/google/code/findbugs/jsr305/3.0.0/jsr305-3.0.0.pom , Apache 2.0 + netty 4.1.79: https://github.com/netty/netty/blob/4.1/LICENSE.txt, Apache 2.0 + +======================================================================== +BSD licenses +======================================================================== + +The following components are provided under a BSD license. See project link for details. +The text of each license is also included at licenses/LICENSE-[project].txt. + + asm 9.2:https://gitlab.ow2.org , BSD-3-Clause diff --git a/hippo4j-agent/dist-material/NOTICE b/hippo4j-agent/dist-material/NOTICE new file mode 100755 index 00000000..5b238489 --- /dev/null +++ b/hippo4j-agent/dist-material/NOTICE @@ -0,0 +1,299 @@ +Opengoofy Hippo4j +Copyright 2017-2022 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +======================================================================== + +grpc-java NOTICE + +======================================================================== +Copyright 2014, gRPC Authors All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +----------------------------------------------------------------------- + +This product contains a modified portion of 'OkHttp', an open source +HTTP & SPDY client for Android and Java applications, which can be obtained +at: + + * LICENSE: + * okhttp/third_party/okhttp/LICENSE (Apache License 2.0) + * HOMEPAGE: + * https://github.com/square/okhttp + * LOCATION_IN_GRPC: + * okhttp/third_party/okhttp + +This product contains a modified portion of 'Netty', an open source +networking library, which can be obtained at: + + * LICENSE: + * netty/third_party/netty/LICENSE.txt (Apache License 2.0) + * HOMEPAGE: + * https://netty.io + * LOCATION_IN_GRPC: + * netty/third_party/netty + +======================================================================== + +grpc NOTICE + +======================================================================== + +Copyright 2014 gRPC authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +======================================================================== + +netty NOTICE + +======================================================================== + + + The Netty Project + ================= + +Please visit the Netty web site for more information: + + * http://netty.io/ + +Copyright 2014 The Netty Project + +The Netty Project licenses this file to you under the Apache License, +version 2.0 (the "License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at: + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations +under the License. + +Also, please refer to each LICENSE..txt file, which is located in +the 'license' directory of the distribution file, for the license terms of the +components that this product depends on. + +------------------------------------------------------------------------------- +This product contains the extensions to Java Collections Framework which has +been derived from the works by JSR-166 EG, Doug Lea, and Jason T. Greene: + + * LICENSE: + * license/LICENSE.jsr166y.txt (Public Domain) + * HOMEPAGE: + * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/ + * http://viewvc.jboss.org/cgi-bin/viewvc.cgi/jbosscache/experimental/jsr166/ + +This product contains a modified version of Robert Harder's Public Domain +Base64 Encoder and Decoder, which can be obtained at: + + * LICENSE: + * license/LICENSE.base64.txt (Public Domain) + * HOMEPAGE: + * http://iharder.sourceforge.net/current/java/base64/ + +This product contains a modified portion of 'Webbit', an event based +WebSocket and HTTP server, which can be obtained at: + + * LICENSE: + * license/LICENSE.webbit.txt (BSD License) + * HOMEPAGE: + * https://github.com/joewalnes/webbit + +This product contains a modified portion of 'SLF4J', a simple logging +facade for Java, which can be obtained at: + + * LICENSE: + * license/LICENSE.slf4j.txt (MIT License) + * HOMEPAGE: + * http://www.slf4j.org/ + +This product contains a modified portion of 'Apache Harmony', an open source +Java SE, which can be obtained at: + + * NOTICE: + * license/NOTICE.harmony.txt + * LICENSE: + * license/LICENSE.harmony.txt (Apache License 2.0) + * HOMEPAGE: + * http://archive.apache.org/dist/harmony/ + +This product contains a modified portion of 'jbzip2', a Java bzip2 compression +and decompression library written by Matthew J. Francis. It can be obtained at: + + * LICENSE: + * license/LICENSE.jbzip2.txt (MIT License) + * HOMEPAGE: + * https://code.google.com/p/jbzip2/ + +This product contains a modified portion of 'libdivsufsort', a C API library to construct +the suffix array and the Burrows-Wheeler transformed string for any input string of +a constant-size alphabet written by Yuta Mori. It can be obtained at: + + * LICENSE: + * license/LICENSE.libdivsufsort.txt (MIT License) + * HOMEPAGE: + * https://github.com/y-256/libdivsufsort + +This product contains a modified portion of Nitsan Wakart's 'JCTools', Java Concurrency Tools for the JVM, + which can be obtained at: + + * LICENSE: + * license/LICENSE.jctools.txt (ASL2 License) + * HOMEPAGE: + * https://github.com/JCTools/JCTools + +This product optionally depends on 'JZlib', a re-implementation of zlib in +pure Java, which can be obtained at: + + * LICENSE: + * license/LICENSE.jzlib.txt (BSD style License) + * HOMEPAGE: + * http://www.jcraft.com/jzlib/ + +This product optionally depends on 'Compress-LZF', a Java library for encoding and +decoding data in LZF format, written by Tatu Saloranta. It can be obtained at: + + * LICENSE: + * license/LICENSE.compress-lzf.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/ning/compress + +This product optionally depends on 'lz4', a LZ4 Java compression +and decompression library written by Adrien Grand. It can be obtained at: + + * LICENSE: + * license/LICENSE.lz4.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/jpountz/lz4-java + +This product optionally depends on 'lzma-java', a LZMA Java compression +and decompression library, which can be obtained at: + + * LICENSE: + * license/LICENSE.lzma-java.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/jponge/lzma-java + +This product contains a modified portion of 'jfastlz', a Java port of FastLZ compression +and decompression library written by William Kinney. It can be obtained at: + + * LICENSE: + * license/LICENSE.jfastlz.txt (MIT License) + * HOMEPAGE: + * https://code.google.com/p/jfastlz/ + +This product contains a modified portion of and optionally depends on 'Protocol Buffers', Google's data +interchange format, which can be obtained at: + + * LICENSE: + * license/LICENSE.protobuf.txt (New BSD License) + * HOMEPAGE: + * https://github.com/google/protobuf + +This product optionally depends on 'Bouncy Castle Crypto APIs' to generate +a temporary self-signed X.509 certificate when the JVM does not provide the +equivalent functionality. It can be obtained at: + + * LICENSE: + * license/LICENSE.bouncycastle.txt (MIT License) + * HOMEPAGE: + * http://www.bouncycastle.org/ + +This product optionally depends on 'Snappy', a compression library produced +by Google Inc, which can be obtained at: + + * LICENSE: + * license/LICENSE.snappy.txt (New BSD License) + * HOMEPAGE: + * https://github.com/google/snappy + +This product optionally depends on 'JBoss Marshalling', an alternative Java +serialization API, which can be obtained at: + + * LICENSE: + * license/LICENSE.jboss-marshalling.txt (GNU LGPL 2.1) + * HOMEPAGE: + * http://www.jboss.org/jbossmarshalling + +This product optionally depends on 'Caliper', Google's micro- +benchmarking framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.caliper.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/google/caliper + +This product optionally depends on 'Apache Commons Logging', a logging +framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.commons-logging.txt (Apache License 2.0) + * HOMEPAGE: + * http://commons.apache.org/logging/ + +This product optionally depends on 'Apache Log4J', a logging framework, which +can be obtained at: + + * LICENSE: + * license/LICENSE.log4j.txt (Apache License 2.0) + * HOMEPAGE: + * http://logging.apache.org/log4j/ + +This product optionally depends on 'Aalto XML', an ultra-high performance +non-blocking XML processor, which can be obtained at: + + * LICENSE: + * license/LICENSE.aalto-xml.txt (Apache License 2.0) + * HOMEPAGE: + * http://wiki.fasterxml.com/AaltoHome + +This product contains a modified version of 'HPACK', a Java implementation of +the HTTP/2 HPACK algorithm written by Twitter. It can be obtained at: + + * LICENSE: + * license/LICENSE.hpack.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/twitter/hpack + +This product contains a modified portion of 'Apache Commons Lang', a Java library +provides utilities for the java.lang API, which can be obtained at: + + * LICENSE: + * license/LICENSE.commons-lang.txt (Apache License 2.0) + * HOMEPAGE: + * https://commons.apache.org/proper/commons-lang/ + + +This product contains the Maven wrapper scripts from 'Maven Wrapper', that provides an easy way to ensure a user has everything necessary to run the Maven build. + + * LICENSE: + * license/LICENSE.mvn-wrapper.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/takari/maven-wrapper + diff --git a/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml b/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml new file mode 100644 index 00000000..d313f6c9 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml @@ -0,0 +1,125 @@ + + + 4.0.0 + + cn.hippo4j + hippo4j-agent + ${revision} + + + hippo4j-agent-bootstrap + jar + + + UTF-8 + cn.hippo4j.agent.bootstrap.Hippo4jAgent + true + true + net.bytebuddy + ${shade.package}.${shade.net.bytebuddy.source} + + + + + cn.hippo4j + hippo4j-agent-core + + + + + hippo4j-agent + + + maven-shade-plugin + + + package + + shade + + + false + true + true + true + + + + ${premain.class} + ${can.redefine.classes} + ${can.retransform.classes} + + + + + + *:gson + io.grpc:* + io.netty:* + io.opencensus:* + com.google.*:* + com.google.guava:guava + org.checkerframework:checker-compat-qual + org.codehaus.mojo:animal-sniffer-annotations + io.perfmark:* + org.slf4j:* + + + + + ${shade.net.bytebuddy.source} + ${shade.net.bytebuddy.target} + + + + + net.bytebuddy:byte-buddy + + META-INF/versions/9/module-info.class + + + + + + + + + maven-antrun-plugin + + + clean + clean + + run + + + + + + + + + package + package + + run + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-bootstrap/src/main/java/cn/hippo4j/agent/bootstrap/Hippo4jAgent.java b/hippo4j-agent/hippo4j-agent-bootstrap/src/main/java/cn/hippo4j/agent/bootstrap/Hippo4jAgent.java new file mode 100644 index 00000000..afae5cc0 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-bootstrap/src/main/java/cn/hippo4j/agent/bootstrap/Hippo4jAgent.java @@ -0,0 +1,256 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.bootstrap; + +import cn.hippo4j.agent.core.boot.AgentPackageNotFoundException; +import cn.hippo4j.agent.core.boot.DefaultNamedThreadFactory; +import cn.hippo4j.agent.core.boot.ServiceManager; +import cn.hippo4j.agent.core.conf.Config; +import cn.hippo4j.agent.core.conf.SnifferConfigInitializer; +import cn.hippo4j.agent.core.jvm.LoadedLibraryCollector; +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.plugin.AbstractClassEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.EnhanceContext; +import cn.hippo4j.agent.core.plugin.InstrumentDebuggingClass; +import cn.hippo4j.agent.core.plugin.PluginBootstrap; +import cn.hippo4j.agent.core.plugin.PluginException; +import cn.hippo4j.agent.core.plugin.PluginFinder; +import cn.hippo4j.agent.core.plugin.bootstrap.BootstrapInstrumentBoost; +import cn.hippo4j.agent.core.plugin.bytebuddy.CacheableTransformerDecorator; +import cn.hippo4j.agent.core.plugin.jdk9module.JDK9ModuleExporter; +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.agent.builder.AgentBuilder; +import net.bytebuddy.description.NamedElement; +import net.bytebuddy.description.type.TypeDescription; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.scaffold.TypeValidation; +import net.bytebuddy.matcher.ElementMatcher; +import net.bytebuddy.matcher.ElementMatchers; +import net.bytebuddy.utility.JavaModule; + +import java.lang.instrument.Instrumentation; +import java.security.ProtectionDomain; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import static net.bytebuddy.matcher.ElementMatchers.nameContains; +import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith; +import static net.bytebuddy.matcher.ElementMatchers.not; + +public class Hippo4jAgent { + + private static ILog LOGGER = LogManager.getLogger(Hippo4jAgent.class); + + /** + * Main entrance. Use byte-buddy transform to enhance all classes, which define in plugins. + */ + public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException { + final PluginFinder pluginFinder; + try { + SnifferConfigInitializer.initializeCoreConfig(agentArgs); + } catch (Exception e) { + // try to resolve a new logger, and use the new logger to write the error log here + LogManager.getLogger(Hippo4jAgent.class) + .error(e, "Hippo4j agent initialized failure. Shutting down."); + return; + } finally { + // refresh logger again after initialization finishes + LOGGER = LogManager.getLogger(Hippo4jAgent.class); + } + + try { + pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins()); + } catch (AgentPackageNotFoundException ape) { + LOGGER.error(ape, "Locate agent.jar failure. Shutting down."); + return; + } catch (Exception e) { + LOGGER.error(e, "Hippo4j agent initialized failure. Shutting down."); + return; + } + + final ByteBuddy byteBuddy = new ByteBuddy().with(TypeValidation.of(Config.Agent.IS_OPEN_DEBUGGING_CLASS)); + + AgentBuilder agentBuilder = new AgentBuilder.Default(byteBuddy).ignore( + nameStartsWith("net.bytebuddy.") + .or(nameStartsWith("org.slf4j.")) + .or(nameStartsWith("org.groovy.")) + .or(nameContains("javassist")) + .or(nameContains(".asm.")) + .or(nameContains(".reflectasm.")) + .or(nameStartsWith("sun.reflect")) + .or(allHippo4jAgentExcludeToolkit()) + .or(ElementMatchers.isSynthetic())); + + JDK9ModuleExporter.EdgeClasses edgeClasses = new JDK9ModuleExporter.EdgeClasses(); + try { + agentBuilder = BootstrapInstrumentBoost.inject(pluginFinder, instrumentation, agentBuilder, edgeClasses); + } catch (Exception e) { + LOGGER.error(e, "Hippo4j agent inject bootstrap instrumentation failure. Shutting down."); + return; + } + + try { + agentBuilder = JDK9ModuleExporter.openReadEdge(instrumentation, agentBuilder, edgeClasses); + } catch (Exception e) { + LOGGER.error(e, "Hippo4j agent open read edge in JDK 9+ failure. Shutting down."); + return; + } + + if (Config.Agent.IS_CACHE_ENHANCED_CLASS) { + try { + agentBuilder = agentBuilder.with(new CacheableTransformerDecorator(Config.Agent.CLASS_CACHE_MODE)); + LOGGER.info("Hippo4j agent class cache [{}] activated.", Config.Agent.CLASS_CACHE_MODE); + } catch (Exception e) { + LOGGER.error(e, "Hippo4j agent can't active class cache."); + } + } + + agentBuilder.type(pluginFinder.buildMatch()) + .transform(new Transformer(pluginFinder)) + .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION) + .with(new RedefinitionListener()) + .with(new Listener()) + .installOn(instrumentation); + + PluginFinder.pluginInitCompleted(); + + try { + ServiceManager.INSTANCE.boot(); + } catch (Exception e) { + LOGGER.error(e, "Hippo4j agent boot failure."); + } + + try { + Class.forName("java.util.concurrent.ThreadPoolExecutor"); + } catch (ClassNotFoundException e) { + LOGGER.error(e, "Hippo4j agent boot failure."); + } + + Runtime.getRuntime() + .addShutdownHook(new Thread(ServiceManager.INSTANCE::shutdown, "hippo4j service shutdown thread")); + } + + private static class Transformer implements AgentBuilder.Transformer { + + private PluginFinder pluginFinder; + + Transformer(PluginFinder pluginFinder) { + this.pluginFinder = pluginFinder; + } + + @Override + public DynamicType.Builder transform(final DynamicType.Builder builder, + final TypeDescription typeDescription, + final ClassLoader classLoader, + final JavaModule javaModule, + final ProtectionDomain protectionDomain) { + LoadedLibraryCollector.registerURLClassLoader(classLoader); + List pluginDefines = pluginFinder.find(typeDescription); + if (pluginDefines.size() > 0) { + DynamicType.Builder newBuilder = builder; + EnhanceContext context = new EnhanceContext(); + for (AbstractClassEnhancePluginDefine define : pluginDefines) { + DynamicType.Builder possibleNewBuilder = define.define( + typeDescription, newBuilder, classLoader, context); + if (possibleNewBuilder != null) { + newBuilder = possibleNewBuilder; + } + } + if (context.isEnhanced()) { + LOGGER.debug("Finish the prepare stage for {}.", typeDescription.getName()); + } + + return newBuilder; + } + + LOGGER.debug("Matched class {}, but ignore by finding mechanism.", typeDescription.getTypeName()); + return builder; + } + } + + private static ElementMatcher.Junction allHippo4jAgentExcludeToolkit() { + return nameStartsWith("cn.hippo4j").and(not(nameStartsWith("cn.hippo4j.agent.toolkit."))); + } + + private static class Listener implements AgentBuilder.Listener { + + @Override + public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) { + + } + + @Override + public void onTransformation(final TypeDescription typeDescription, + final ClassLoader classLoader, + final JavaModule module, + final boolean loaded, + final DynamicType dynamicType) { + if (LOGGER.isDebugEnable()) { + LOGGER.debug("On Transformation class {}.", typeDescription.getName()); + } + + InstrumentDebuggingClass.INSTANCE.log(dynamicType); + } + + @Override + public void onIgnored(final TypeDescription typeDescription, + final ClassLoader classLoader, + final JavaModule module, + final boolean loaded) { + + } + + @Override + public void onError(final String typeName, + final ClassLoader classLoader, + final JavaModule module, + final boolean loaded, + final Throwable throwable) { + LOGGER.error("Enhance class " + typeName + " error.", throwable); + } + + @Override + public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) { + } + } + + private static class RedefinitionListener implements AgentBuilder.RedefinitionStrategy.Listener { + + @Override + public void onBatch(int index, List> batch, List> types) { + /* do nothing */ + } + + @Override + public Iterable>> onError(int index, List> batch, Throwable throwable, List> types) { + LOGGER.error(throwable, "index={}, batch={}, types={}", index, batch, types); + return Collections.emptyList(); + } + + @Override + public void onComplete(int amount, List> types, Map>, Throwable> failures) { + /* do nothing */ + } + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/dependency-reduced-pom.xml b/hippo4j-agent/hippo4j-agent-core/dependency-reduced-pom.xml deleted file mode 100644 index 93dafe25..00000000 --- a/hippo4j-agent/hippo4j-agent-core/dependency-reduced-pom.xml +++ /dev/null @@ -1,311 +0,0 @@ - - - - hippo4j-agent - cn.hippo4j - ${revision} - - 4.0.0 - hippo4j-agent-core - - - - kr.motd.maven - os-maven-plugin - ${os-maven-plugin.version} - - - initialize - - detect - - - - - - maven-shade-plugin - - - package - - shade - - - - - net.bytebuddy:byte-buddy:jar: - com.google.errorprone:error_prone_annotations:jar: - com.google.code.findbugs:jsr305:jar: - com.google.android:annotations:jar: - com.google.api.grpc:proto-google-common-protos:jar: - org.checkerframework:checker-compat-qual:jar: - org.codehaus.mojo:animal-sniffer-annotations:jar: - - - - - ${shade.com.google.source} - ${shade.com.google.target} - - - ${shade.io.grpc.source} - ${shade.io.grpc.target} - - - ${shade.io.netty.source} - ${shade.io.netty.target} - - - ${shade.io.opencensus.source} - ${shade.io.opencensus.target} - - - ${shade.io.perfmark.source} - ${shade.io.perfmark.target} - - - ${shade.org.slf4j.source} - ${shade.org.slf4j.target} - - - - - com.google.protobuf:protobuf-java - - google/protobuf/*.proto - google/protobuf/compiler/*.proto - - - - - - - - - - - - - - - net.bytebuddy - byte-buddy - 1.12.13 - compile - - - net.bytebuddy - byte-buddy-agent - 1.12.13 - test - - - com.github.tomakehurst - wiremock - 2.6.0 - test - - - jackson-annotations - com.fasterxml.jackson.core - - - jackson-core - com.fasterxml.jackson.core - - - jackson-databind - com.fasterxml.jackson.core - - - jetty-server - org.eclipse.jetty - - - jetty-servlet - org.eclipse.jetty - - - jetty-servlets - org.eclipse.jetty - - - jetty-webapp - org.eclipse.jetty - - - guava - com.google.guava - - - httpclient - org.apache.httpcomponents - - - xmlunit-core - org.xmlunit - - - xmlunit-legacy - org.xmlunit - - - json-path - com.jayway.jsonpath - - - jopt-simple - net.sf.jopt-simple - - - junit - junit - - - commons-lang3 - org.apache.commons - - - zjsonpatch - com.flipkart.zjsonpatch - - - handlebars - com.github.jknack - - - - - com.github.stefanbirkner - system-rules - 1.18.0 - test - - - junit - junit - - - junit-dep - junit - - - - - org.openjdk.jmh - jmh-generator-annprocess - 1.33 - test - - - org.powermock - powermock-api-mockito2 - 2.0.7 - test - - - powermock-api-support - org.powermock - - - mockito-core - org.mockito - - - - - org.objenesis - objenesis - 3.1 - test - - - org.openjdk.jmh - jmh-core - 1.33 - test - - - commons-math3 - org.apache.commons - - - jopt-simple - net.sf.jopt-simple - - - - - org.projectlombok - lombok - 1.18.20 - provided - - - javax.annotation - javax.annotation-api - 1.3.2 - provided - - - org.powermock - powermock-module-junit4 - 2.0.7 - test - - - powermock-module-junit4-common - org.powermock - - - hamcrest-core - org.hamcrest - - - junit - junit - - - - - - - - com.google.guava - guava - ${guava.version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - - ${shade.package}.${shade.io.perfmark.source} - io.opencensus - ${shade.package}.${shade.org.slf4j.source} - ${shade.package}.${shade.io.grpc.source} - 2.0.7.Final - 1.4.1.Final - io.netty - UTF-8 - 2.6.0 - 1.18.0 - ${shade.package}.${shade.io.opencensus.source} - 1.7.25 - ${shade.package}.${shade.io.netty.source} - com.google - 30.1.1-jre - io.perfmark - org.slf4j - io.grpc - ${shade.package}.${shade.com.google.source} - - diff --git a/hippo4j-agent/hippo4j-agent-core/pom.xml b/hippo4j-agent/hippo4j-agent-core/pom.xml index b1c4dc3f..16935905 100644 --- a/hippo4j-agent/hippo4j-agent-core/pom.xml +++ b/hippo4j-agent/hippo4j-agent-core/pom.xml @@ -14,8 +14,6 @@ UTF-8 - 30.1.1-jre - 2.6.0 2.0.7.Final 1.4.1.Final com.google @@ -31,7 +29,6 @@ org.slf4j ${shade.package}.${shade.org.slf4j.source} 1.18.0 - 1.7.25 @@ -42,19 +39,19 @@ com.google.code.gson gson - ${gson.version} - + + org.projectlombok + lombok + net.bytebuddy byte-buddy-agent - ${bytebuddy.version} test com.github.tomakehurst wiremock - ${wiremock.version} test @@ -71,41 +68,19 @@ - - com.github.stefanbirkner - system-rules - ${ststem-rules.version} - test - org.openjdk.jmh jmh-generator-annprocess test - org.slf4j - slf4j-api + cn.hippo4j + hippo4j-common + ${project.version} + provided - - - - com.google.guava - guava - ${guava.version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - + diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/AgentPackagePath.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/AgentPackagePath.java index 3844347b..029a4bfb 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/AgentPackagePath.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/AgentPackagePath.java @@ -26,7 +26,7 @@ import java.net.URISyntaxException; import java.net.URL; /** - * AgentPackagePath is a flag and finder to locate the SkyWalking agent.jar. It gets the absolute path of the agent jar. + * AgentPackagePath is a flag and finder to locate the Hippo4j agent.jar. It gets the absolute path of the agent jar. * The path is the required metadata for agent core looking up the plugins and toolkit activations. If the lookup * mechanism fails, the agent will exit directly. */ diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/DefaultNamedThreadFactory.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/DefaultNamedThreadFactory.java index 8b43f216..41c41204 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/DefaultNamedThreadFactory.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/DefaultNamedThreadFactory.java @@ -27,7 +27,7 @@ public class DefaultNamedThreadFactory implements ThreadFactory { private final String namePrefix; public DefaultNamedThreadFactory(String name) { - namePrefix = "SkywalkingAgent-" + BOOT_SERVICE_SEQ.incrementAndGet() + "-" + name + "-"; + namePrefix = "Hippo4jAgent-" + BOOT_SERVICE_SEQ.incrementAndGet() + "-" + name + "-"; } @Override diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/PluginConfig.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/PluginConfig.java index 64dfff77..8b175bc6 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/PluginConfig.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/PluginConfig.java @@ -24,7 +24,7 @@ import java.lang.annotation.Target; /** * ConfigInitializationService provides the config class which should host all parameters originally from agent setup. - * {@link org.apache.skywalking.apm.agent.core.conf.Config} provides the core level config, all plugins could implement + * {@link cn.hippo4j.agent.core.conf.Config} provides the core level config, all plugins could implement * this interface to have the same capability about initializing config from agent.config, system properties and system * environment variables. */ diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/ServiceManager.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/ServiceManager.java index af0aba72..2026ea9f 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/ServiceManager.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/ServiceManager.java @@ -21,7 +21,13 @@ import cn.hippo4j.agent.core.logging.api.ILog; import cn.hippo4j.agent.core.logging.api.LogManager; import cn.hippo4j.agent.core.plugin.loader.AgentClassLoader; -import java.util.*; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; /** * The ServiceManager bases on {@link ServiceLoader}, load all {@link BootService} implementations. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java new file mode 100644 index 00000000..bfdebf59 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.boot; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface SpringBootConfig { + + /** + * @return Class as the root to do config initialization. + */ + Class root(); +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java new file mode 100644 index 00000000..a8d33aed --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.boot; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.util.ConfigInitializer; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +public class SpringBootConfigInitializer { + + private static final ILog LOG = LogManager.getLogger(SpringBootConfigInitializer.class); + + private static final Set> SPRING_BOOT_CONFIG_LIST = Collections.synchronizedSet(new HashSet<>()); + + private static final long MAX_CACHE_TIME = 30L * 60L * 1000L; // half an hour. + + private static final int MAX_CACHE_SIZE = 1000; + + private static long PROPERTIES_LOAD_TIME; + + public static Properties SPRING_PROPERTIES = null; + + private SpringBootConfigInitializer() { + + } + + public static boolean isSpringPropertiesEmpty() { + return SPRING_PROPERTIES == null || SPRING_PROPERTIES.isEmpty(); + } + + public static synchronized void initializeConfig(SpringBootConfig springBootConfig) { + if (SPRING_PROPERTIES != null) { + try { + LOG.info("initialize Spring Config Class {}.", springBootConfig.root()); + ConfigInitializer.initialize(SPRING_PROPERTIES, springBootConfig.root(), true); + } catch (Throwable e) { + LOG.error(e, "Failed to set the agent settings {} to Config={} ", SPRING_PROPERTIES, springBootConfig.root()); + } + } + boolean isStarting = PROPERTIES_LOAD_TIME == 0L; + boolean overtime = System.currentTimeMillis() - PROPERTIES_LOAD_TIME > MAX_CACHE_TIME; + boolean oversize = SPRING_BOOT_CONFIG_LIST.size() > MAX_CACHE_SIZE; + // avoid memory leak. + if (isStarting || (!oversize && !overtime)) { + SPRING_BOOT_CONFIG_LIST.add(springBootConfig.root()); + } else { + LOG.warn("spirng Config Class is skipped {}.", springBootConfig.root()); + } + } + + public static synchronized void setSpringProperties(Properties properties) { + if (properties != null && (SPRING_PROPERTIES == null || properties.size() > SPRING_PROPERTIES.size())) { + LOG.info("set Spring Config Properties before : {}.", SPRING_PROPERTIES); + SPRING_PROPERTIES = properties; + LOG.info("set Spring Config Properties after : {}.", SPRING_PROPERTIES); + PROPERTIES_LOAD_TIME = System.currentTimeMillis(); + } + for (Class clazz : SPRING_BOOT_CONFIG_LIST) { + try { + LOG.info("initialize Spring Config Class in loop {}.", clazz); + ConfigInitializer.initialize(SPRING_PROPERTIES, clazz); + } catch (Throwable e) { + LOG.error(e, "Failed to set the agent Config={} from settings {}", clazz, properties); + } + } + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Config.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Config.java index 90309f5f..04fc9251 100755 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Config.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Config.java @@ -82,14 +82,14 @@ public class Config { public static String AUTHENTICATION = ""; /** - * If true, SkyWalking agent will save all instrumented classes files in `/debugging` folder. SkyWalking team + * If true, Hippo4j agent will save all instrumented classes files in `/debugging` folder. Hippo4j team * may ask for these files in order to resolve compatible problem. */ public static boolean IS_OPEN_DEBUGGING_CLASS = false; /** - * If true, SkyWalking agent will cache all instrumented classes to memory or disk files (decided by class cache - * mode), allow other javaagent to enhance those classes that enhanced by SkyWalking agent. + * If true, Hippo4j agent will cache all instrumented classes to memory or disk files (decided by class cache + * mode), allow other javaagent to enhance those classes that enhanced by Hippo4j agent. */ public static boolean IS_CACHE_ENHANCED_CLASS = false; @@ -108,7 +108,7 @@ public class Config { /** * service instance properties in json format. e.g. agent.instance_properties_json = {"org": - * "apache-skywalking"} + * "cn.hippo4j"} */ public static String INSTANCE_PROPERTIES_JSON = ""; @@ -181,7 +181,7 @@ public class Config { */ public static int PROPERTIES_REPORT_PERIOD_FACTOR = 10; /** - * Collector skywalking trace receiver service addresses. + * Collector hippo4j trace receiver service addresses. */ public static String BACKEND_SERVICE = ""; /** @@ -197,7 +197,7 @@ public class Config { */ public static int GET_AGENT_DYNAMIC_CONFIG_INTERVAL = 20; /** - * If true, skywalking agent will enable periodically resolving DNS to update receiver service addresses. + * If true, hippo4j agent will enable periodically resolving DNS to update receiver service addresses. */ public static boolean IS_RESOLVE_DNS_PERIODICALLY = false; } @@ -205,7 +205,7 @@ public class Config { public static class Profile { /** - * If true, skywalking agent will enable profile when user create a new profile task. Otherwise disable + * If true, hippo4j agent will enable profile when user create a new profile task. Otherwise disable * profile. */ public static boolean ACTIVE = true; @@ -234,7 +234,7 @@ public class Config { public static class Meter { /** - * If true, skywalking agent will enable sending meters. Otherwise disable meter report. + * If true, Hippo4j agent will enable sending meters. Otherwise disable meter report. */ public static boolean ACTIVE = true; @@ -277,11 +277,11 @@ public class Config { /** * Log file name. */ - public static String FILE_NAME = "skywalking-api.log"; + public static String FILE_NAME = "hippo4j-api.log"; /** - * Log files directory. Default is blank string, means, use "{theSkywalkingAgentJarDir}/logs " to output logs. - * {theSkywalkingAgentJarDir} is the directory where the skywalking agent jar file is located. + * Log files directory. Default is blank string, means, use "{theHippo4jAgentJarDir}/logs " to output logs. + * {theHippo4jAgentJarDir} is the directory where the hippo4j agent jar file is located. *

* Ref to {@link WriterFactory#getLogWriter()} */ @@ -358,6 +358,32 @@ public class Config { * Mount the folders of the plugins. The folder path is relative to agent.jar. */ public static List MOUNT = Arrays.asList("plugins", "activations"); + + public static class ThreadPool { + + public static List EXCLUDE_PACKAGE_PREFIX = Arrays.asList( + "java", "sun", "okhttp3", "retrofit2", "reactor", + "org.apache", "io.netty", "org.springframework", "com.ctrip", "com.google", + "io.undertow", "org.xnio", "org.jboss", "com.zaxxer", "org.redisson", "com.alibaba", + "com.netflix", "com.mysql", "rx.internal", "io.shardingjdbc", "org.drools", "org.elasticsearch", + "ch.qos.logback", "net.sf.ehcache"); + } + + public static class Apollo { + + public static class App { + + public static String ID; + } + public static String META; + + public static class BootStrap { + + public static boolean ENABLED = false; + + public static List NAMESPACES; + } + } } public static class Correlation { diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Constants.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Constants.java index 26433f2e..25f3d7bb 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Constants.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/Constants.java @@ -33,4 +33,7 @@ public class Constants { public static String EVENT_LAYER_NAME = "GENERAL"; public static int NULL_VALUE = 0; + + public static String SPRING_BOOT_CONFIG_PREFIX = "spring.dynamic.thread-pool"; + } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/SnifferConfigInitializer.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/SnifferConfigInitializer.java index 4323cc0f..570a68c8 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/SnifferConfigInitializer.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/SnifferConfigInitializer.java @@ -27,7 +27,10 @@ import cn.hippo4j.agent.core.util.ConfigInitializer; import cn.hippo4j.agent.core.util.PropertyPlaceholderHelper; import cn.hippo4j.agent.core.util.StringUtil; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -42,9 +45,9 @@ import static cn.hippo4j.agent.core.conf.Constants.SERVICE_NAME_PART_CONNECTOR; public class SnifferConfigInitializer { private static ILog LOGGER = LogManager.getLogger(SnifferConfigInitializer.class); - private static final String SPECIFIED_CONFIG_PATH = "skywalking_config"; + private static final String SPECIFIED_CONFIG_PATH = "hippo4j_config"; private static final String DEFAULT_CONFIG_FILE_NAME = "/config/agent.config"; - private static final String ENV_KEY_PREFIX = "skywalking."; + private static final String ENV_KEY_PREFIX = "hippo4j."; private static Properties AGENT_SETTINGS; private static boolean IS_INIT_COMPLETED = false; @@ -54,7 +57,7 @@ public class SnifferConfigInitializer { * /config directory of agent package. *

* Also try to override the config by system.properties. All the keys in this place should start with {@link - * #ENV_KEY_PREFIX}. e.g. in env `skywalking.agent.service_name=yourAppName` to override `agent.service_name` in + * #ENV_KEY_PREFIX}. e.g. in env `hippo4j.agent.service_name=yourAppName` to override `agent.service_name` in * config file. *

* At the end, `agent.service_name` and `collector.servers` must not be blank. @@ -69,7 +72,7 @@ public class SnifferConfigInitializer { } } catch (Exception e) { - LOGGER.error(e, "Failed to read the config file, skywalking is going to run in default config."); + LOGGER.error(e, "Failed to read the config file, hippo4j is going to run in default config."); } try { @@ -106,9 +109,9 @@ public class SnifferConfigInitializer { Config.Agent.CLUSTER); } } - if (StringUtil.isEmpty(Config.Collector.BACKEND_SERVICE)) { - throw new ExceptionInInitializerError("`collector.backend_service` is missing."); - } + // if (StringUtil.isEmpty(Config.Collector.BACKEND_SERVICE)) { + // throw new ExceptionInInitializerError("`collector.backend_service` is missing."); + // } if (Config.Plugin.PEER_MAX_LENGTH <= 3) { LOGGER.warn( "PEER_MAX_LENGTH configuration:{} error, the default value of 200 will be used.", @@ -180,10 +183,10 @@ public class SnifferConfigInitializer { } /** - * Override the config by system properties. The property key must start with `skywalking`, the result should be as + * Override the config by system properties. The property key must start with `hippo4j`, the result should be as * same as in `agent.config` *

- * such as: Property key of `agent.service_name` should be `skywalking.agent.service_name` + * such as: Property key of `agent.service_name` should be `hippo4j.agent.service_name` */ private static void overrideConfigBySystemProp() { Properties systemProperties = System.getProperties(); diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/dynamic/AgentConfigChangeWatcher.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/dynamic/AgentConfigChangeWatcher.java index 66bc294b..e896584d 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/dynamic/AgentConfigChangeWatcher.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/conf/dynamic/AgentConfigChangeWatcher.java @@ -44,9 +44,9 @@ public abstract class AgentConfigChangeWatcher { @Override public String toString() { - return "AgentConfigChangeWatcher{" + - "propertyKey='" + propertyKey + '\'' + - '}'; + return "AgentConfigChangeWatcher{" + + "propertyKey='" + propertyKey + '\'' + + '}'; } @Getter diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/jvm/LoadedLibraryCollector.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/jvm/LoadedLibraryCollector.java new file mode 100644 index 00000000..f8a466a6 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/jvm/LoadedLibraryCollector.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.jvm; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.util.CollectionUtil; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.File; +import java.lang.management.ManagementFactory; +import java.net.URL; +import java.net.URLClassLoader; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class LoadedLibraryCollector { + + private static final ILog LOGGER = LogManager.getLogger(LoadedLibraryCollector.class); + private static final String JAR_SEPARATOR = "!"; + private static Set CURRENT_URL_CLASSLOADER_SET = new HashSet<>(); + private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + /** + * Prevent OOM in special scenes + */ + private static int CURRENT_URL_CLASSLOADER_SET_MAX_SIZE = 50; + + public static void registerURLClassLoader(ClassLoader classLoader) { + if (CURRENT_URL_CLASSLOADER_SET.size() < CURRENT_URL_CLASSLOADER_SET_MAX_SIZE && classLoader instanceof URLClassLoader) { + CURRENT_URL_CLASSLOADER_SET.add(classLoader); + } + } + + private static String getVmStartTime() { + long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(startTime)); + } + + private static List getVmArgs() { + List vmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); + List sortedVmArgs = new ArrayList<>(vmArgs); + Collections.sort(sortedVmArgs); + return sortedVmArgs; + } + + private static List getLibJarNames() { + List classLoaderUrls = loadClassLoaderUrls(); + return extractLibJarNamesFromURLs(classLoaderUrls); + } + + private static List loadClassLoaderUrls() { + List classLoaderUrls = new ArrayList<>(); + for (ClassLoader classLoader : CURRENT_URL_CLASSLOADER_SET) { + try { + URLClassLoader webappClassLoader = (URLClassLoader) classLoader; + URL[] urls = webappClassLoader.getURLs(); + classLoaderUrls.addAll(Arrays.asList(urls)); + } catch (Exception e) { + LOGGER.warn("Load classloader urls exception: {}", e.getMessage()); + } + } + return classLoaderUrls; + } + + private static List extractLibJarNamesFromURLs(List urls) { + Set libJarNames = new HashSet<>(); + for (URL url : urls) { + try { + String libJarName = extractLibJarName(url); + if (libJarName.endsWith(".jar")) { + libJarNames.add(libJarName); + } + } catch (Exception e) { + LOGGER.warn("Extracting library name exception: {}", e.getMessage()); + } + } + List sortedLibJarNames = new ArrayList<>(libJarNames.size()); + if (!CollectionUtil.isEmpty(libJarNames)) { + sortedLibJarNames.addAll(libJarNames); + Collections.sort(sortedLibJarNames); + } + return sortedLibJarNames; + } + + private static String extractLibJarName(URL url) { + String protocol = url.getProtocol(); + if (protocol.equals("file")) { + return extractNameFromFile(url.toString()); + } else if (protocol.equals("jar")) { + return extractNameFromJar(url.toString()); + } else { + return ""; + } + } + + private static String extractNameFromFile(String fileUri) { + int lastIndexOfSeparator = fileUri.lastIndexOf(File.separator); + if (lastIndexOfSeparator < 0) { + return fileUri; + } else { + return fileUri.substring(lastIndexOfSeparator + 1); + } + } + + private static String extractNameFromJar(String jarUri) { + String uri = jarUri.substring(0, jarUri.lastIndexOf(JAR_SEPARATOR)); + return extractNameFromFile(uri); + } + +} \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/AbstractLogger.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/AbstractLogger.java index 939d4738..05a53ff0 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/AbstractLogger.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/AbstractLogger.java @@ -19,7 +19,13 @@ package cn.hippo4j.agent.core.logging.core; import cn.hippo4j.agent.core.conf.Config; import cn.hippo4j.agent.core.logging.api.ILog; -import cn.hippo4j.agent.core.logging.core.converters.*; +import cn.hippo4j.agent.core.logging.core.converters.AgentNameConverter; +import cn.hippo4j.agent.core.logging.core.converters.ClassConverter; +import cn.hippo4j.agent.core.logging.core.converters.DateConverter; +import cn.hippo4j.agent.core.logging.core.converters.LevelConverter; +import cn.hippo4j.agent.core.logging.core.converters.MessageConverter; +import cn.hippo4j.agent.core.logging.core.converters.ThreadConverter; +import cn.hippo4j.agent.core.logging.core.converters.ThrowableConverter; import java.util.ArrayList; import java.util.HashMap; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/FileWriter.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/FileWriter.java index f46ef87c..e2fde308 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/FileWriter.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/FileWriter.java @@ -22,7 +22,11 @@ import cn.hippo4j.agent.core.conf.Config; import cn.hippo4j.agent.core.conf.Constants; import cn.hippo4j.agent.core.util.RunnableWithExceptionProtection; -import java.io.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/JsonLogger.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/JsonLogger.java index 4ef0d682..fc657ef1 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/JsonLogger.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/JsonLogger.java @@ -24,7 +24,7 @@ import java.util.HashMap; import java.util.Map; /** - * An alternative logger for the SkyWalking agent. The default layout is + * An alternative logger for the Hippo4j agent. The default layout is * { * "@timestamp": "", // timestamp * "logger": "", // name of the Logger diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/WriterFactory.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/WriterFactory.java index 90777b21..72f2ddee 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/WriterFactory.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/logging/core/WriterFactory.java @@ -24,8 +24,6 @@ import cn.hippo4j.agent.core.conf.SnifferConfigInitializer; import cn.hippo4j.agent.core.plugin.PluginFinder; import cn.hippo4j.agent.core.util.StringUtil; -import static cn.hippo4j.agent.core.logging.core.LogOutput.FILE; - public class WriterFactory { private static IWriter WRITER; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/os/OSUtil.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/os/OSUtil.java index a2025596..c3040fff 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/os/OSUtil.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/os/OSUtil.java @@ -18,8 +18,11 @@ package cn.hippo4j.agent.core.os; import java.lang.management.ManagementFactory; -import java.net.*; -import java.util.ArrayList; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/ByteBuddyCoreClasses.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/ByteBuddyCoreClasses.java index 7a5ceeb2..95c5ef9f 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/ByteBuddyCoreClasses.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/ByteBuddyCoreClasses.java @@ -22,7 +22,7 @@ package cn.hippo4j.agent.core.plugin; */ public class ByteBuddyCoreClasses { - private static final String SHADE_PACKAGE = "org.apache.skywalking.apm.dependencies."; + private static final String SHADE_PACKAGE = "cn.hippo4j.agent.dependencies."; public static final String[] CLASSES = { SHADE_PACKAGE + "net.bytebuddy.implementation.bind.annotation.RuntimeType", diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginBootstrap.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginBootstrap.java index e17c0608..12dffe39 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginBootstrap.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginBootstrap.java @@ -46,7 +46,7 @@ public class PluginBootstrap { List resources = resolver.getResources(); if (resources == null || resources.size() == 0) { - LOGGER.info("no plugin files (skywalking-plugin.def) found, continue to start application."); + LOGGER.info("no plugin files (hippo4j-plugin.def) found, continue to start application."); return new ArrayList(); } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginFinder.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginFinder.java index 556726f8..588d4f5f 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginFinder.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginFinder.java @@ -26,7 +26,11 @@ import net.bytebuddy.description.NamedElement; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import static net.bytebuddy.matcher.ElementMatchers.isInterface; import static net.bytebuddy.matcher.ElementMatchers.not; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginResourcesResolver.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginResourcesResolver.java index da828860..06058a0b 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginResourcesResolver.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/PluginResourcesResolver.java @@ -28,7 +28,7 @@ import java.util.Enumeration; import java.util.List; /** - * Use the current classloader to read all plugin define file. The file must be named 'skywalking-plugin.def' + * Use the current classloader to read all plugin define file. The file must be named 'hippo4j-plugin.def' */ public class PluginResourcesResolver { @@ -38,12 +38,12 @@ public class PluginResourcesResolver { List cfgUrlPaths = new ArrayList(); Enumeration urls; try { - urls = AgentClassLoader.getDefault().getResources("skywalking-plugin.def"); + urls = AgentClassLoader.getDefault().getResources("hippo4j-plugin.def"); while (urls.hasMoreElements()) { URL pluginUrl = urls.nextElement(); cfgUrlPaths.add(pluginUrl); - LOGGER.info("find skywalking plugin define in {}", pluginUrl); + LOGGER.info("find hippo4j plugin define in {}", pluginUrl); } return cfgUrlPaths; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/BootstrapInstrumentBoost.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/BootstrapInstrumentBoost.java index ee4f2a84..3260e439 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/BootstrapInstrumentBoost.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/BootstrapInstrumentBoost.java @@ -19,7 +19,11 @@ package cn.hippo4j.agent.core.plugin.bootstrap; import cn.hippo4j.agent.core.logging.api.ILog; import cn.hippo4j.agent.core.logging.api.LogManager; -import cn.hippo4j.agent.core.plugin.*; +import cn.hippo4j.agent.core.plugin.AbstractClassEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.ByteBuddyCoreClasses; +import cn.hippo4j.agent.core.plugin.InstrumentDebuggingClass; +import cn.hippo4j.agent.core.plugin.PluginException; +import cn.hippo4j.agent.core.plugin.PluginFinder; import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; import cn.hippo4j.agent.core.plugin.interceptor.StaticMethodsInterceptPoint; @@ -55,31 +59,31 @@ public class BootstrapInstrumentBoost { private static final ILog LOGGER = LogManager.getLogger(BootstrapInstrumentBoost.class); private static final String[] HIGH_PRIORITY_CLASSES = { - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.BootstrapInterRuntimeAssist", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsAroundInterceptor", - "org.apache.skywalking.apm.agent.core.plugin.bootstrap.IBootstrapLog", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.OverrideCallable", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.BootstrapInterRuntimeAssist", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.StaticMethodsAroundInterceptor", + "cn.hippo4j.agent.core.plugin.bootstrap.IBootstrapLog", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.OverrideCallable", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult", // interceptor v2 - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.v2.InstanceMethodsAroundInterceptorV2", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.v2.StaticMethodsAroundInterceptorV2", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.v2.MethodInvocationContext", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.InstanceMethodsAroundInterceptorV2", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.StaticMethodsAroundInterceptorV2", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.MethodInvocationContext", }; - private static String INSTANCE_METHOD_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.InstanceMethodInterTemplate"; - private static String INSTANCE_METHOD_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.InstanceMethodInterWithOverrideArgsTemplate"; - private static String CONSTRUCTOR_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.ConstructorInterTemplate"; - private static String STATIC_METHOD_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.StaticMethodInterTemplate"; - private static String STATIC_METHOD_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.StaticMethodInterWithOverrideArgsTemplate"; + private static String INSTANCE_METHOD_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.InstanceMethodInterTemplate"; + private static String INSTANCE_METHOD_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.InstanceMethodInterWithOverrideArgsTemplate"; + private static String CONSTRUCTOR_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.ConstructorInterTemplate"; + private static String STATIC_METHOD_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.StaticMethodInterTemplate"; + private static String STATIC_METHOD_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.StaticMethodInterWithOverrideArgsTemplate"; - private static String INSTANCE_METHOD_V2_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.v2.InstanceMethodInterV2Template"; - private static String INSTANCE_METHOD_V2_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.v2.InstanceMethodInterV2WithOverrideArgsTemplate"; - private static String STATIC_METHOD_V2_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.v2.StaticMethodInterV2Template"; - private static String STATIC_METHOD_V2_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.template.v2.StaticMethodInterV2WithOverrideArgsTemplate"; + private static String INSTANCE_METHOD_V2_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.v2.InstanceMethodInterV2Template"; + private static String INSTANCE_METHOD_V2_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.v2.InstanceMethodInterV2WithOverrideArgsTemplate"; + private static String STATIC_METHOD_V2_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.v2.StaticMethodInterV2Template"; + private static String STATIC_METHOD_V2_WITH_OVERRIDE_ARGS_DELEGATE_TEMPLATE = "cn.hippo4j.agent.core.plugin.bootstrap.template.v2.StaticMethodInterV2WithOverrideArgsTemplate"; public static AgentBuilder inject(PluginFinder pluginFinder, Instrumentation instrumentation, AgentBuilder agentBuilder, JDK9ModuleExporter.EdgeClasses edgeClasses) throws PluginException { @@ -235,7 +239,7 @@ public class BootstrapInstrumentBoost { * @param classesTypeMap hosts injected binary of generated class * @param typePool to generate new class * @param templateClassName represents the class as template in this generation process. The templates are - * pre-defined in SkyWalking agent core. + * pre-defined in Hippo4j agent core. */ private static void generateDelegator(Map classesTypeMap, TypePool typePool, String templateClassName, String methodsInterceptor) { diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterTemplate.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterTemplate.java index a98212a8..aa9cb6f3 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterTemplate.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterTemplate.java @@ -22,7 +22,11 @@ import cn.hippo4j.agent.core.plugin.interceptor.enhance.BootstrapInterRuntimeAss import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.SuperCall; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; import java.util.concurrent.Callable; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterWithOverrideArgsTemplate.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterWithOverrideArgsTemplate.java index 319ffb8d..78ef6751 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterWithOverrideArgsTemplate.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/InstanceMethodInterWithOverrideArgsTemplate.java @@ -18,8 +18,16 @@ package cn.hippo4j.agent.core.plugin.bootstrap.template; import cn.hippo4j.agent.core.plugin.bootstrap.IBootstrapLog; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.*; -import net.bytebuddy.implementation.bind.annotation.*; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.BootstrapInterRuntimeAssist; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.OverrideCallable; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Morph; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2Template.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2Template.java index 31b3a4e0..0bc6205e 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2Template.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2Template.java @@ -22,7 +22,12 @@ import cn.hippo4j.agent.core.plugin.interceptor.enhance.BootstrapInterRuntimeAss import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.InstanceMethodsAroundInterceptorV2; import cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.MethodInvocationContext; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.SuperCall; +import net.bytebuddy.implementation.bind.annotation.This; + import java.lang.reflect.Method; import java.util.concurrent.Callable; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2WithOverrideArgsTemplate.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2WithOverrideArgsTemplate.java index be29208c..6e15b671 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2WithOverrideArgsTemplate.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bootstrap/template/v2/InstanceMethodInterV2WithOverrideArgsTemplate.java @@ -23,7 +23,11 @@ import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.OverrideCallable; import cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.InstanceMethodsAroundInterceptorV2; import cn.hippo4j.agent.core.plugin.interceptor.enhance.v2.MethodInvocationContext; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Morph; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java index 54021db8..8341772c 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/bytebuddy/CacheableTransformerDecorator.java @@ -27,7 +27,11 @@ import net.bytebuddy.agent.builder.AgentBuilder; import net.bytebuddy.agent.builder.ResettableClassFileTransformer; import net.bytebuddy.utility.RandomString; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Map; @@ -37,7 +41,7 @@ import java.util.concurrent.ConcurrentHashMap; * Wrapper classFileTransformer of ByteBuddy, save the enhanced bytecode to memory cache or file cache, * and automatically load the previously generated bytecode during the second retransform, * to solve the problem that ByteBuddy generates auxiliary classes with different random names every time. - * Allow other javaagent to enhance those classes that enhanced by SkyWalking agent. + * Allow other javaagent to enhance those classes that enhanced by Hippo4j agent. */ public class CacheableTransformerDecorator implements AgentBuilder.TransformerDecorator { diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/exception/IllegalPluginDefineException.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/exception/IllegalPluginDefineException.java index c7ab4ac5..a23d7240 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/exception/IllegalPluginDefineException.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/exception/IllegalPluginDefineException.java @@ -18,7 +18,7 @@ package cn.hippo4j.agent.core.plugin.exception; /** - * Thrown to indicate that a illegal format plugin definition has been defined in skywalking-plugin.define. + * Thrown to indicate that a illegal format plugin definition has been defined in hippo4j-plugin.define. */ public class IllegalPluginDefineException extends Exception { diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/ConstructorInterceptPoint.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/ConstructorInterceptPoint.java index 8d506413..330aa7d0 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/ConstructorInterceptPoint.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/ConstructorInterceptPoint.java @@ -38,7 +38,7 @@ public interface ConstructorInterceptPoint { /** * @return represents a class name, the class instance must be a instance of {@link - * org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor} + * cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor} */ String getConstructorInterceptor(); } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/BootstrapInterRuntimeAssist.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/BootstrapInterRuntimeAssist.java index b5f8f353..a1c5d38a 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/BootstrapInterRuntimeAssist.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/BootstrapInterRuntimeAssist.java @@ -28,9 +28,9 @@ import java.lang.reflect.Method; */ public class BootstrapInterRuntimeAssist { - private static final String AGENT_CLASSLOADER_DEFAULT = "org.apache.skywalking.apm.agent.core.plugin.loader.AgentClassLoader"; + private static final String AGENT_CLASSLOADER_DEFAULT = "cn.hippo4j.agent.core.plugin.loader.AgentClassLoader"; private static final String DEFAULT_AGENT_CLASSLOADER_INSTANCE = "DEFAULT_LOADER"; - private static final String LOG_MANAGER_CLASS = "org.apache.skywalking.apm.agent.core.plugin.bootstrap.BootstrapPluginLogBridge"; + private static final String LOG_MANAGER_CLASS = "cn.hippo4j.agent.core.plugin.bootstrap.BootstrapPluginLogBridge"; private static final String LOG_MANAGER_GET_LOGGER_METHOD = "getLogger"; private static final PrintStream OUT = System.out; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/ClassEnhancePluginDefine.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/ClassEnhancePluginDefine.java index b83dbfa0..70dddbad 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/ClassEnhancePluginDefine.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/ClassEnhancePluginDefine.java @@ -23,7 +23,11 @@ import cn.hippo4j.agent.core.plugin.AbstractClassEnhancePluginDefine; import cn.hippo4j.agent.core.plugin.EnhanceContext; import cn.hippo4j.agent.core.plugin.PluginException; import cn.hippo4j.agent.core.plugin.bootstrap.BootstrapInstrumentBoost; -import cn.hippo4j.agent.core.plugin.interceptor.*; +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.DeclaredInstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.EnhanceException; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.StaticMethodsInterceptPoint; import cn.hippo4j.agent.core.plugin.interceptor.v2.InstanceMethodsInterceptV2Point; import cn.hippo4j.agent.core.plugin.interceptor.v2.StaticMethodsInterceptV2Point; import cn.hippo4j.agent.core.util.StringUtil; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/EnhancedInstance.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/EnhancedInstance.java index cb04a006..c6b7900b 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/EnhancedInstance.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/EnhancedInstance.java @@ -19,7 +19,7 @@ package cn.hippo4j.agent.core.plugin.interceptor.enhance; public interface EnhancedInstance { - Object getSkyWalkingDynamicField(); + Object getHippo4jDynamicField(); - void setSkyWalkingDynamicField(Object value); + void setHippo4jDynamicField(Object value); } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInter.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInter.java index 2cc28baa..489c54d3 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInter.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInter.java @@ -21,7 +21,11 @@ import cn.hippo4j.agent.core.logging.api.ILog; import cn.hippo4j.agent.core.logging.api.LogManager; import cn.hippo4j.agent.core.plugin.PluginException; import cn.hippo4j.agent.core.plugin.loader.InterceptorInstanceLoader; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.SuperCall; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; import java.util.concurrent.Callable; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInterWithOverrideArgs.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInterWithOverrideArgs.java index ef7c95c6..5febdb83 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInterWithOverrideArgs.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/InstMethodsInterWithOverrideArgs.java @@ -21,7 +21,11 @@ import cn.hippo4j.agent.core.logging.api.ILog; import cn.hippo4j.agent.core.logging.api.LogManager; import cn.hippo4j.agent.core.plugin.PluginException; import cn.hippo4j.agent.core.plugin.loader.InterceptorInstanceLoader; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Morph; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2.java index c7b1b6f3..3967736a 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2.java @@ -22,7 +22,11 @@ import cn.hippo4j.agent.core.logging.api.LogManager; import cn.hippo4j.agent.core.plugin.PluginException; import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.loader.InterceptorInstanceLoader; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.SuperCall; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; import java.util.concurrent.Callable; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2WithOverrideArgs.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2WithOverrideArgs.java index aaacb300..f9cd51d6 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2WithOverrideArgs.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/enhance/v2/InstMethodsInterV2WithOverrideArgs.java @@ -23,7 +23,11 @@ import cn.hippo4j.agent.core.plugin.PluginException; import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.OverrideCallable; import cn.hippo4j.agent.core.plugin.loader.InterceptorInstanceLoader; -import net.bytebuddy.implementation.bind.annotation.*; +import net.bytebuddy.implementation.bind.annotation.AllArguments; +import net.bytebuddy.implementation.bind.annotation.Morph; +import net.bytebuddy.implementation.bind.annotation.Origin; +import net.bytebuddy.implementation.bind.annotation.RuntimeType; +import net.bytebuddy.implementation.bind.annotation.This; import java.lang.reflect.Method; diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/v2/ConstructorInterceptV2Point.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/v2/ConstructorInterceptV2Point.java index 0a035db0..e073e7c1 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/v2/ConstructorInterceptV2Point.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/interceptor/v2/ConstructorInterceptV2Point.java @@ -31,7 +31,7 @@ public interface ConstructorInterceptV2Point { /** * @return represents a class name, the class instance must be a instance of {@link - * org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor} + * cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor} */ String getConstructorInterceptorV2(); diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/jdk9module/JDK9ModuleExporter.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/jdk9module/JDK9ModuleExporter.java index f1923ef5..1ff3514e 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/jdk9module/JDK9ModuleExporter.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/jdk9module/JDK9ModuleExporter.java @@ -34,14 +34,14 @@ public class JDK9ModuleExporter { private static final ILog LOGGER = LogManager.getLogger(JDK9ModuleExporter.class); private static final String[] HIGH_PRIORITY_CLASSES = { - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.OverrideCallable", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.ConstructorInter", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstMethodsInter", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstMethodsInterWithOverrideArgs", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsInter", - "org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.StaticMethodsInterWithOverrideArgs", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.OverrideCallable", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.ConstructorInter", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.InstMethodsInter", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.InstMethodsInterWithOverrideArgs", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.StaticMethodsInter", + "cn.hippo4j.agent.core.plugin.interceptor.enhance.StaticMethodsInterWithOverrideArgs", }; /** diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java index 0539c9a7..24cca2b6 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java @@ -20,6 +20,8 @@ package cn.hippo4j.agent.core.plugin.loader; import cn.hippo4j.agent.core.boot.AgentPackageNotFoundException; import cn.hippo4j.agent.core.boot.AgentPackagePath; import cn.hippo4j.agent.core.boot.PluginConfig; +import cn.hippo4j.agent.core.boot.SpringBootConfig; +import cn.hippo4j.agent.core.boot.SpringBootConfigInitializer; import cn.hippo4j.agent.core.conf.Config; import cn.hippo4j.agent.core.conf.SnifferConfigInitializer; import cn.hippo4j.agent.core.logging.api.ILog; @@ -169,6 +171,13 @@ public class AgentClassLoader extends ClassLoader { SnifferConfigInitializer.initializeConfig(pluginConfig.root()); } + final SpringBootConfig springBootConfig = loadedClass.getAnnotation(SpringBootConfig.class); + if (springBootConfig != null) { + // Set up the plugin config when loaded by spring environment is prepared, just scan in here. + // Agent class loader just loaded limited classes in the plugin jar(s), so the cost of this + // isAssignableFrom would be also very limited. + SpringBootConfigInitializer.initializeConfig(springBootConfig); + } return loadedClass; } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ClassAnnotationMatch.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ClassAnnotationMatch.java index 7d8f2bd0..ab181816 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ClassAnnotationMatch.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ClassAnnotationMatch.java @@ -26,7 +26,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static net.bytebuddy.matcher.ElementMatchers.*; +import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; +import static net.bytebuddy.matcher.ElementMatchers.isInterface; +import static net.bytebuddy.matcher.ElementMatchers.named; +import static net.bytebuddy.matcher.ElementMatchers.not; /** * Match the class by the given annotations in class. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/HierarchyMatch.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/HierarchyMatch.java index 31e10d66..759f38ba 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/HierarchyMatch.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/HierarchyMatch.java @@ -25,7 +25,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static net.bytebuddy.matcher.ElementMatchers.*; +import static net.bytebuddy.matcher.ElementMatchers.hasSuperType; +import static net.bytebuddy.matcher.ElementMatchers.isInterface; +import static net.bytebuddy.matcher.ElementMatchers.named; +import static net.bytebuddy.matcher.ElementMatchers.not; /** * Match the class by the given super class or interfaces. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/MethodAnnotationMatch.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/MethodAnnotationMatch.java index 8bb216fe..71c79747 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/MethodAnnotationMatch.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/MethodAnnotationMatch.java @@ -28,7 +28,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static net.bytebuddy.matcher.ElementMatchers.*; +import static net.bytebuddy.matcher.ElementMatchers.declaresMethod; +import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith; +import static net.bytebuddy.matcher.ElementMatchers.isInterface; +import static net.bytebuddy.matcher.ElementMatchers.named; /** * Match the class, which has methods with the certain annotations. This is a very complex match. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ProtectiveShieldMatcher.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ProtectiveShieldMatcher.java index 525cee21..d0ec36cb 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ProtectiveShieldMatcher.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/ProtectiveShieldMatcher.java @@ -26,7 +26,7 @@ import net.bytebuddy.matcher.ElementMatcher; * them have compatible issues with byte-buddy core, which trigger "Can't resolve type description" exception. *

* So I build this protective shield by a nested matcher. When the origin matcher(s) can't resolve the type, the - * SkyWalking agent ignores this types. + * Hippo4j agent ignores this types. *

* Notice: this ignore mechanism may miss some instrumentations, but at most cases, it's same. If missing happens, * please pay attention to the WARNING logs. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/logical/LogicalMatchOperation.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/logical/LogicalMatchOperation.java index ee19f5b0..26637d8d 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/logical/LogicalMatchOperation.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/match/logical/LogicalMatchOperation.java @@ -23,7 +23,7 @@ import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.matcher.NegatingMatcher; /** - * Util class to help to construct logical operations on {@link org.apache.skywalking.apm.agent.core.plugin.match.ClassMatch}s + * Util class to help to construct logical operations on {@link cn.hippo4j.agent.core.plugin.match.ClassMatch}s */ public class LogicalMatchOperation { diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolExecutorHolder.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolExecutorHolder.java new file mode 100644 index 00000000..42df259e --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolExecutorHolder.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.registry; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.common.config.ExecutorProperties; +import lombok.Data; + +import java.util.Properties; +import java.util.concurrent.ThreadPoolExecutor; + +@Data +public class AgentThreadPoolExecutorHolder { + + private static final ILog LOGGER = LogManager.getLogger(AgentThreadPoolExecutorHolder.class); + + public static final AgentThreadPoolExecutorHolder EMPTY = new AgentThreadPoolExecutorHolder(); + + private String executorName; + + private ThreadPoolExecutor executor; + + private Properties properties; + + public AgentThreadPoolExecutorHolder() { + } + + public AgentThreadPoolExecutorHolder(String executorName, ThreadPoolExecutor executor, Properties properties) { + this.executorName = executorName; + this.executor = executor; + this.properties = properties; + } + + public boolean isEmpty() { + return this == EMPTY; + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolInstanceRegistry.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolInstanceRegistry.java new file mode 100644 index 00000000..3b34210e --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/registry/AgentThreadPoolInstanceRegistry.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.registry; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.common.config.ExecutorProperties; + +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadPoolExecutor; + +public class AgentThreadPoolInstanceRegistry { + + private static final ILog LOGGER = LogManager.getLogger(AgentThreadPoolInstanceRegistry.class); + + private final Map holderMap = new ConcurrentHashMap<>(); + + public final Map> earlyConstructMap = new ConcurrentHashMap<>(); + + private volatile static AgentThreadPoolInstanceRegistry INSTANCE; + + private AgentThreadPoolInstanceRegistry() { + } + + public static AgentThreadPoolInstanceRegistry getInstance() { + if (INSTANCE == null) { + synchronized (AgentThreadPoolInstanceRegistry.class) { + if (INSTANCE == null) { + INSTANCE = new AgentThreadPoolInstanceRegistry(); + } + } + } + return INSTANCE; + } + + public Map getHolderMap() { + return holderMap; + } + + public void putHolder(String executorName, ThreadPoolExecutor executor, Properties properties) { + AgentThreadPoolExecutorHolder holder = new AgentThreadPoolExecutorHolder(executorName, executor, properties); + holderMap.put(executorName, holder); + } + + public AgentThreadPoolExecutorHolder getHolder(String executorName) { + return Optional.ofNullable(holderMap.get(executorName)).orElse(AgentThreadPoolExecutorHolder.EMPTY); + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/AgentThreadPoolConstants.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/AgentThreadPoolConstants.java new file mode 100644 index 00000000..bdfbdaac --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/AgentThreadPoolConstants.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.util; + +public interface AgentThreadPoolConstants { + + String TOMCAT_NAME_PREFIX = "namePrefix"; + String DUBBO_NAME_PREFIX = "mPrefix"; + String DUBBO_THREAD_NAME = "DubboServerHandler"; + String THREAD_POOL_NAME_DUBBO = "dubbo"; + +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/CollectionUtil.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/CollectionUtil.java index 0037ae76..587c84f8 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/CollectionUtil.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/CollectionUtil.java @@ -41,4 +41,24 @@ public final class CollectionUtil { public static boolean isEmpty(Collection collection) { return collection == null || collection.isEmpty(); } + + /** + * Is empty. + * + * @param map + * @return + */ + public static boolean isEmpty(Map map) { + return map == null || map.isEmpty(); + } + + /** + * Is not empty. + * + * @param map + * @return + */ + public static boolean isNotEmpty(Map map) { + return !isEmpty(map); + } } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ConfigInitializer.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ConfigInitializer.java index 3bb87ccd..5559db3c 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ConfigInitializer.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ConfigInitializer.java @@ -21,7 +21,12 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.*; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; /** * Init a class's static fields by a {@link Properties}, including static fields and static inner classes. @@ -30,14 +35,18 @@ import java.util.*; public class ConfigInitializer { public static void initialize(Properties properties, Class rootConfigType) throws IllegalAccessException { - initNextLevel(properties, rootConfigType, new ConfigDesc()); + initNextLevel(properties, rootConfigType, new ConfigDesc(), false); + } + + public static void initialize(Properties properties, Class rootConfigType, boolean isSpringProperties) throws IllegalAccessException { + initNextLevel(properties, rootConfigType, new ConfigDesc(), isSpringProperties); } private static void initNextLevel(Properties properties, Class recentConfigType, - ConfigDesc parentDesc) throws IllegalArgumentException, IllegalAccessException { + ConfigDesc parentDesc, boolean isSpringProperties) throws IllegalArgumentException, IllegalAccessException { for (Field field : recentConfigType.getFields()) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { - String configKey = (parentDesc + "." + field.getName()).toLowerCase(); + String configKey = (parentDesc + "." + (isSpringProperties ? field.getName().replace("_", "-") : field.getName())).toLowerCase(); Class type = field.getType(); if (type.equals(Map.class)) { @@ -78,8 +87,10 @@ public class ConfigInitializer { } } for (Class innerConfiguration : recentConfigType.getClasses()) { - parentDesc.append(innerConfiguration.getSimpleName()); - initNextLevel(properties, innerConfiguration, parentDesc); + String simpleName = innerConfiguration.getSimpleName(); + String description = isSpringProperties ? simpleName.replace("_", "-") : simpleName; + parentDesc.append(description); + initNextLevel(properties, innerConfiguration, parentDesc, isSpringProperties); parentDesc.removeLastDesc(); } } diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ExecutorNameUtil.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ExecutorNameUtil.java new file mode 100644 index 00000000..7a597187 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ExecutorNameUtil.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.util; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; + +import java.lang.reflect.Field; + +public class ExecutorNameUtil { + + private static final ILog LOGGER = LogManager.getLogger(ExecutorNameUtil.class); + + public static boolean isTomcatExecutor(Object threadFactory) { + try { + if ("org.apache.tomcat.util.threads.TaskThreadFactory".equals(threadFactory.getClass().getName())) { + Field namePrefixField = threadFactory.getClass().getDeclaredField(AgentThreadPoolConstants.TOMCAT_NAME_PREFIX); + namePrefixField.setAccessible(true); + String namePrefix = (String) namePrefixField.get(threadFactory); + if (RegexUtil.isTomcatNameMatch(namePrefix)) { + return true; + } + } + } catch (Throwable t) { + LOGGER.error("Fail to put tomcat executor", t); + } + return false; + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/IOUtils.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/IOUtils.java index 30ac27b7..7c89756b 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/IOUtils.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/IOUtils.java @@ -17,7 +17,11 @@ package cn.hippo4j.agent.core.util; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; /** * Copied from commons-io-2.2 (org.apache.commons.io.IOUtils) diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/PropertyPlaceholderHelper.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/PropertyPlaceholderHelper.java index 2b670c49..39e09629 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/PropertyPlaceholderHelper.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/PropertyPlaceholderHelper.java @@ -17,7 +17,11 @@ package cn.hippo4j.agent.core.util; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; /** * Utility class for working with Strings that have placeholder values in them. A placeholder takes the form {@code diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ReflectUtil.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ReflectUtil.java new file mode 100644 index 00000000..e6fed965 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ReflectUtil.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.util; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class ReflectUtil { + + private static final ILog LOGGER = LogManager.getLogger(ReflectUtil.class); + + public static List getStaticFieldsFromType(Class clazz, Class declaredType) { + Field[] fields = clazz.getDeclaredFields(); + List result = new ArrayList<>(); + for (Field field : fields) { + if (field.getType().isAssignableFrom(declaredType) + && Modifier.isStatic(field.getModifiers())) { + field.setAccessible(true); + result.add(field); + } + } + return result; + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/RegexUtil.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/RegexUtil.java new file mode 100644 index 00000000..a3576643 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/RegexUtil.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.util; + +import java.util.regex.Pattern; + +public class RegexUtil { + + private static final String TOMCAT_NAME_PATTERN_STRING = "http\\S+nio\\S+-exec-"; + private static final Pattern TOMCAT_NAME_PATTERN = Pattern.compile(TOMCAT_NAME_PATTERN_STRING); + + public static boolean isTomcatNameMatch(String executorName) { + return TOMCAT_NAME_PATTERN.matcher(executorName).find(); + } +} diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ThreadPoolPropertyKey.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ThreadPoolPropertyKey.java new file mode 100644 index 00000000..89148adb --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/util/ThreadPoolPropertyKey.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.core.util; + +public interface ThreadPoolPropertyKey { + + String THREAD_POOL_ID = "threadPoolId"; + String CORE_POOL_SIZE = "corePoolSize"; + String MAXIMUM_POOL_SIZE = "maximumPoolSize"; + String ALLOW_CORE_THREAD_TIME_OUT = "allowCoreThreadTimeOut"; + String KEEP_ALIVE_TIME = "keepAliveTime"; + String BLOCKING_QUEUE = "blockingQueue"; + String QUEUE_CAPACITY = "queueCapacity"; + String THREAD_NAME_PREFIX = "threadNamePrefix"; + String REJECTED_HANDLER = "rejectedHandler"; + String EXECUTE_TIME_OUT = "executeTimeOut"; +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/pom.xml new file mode 100644 index 00000000..c50abc5e --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + cn.hippo4j + hippo4j-agent-plugin + ${revision} + + + apollo-plugin + + + 1.9.1 + + + + + com.ctrip.framework.apollo + apollo-client + ${apollo.version} + provided + + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java new file mode 100644 index 00000000..007e661f --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.apollo; + +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor; + +public class DefaultConfigConstructorInterceptor implements InstanceConstructorInterceptor { + + @Override + public void onConstruct(EnhancedInstance objInst, Object[] allArguments) throws Throwable { + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/boot/ApolloPluginBootService.java b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/boot/ApolloPluginBootService.java new file mode 100644 index 00000000..9ad1dd0f --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/boot/ApolloPluginBootService.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.apollo.boot; + +import cn.hippo4j.agent.core.boot.BootService; +import cn.hippo4j.agent.core.boot.DefaultImplementor; + +@DefaultImplementor +public class ApolloPluginBootService implements BootService { + + @Override + public void prepare() throws Throwable { + + } + + @Override + public void boot() throws Throwable { + + } + + @Override + public void onComplete() throws Throwable { + + } + + @Override + public void shutdown() throws Throwable { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java new file mode 100644 index 00000000..6ae9d63c --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.apollo.define; + +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.match.ClassMatch; +import cn.hippo4j.agent.core.plugin.match.NameMatch; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +import static net.bytebuddy.matcher.ElementMatchers.any; + +public class ApolloInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { + + private static final String ENHANCE_CLASS = "com.ctrip.framework.apollo.internals.DefaultConfig"; + + private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.apollo.DefaultConfigConstructorInterceptor"; + + @Override + protected ClassMatch enhanceClass() { + return NameMatch.byName(ENHANCE_CLASS); + } + + @Override + public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { + return new ConstructorInterceptPoint[]{ + new ConstructorInterceptPoint() { + + @Override + public ElementMatcher getConstructorMatcher() { + return any(); + } + + @Override + public String getConstructorInterceptor() { + return CONSTRUCTOR_INTERCEPT_CLASS; + } + } + }; + } + + @Override + public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { + return new InstanceMethodsInterceptPoint[0]; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/META-INF/services/cn.hippo4j.agent.core.boot.BootService b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/META-INF/services/cn.hippo4j.agent.core.boot.BootService new file mode 100644 index 00000000..8832c467 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/META-INF/services/cn.hippo4j.agent.core.boot.BootService @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +cn.hippo4j.agent.plugin.apollo.boot.ApolloPluginBootService \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/hippo4j-plugin.def b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/hippo4j-plugin.def new file mode 100644 index 00000000..ede6239b --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/resources/hippo4j-plugin.def @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apollo-plugin=cn.hippo4j.agent.plugin.apollo.define.ApolloInstrumentation \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/pom.xml new file mode 100644 index 00000000..1a3db451 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/pom.xml @@ -0,0 +1,118 @@ + + + 4.0.0 + + cn.hippo4j + hippo4j-agent + ${revision} + + + hippo4j-agent-plugin + pom + + spring-plugins + thread-pool-plugin + apollo-plugin + + + + UTF-8 + + net.bytebuddy + ${shade.package}.${shade.net.bytebuddy.source} + + ${project.build.directory}${sdk.plugin.related.dir}/../../../hippo4j-agent + + ${agent.package.dest.dir}/plugins + + 1.0b3 + 1.8.1 + + + + + cn.hippo4j + hippo4j-agent-core + ${project.version} + provided + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + provided + + + + + + + maven-shade-plugin + + + package + + shade + + + false + true + true + true + + + ${shade.net.bytebuddy.source} + ${shade.net.bytebuddy.target} + + + + + + + + maven-antrun-plugin + + + package + + run + + + + + + + + + + + + + + + + + + + ant-contrib + ant-contrib + ${ant-contrib.version} + + + ant + ant + + + + + org.apache.ant + ant-nodeps + ${ant-nodeps.version} + + + + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/pom.xml new file mode 100644 index 00000000..200bfd2a --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + cn.hippo4j + hippo4j-agent-plugin + ${revision} + + + spring-plugins + pom + + spring-boot-1.x-plugin + spring-boot-2.x-plugin + spring-plugin-common + + + + UTF-8 + /.. + + + + + + cn.hippo4j + spring-plugin-common + ${project.version} + + + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml new file mode 100644 index 00000000..e144cf35 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + cn.hippo4j + spring-plugins + ${revision} + + + spring-boot-1.x-plugin + + + 1.5.22.RELEASE + 1.9.1 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + + + + cn.hippo4j + spring-plugin-common + provided + + + + org.springframework.boot + spring-boot-starter + ${spring.boot.version} + provided + + + + com.ctrip.framework.apollo + apollo-client + ${apollo.version} + provided + + + + org.projectlombok + lombok + provided + + + + cn.hippo4j + hippo4j-config-spring-boot-1x-starter + ${project.version} + provided + + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java new file mode 100644 index 00000000..f7b7a128 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1; + +import cn.hippo4j.agent.core.boot.SpringBootConfig; + +import java.util.Arrays; +import java.util.List; + +public class ApolloSpringBootProperties { + + public static class Spring { + + public static class Dynamic { + + @SpringBootConfig(root = ApolloSpringBootProperties.class) + public static class Thread_Pool { + + @SpringBootConfig(root = ApolloSpringBootProperties.class) + public static class Apollo { + + public static List NAMESPACE = Arrays.asList("application"); + } + + public static String CONFIG_FILE_TYPE; + } + } + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java new file mode 100644 index 00000000..1017c46b --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java @@ -0,0 +1,326 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.core.registry.AgentThreadPoolExecutorHolder; +import cn.hippo4j.agent.core.registry.AgentThreadPoolInstanceRegistry; +import cn.hippo4j.agent.core.util.ThreadPoolPropertyKey; +import cn.hippo4j.agent.plugin.spring.common.SpringPropertiesLoader; +import cn.hippo4j.common.executor.support.BlockingQueueTypeEnum; +import cn.hippo4j.common.executor.support.RejectedPolicyTypeEnum; +import cn.hippo4j.common.executor.support.ResizableCapacityLinkedBlockingQueue; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.MapUtil; +import cn.hippo4j.common.toolkit.ThreadPoolExecutorUtil; +import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; +import cn.hippo4j.common.config.ExecutorProperties; +import cn.hippo4j.config.springboot.starter.parser.ConfigFileTypeEnum; +import cn.hippo4j.config.springboot.starter.parser.ConfigParserHandler; +import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; +import cn.hippo4j.message.request.ChangeParameterNotifyRequest; +import com.ctrip.framework.apollo.ConfigChangeListener; +import com.ctrip.framework.apollo.ConfigFile; +import com.ctrip.framework.apollo.ConfigService; +import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; +import com.ctrip.framework.apollo.model.ConfigChange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.support.ResourceEditorRegistrar; +import org.springframework.boot.bind.CustomPropertyNamePatternsMatcher; +import org.springframework.boot.bind.RelaxedDataBinder; +import org.springframework.boot.bind.RelaxedNames; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import static cn.hippo4j.agent.core.conf.Constants.SPRING_BOOT_CONFIG_PREFIX; +import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER; +import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_THREAD_POOL_TEXT; +import static cn.hippo4j.config.springboot1x.starter.refresher.SpringBoot1xBootstrapConfigPropertiesBinderAdapt.getNames; + +public class EventPublishingFinishedInterceptor implements InstanceMethodsAroundInterceptor { + + private static final ILog FILE_LOGGER = LogManager.getLogger(EventPublishingFinishedInterceptor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EventPublishingFinishedInterceptor.class); + + @Override + public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + + } + + @Override + public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { + ConfigurableApplicationContext context = (ConfigurableApplicationContext) allArguments[0]; + SpringPropertiesLoader.loadSpringProperties(context.getEnvironment()); + + List apolloNamespaces = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.Apollo.NAMESPACE; + + String namespace = apolloNamespaces.get(0); + String configFileType = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; + com.ctrip.framework.apollo.Config config = ConfigService.getConfig(String.format("%s.%s", namespace, configFileType)); + ConfigChangeListener configChangeListener = configChangeEvent -> { + String replacedNamespace = namespace.replaceAll("." + configFileType, ""); + ConfigFileFormat configFileFormat = ConfigFileFormat.fromString(configFileType); + ConfigFile configFile = ConfigService.getConfigFile(replacedNamespace, configFileFormat); + Map newChangeValueMap = new HashMap<>(); + configChangeEvent.changedKeys().stream().filter(each -> each.contains(SPRING_BOOT_CONFIG_PREFIX)).forEach(each -> { + ConfigChange change = configChangeEvent.getChange(each); + String newValue = change.getNewValue(); + newChangeValueMap.put(each, newValue); + }); + dynamicRefresh(configFile.getContent(), newChangeValueMap, context); + }; + config.addChangeListener(configChangeListener); + LOGGER.info("Dynamic thread pool refresher, add apollo listener success. namespace: {}", namespace); + return ret; + } + + public BootstrapConfigProperties bindProperties(Map configInfo, ApplicationContext applicationContext) { + BootstrapConfigProperties bindableCoreProperties = new BootstrapConfigProperties(); + if (MapUtil.isEmpty(configInfo)) { + return bindableCoreProperties; + } + RelaxedNames relaxedNames = new RelaxedNames(BootstrapConfigProperties.PREFIX); + Set names = getNames(bindableCoreProperties, relaxedNames); + Map stringConfigInfo = new HashMap<>(configInfo.size()); + configInfo.forEach((key, value) -> stringConfigInfo.put(key.toString(), value)); + MapPropertySource test = new MapPropertySource("Hippo4j", stringConfigInfo); + MutablePropertySources propertySources = new MutablePropertySources(); + propertySources.addFirst(test); + PropertyValues propertyValues = CustomPropertyNamePatternsMatcher.getPropertySourcesPropertyValues(names, propertySources); + RelaxedDataBinder dataBinder = new RelaxedDataBinder(bindableCoreProperties, BootstrapConfigProperties.PREFIX); + dataBinder.setAutoGrowCollectionLimit(Integer.MAX_VALUE); + dataBinder.setIgnoreNestedProperties(false); + dataBinder.setIgnoreInvalidFields(false); + dataBinder.setIgnoreUnknownFields(true); + ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar(applicationContext, applicationContext.getEnvironment()); + resourceEditorRegistrar.registerCustomEditors(dataBinder); + dataBinder.bind(propertyValues); + return bindableCoreProperties; + } + + public void dynamicRefresh(String configContent, Map newValueChangeMap, ApplicationContext context) { + try { + String configFileType = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; + + Map afterConfigMap = ConfigParserHandler.getInstance().parseConfig(configContent, + ConfigFileTypeEnum.of(configFileType)); + if (CollectionUtil.isNotEmpty(newValueChangeMap)) { + Optional.ofNullable(afterConfigMap).ifPresent(each -> each.putAll(newValueChangeMap)); + } + BootstrapConfigProperties afterConfigProperties = bindProperties(afterConfigMap, context); + + List executors = afterConfigProperties.getExecutors(); + for (ExecutorProperties afterProperties : executors) { + String threadPoolId = afterProperties.getThreadPoolId(); + AgentThreadPoolExecutorHolder holder = AgentThreadPoolInstanceRegistry.getInstance().getHolder(threadPoolId); + if (holder.isEmpty() || holder.getExecutor() == null) { + continue; + } + ExecutorProperties beforeProperties = convert(holder.getProperties()); + + if (!checkConsistency(threadPoolId, beforeProperties, afterProperties)) { + continue; + } + + dynamicRefreshPool(beforeProperties, afterProperties); + holder.setProperties(failDefaultExecutorProperties(beforeProperties, afterProperties)); // do refresh. + ChangeParameterNotifyRequest changeRequest = buildChangeRequest(beforeProperties, afterProperties); + LOGGER.info(CHANGE_THREAD_POOL_TEXT, + threadPoolId, + String.format(CHANGE_DELIMITER, beforeProperties.getCorePoolSize(), changeRequest.getNowCorePoolSize()), + String.format(CHANGE_DELIMITER, beforeProperties.getMaximumPoolSize(), changeRequest.getNowMaximumPoolSize()), + String.format(CHANGE_DELIMITER, beforeProperties.getQueueCapacity(), changeRequest.getNowQueueCapacity()), + String.format(CHANGE_DELIMITER, beforeProperties.getKeepAliveTime(), changeRequest.getNowKeepAliveTime()), + String.format(CHANGE_DELIMITER, beforeProperties.getExecuteTimeOut(), changeRequest.getNowExecuteTimeOut()), + String.format(CHANGE_DELIMITER, beforeProperties.getRejectedHandler(), changeRequest.getNowRejectedName()), + String.format(CHANGE_DELIMITER, beforeProperties.getAllowCoreThreadTimeOut(), changeRequest.getNowAllowsCoreThreadTimeOut())); + } + } catch (Exception ex) { + LOGGER.error("[Hippo4j-Agent] config mode dynamic refresh failed.", ex); + } + } + + /** + * Dynamic refresh pool. + */ + private void dynamicRefreshPool(ExecutorProperties beforeProperties, ExecutorProperties afterProperties) { + AgentThreadPoolExecutorHolder holder = AgentThreadPoolInstanceRegistry.getInstance().getHolder(afterProperties.getThreadPoolId()); + ThreadPoolExecutor executor = holder.getExecutor(); + if (afterProperties.getMaximumPoolSize() != null && afterProperties.getCorePoolSize() != null) { + ThreadPoolExecutorUtil.safeSetPoolSize(executor, afterProperties.getCorePoolSize(), afterProperties.getMaximumPoolSize()); + } else { + if (afterProperties.getMaximumPoolSize() != null) { + executor.setMaximumPoolSize(afterProperties.getMaximumPoolSize()); + } + if (afterProperties.getCorePoolSize() != null) { + executor.setCorePoolSize(afterProperties.getCorePoolSize()); + } + } + if (afterProperties.getAllowCoreThreadTimeOut() != null && !Objects.equals(beforeProperties.getAllowCoreThreadTimeOut(), afterProperties.getAllowCoreThreadTimeOut())) { + executor.allowCoreThreadTimeOut(afterProperties.getAllowCoreThreadTimeOut()); + } + if (afterProperties.getExecuteTimeOut() != null && !Objects.equals(beforeProperties.getExecuteTimeOut(), afterProperties.getExecuteTimeOut())) { + if (executor instanceof DynamicThreadPoolExecutor) { + ((DynamicThreadPoolExecutor) executor).setExecuteTimeOut(afterProperties.getExecuteTimeOut()); + } + } + if (afterProperties.getRejectedHandler() != null && !Objects.equals(beforeProperties.getRejectedHandler(), afterProperties.getRejectedHandler())) { + RejectedExecutionHandler rejectedExecutionHandler = RejectedPolicyTypeEnum.createPolicy(afterProperties.getRejectedHandler()); + executor.setRejectedExecutionHandler(rejectedExecutionHandler); + } + if (afterProperties.getKeepAliveTime() != null && !Objects.equals(beforeProperties.getKeepAliveTime(), afterProperties.getKeepAliveTime())) { + executor.setKeepAliveTime(afterProperties.getKeepAliveTime(), TimeUnit.SECONDS); + } + if (afterProperties.getQueueCapacity() != null && !Objects.equals(beforeProperties.getQueueCapacity(), afterProperties.getQueueCapacity()) + && Objects.equals(BlockingQueueTypeEnum.RESIZABLE_LINKED_BLOCKING_QUEUE.getName(), executor.getQueue().getClass().getSimpleName())) { + if (executor.getQueue() instanceof ResizableCapacityLinkedBlockingQueue) { + ResizableCapacityLinkedBlockingQueue queue = (ResizableCapacityLinkedBlockingQueue) executor.getQueue(); + queue.setCapacity(afterProperties.getQueueCapacity()); + } else { + LOGGER.warn("The queue length cannot be modified. Queue type mismatch. Current queue type: {}", executor.getQueue().getClass().getSimpleName()); + } + } + } + + /** + * Fail default executor properties. + * + * @param beforeProperties old properties + * @param afterProperties new properties + * @return executor properties + */ + private Properties failDefaultExecutorProperties(ExecutorProperties beforeProperties, ExecutorProperties afterProperties) { + return convert(ExecutorProperties.builder() + .corePoolSize(Optional.ofNullable(afterProperties.getCorePoolSize()).orElse(beforeProperties.getCorePoolSize())) + .maximumPoolSize(Optional.ofNullable(afterProperties.getMaximumPoolSize()).orElse(beforeProperties.getMaximumPoolSize())) + .blockingQueue(afterProperties.getBlockingQueue()) + .queueCapacity(Optional.ofNullable(afterProperties.getQueueCapacity()).orElse(beforeProperties.getQueueCapacity())) + .keepAliveTime(Optional.ofNullable(afterProperties.getKeepAliveTime()).orElse(beforeProperties.getKeepAliveTime())) + .executeTimeOut(Optional.ofNullable(afterProperties.getExecuteTimeOut()).orElse(beforeProperties.getExecuteTimeOut())) + .rejectedHandler(Optional.ofNullable(afterProperties.getRejectedHandler()).orElse(beforeProperties.getRejectedHandler())) + .allowCoreThreadTimeOut(Optional.ofNullable(afterProperties.getAllowCoreThreadTimeOut()).orElse(beforeProperties.getAllowCoreThreadTimeOut())) + .threadPoolId(beforeProperties.getThreadPoolId()) + .build()); + } + + private ExecutorProperties convert(Properties properties) { + return ExecutorProperties.builder() + .threadPoolId((String) properties.get(ThreadPoolPropertyKey.THREAD_POOL_ID)) + .corePoolSize((Integer) properties.get(ThreadPoolPropertyKey.CORE_POOL_SIZE)) + .maximumPoolSize((Integer) properties.get(ThreadPoolPropertyKey.MAXIMUM_POOL_SIZE)) + .allowCoreThreadTimeOut((Boolean) properties.get(ThreadPoolPropertyKey.ALLOW_CORE_THREAD_TIME_OUT)) + .keepAliveTime((Long) properties.get(ThreadPoolPropertyKey.KEEP_ALIVE_TIME)) + .blockingQueue((String) properties.get(ThreadPoolPropertyKey.BLOCKING_QUEUE)) + .queueCapacity((Integer) properties.get(ThreadPoolPropertyKey.QUEUE_CAPACITY)) + .threadNamePrefix((String) properties.get(ThreadPoolPropertyKey.THREAD_NAME_PREFIX)) + .rejectedHandler((String) properties.get(ThreadPoolPropertyKey.REJECTED_HANDLER)) + .executeTimeOut((Long) properties.get(ThreadPoolPropertyKey.EXECUTE_TIME_OUT)) + .build(); + } + + private Properties convert(ExecutorProperties executorProperties) { + Properties properties = new Properties(); + Optional.ofNullable(executorProperties.getCorePoolSize()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.CORE_POOL_SIZE, v)); + Optional.ofNullable(executorProperties.getMaximumPoolSize()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.MAXIMUM_POOL_SIZE, v)); + Optional.ofNullable(executorProperties.getBlockingQueue()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.BLOCKING_QUEUE, v)); + Optional.ofNullable(executorProperties.getQueueCapacity()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.QUEUE_CAPACITY, v)); + Optional.ofNullable(executorProperties.getKeepAliveTime()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.KEEP_ALIVE_TIME, v)); + Optional.ofNullable(executorProperties.getExecuteTimeOut()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.EXECUTE_TIME_OUT, v)); + Optional.ofNullable(executorProperties.getRejectedHandler()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.REJECTED_HANDLER, v)); + Optional.ofNullable(executorProperties.getAllowCoreThreadTimeOut()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.ALLOW_CORE_THREAD_TIME_OUT, v)); + Optional.ofNullable(executorProperties.getThreadPoolId()).ifPresent(v -> properties.put(ThreadPoolPropertyKey.THREAD_POOL_ID, v)); + return properties; + } + + /** + * Construct change parameter notify request instance. + * + * @param beforeProperties old properties + * @param afterProperties new properties + * @return instance + */ + private ChangeParameterNotifyRequest buildChangeRequest(ExecutorProperties beforeProperties, ExecutorProperties afterProperties) { + ChangeParameterNotifyRequest changeParameterNotifyRequest = ChangeParameterNotifyRequest.builder() + .beforeCorePoolSize(beforeProperties.getCorePoolSize()) + .beforeMaximumPoolSize(beforeProperties.getMaximumPoolSize()) + .beforeAllowsCoreThreadTimeOut(beforeProperties.getAllowCoreThreadTimeOut()) + .beforeKeepAliveTime(beforeProperties.getKeepAliveTime()) + .beforeQueueCapacity(beforeProperties.getQueueCapacity()) + .beforeRejectedName(beforeProperties.getRejectedHandler()) + .beforeExecuteTimeOut(beforeProperties.getExecuteTimeOut()) + .blockingQueueName(afterProperties.getBlockingQueue()) + .nowCorePoolSize(Optional.ofNullable(afterProperties.getCorePoolSize()).orElse(beforeProperties.getCorePoolSize())) + .nowMaximumPoolSize(Optional.ofNullable(afterProperties.getMaximumPoolSize()).orElse(beforeProperties.getMaximumPoolSize())) + .nowAllowsCoreThreadTimeOut(Optional.ofNullable(afterProperties.getAllowCoreThreadTimeOut()).orElse(beforeProperties.getAllowCoreThreadTimeOut())) + .nowKeepAliveTime(Optional.ofNullable(afterProperties.getKeepAliveTime()).orElse(beforeProperties.getKeepAliveTime())) + .nowQueueCapacity(Optional.ofNullable(afterProperties.getQueueCapacity()).orElse(beforeProperties.getQueueCapacity())) + .nowRejectedName(Optional.ofNullable(afterProperties.getRejectedHandler()).orElse(beforeProperties.getRejectedHandler())) + .nowExecuteTimeOut(Optional.ofNullable(afterProperties.getExecuteTimeOut()).orElse(beforeProperties.getExecuteTimeOut())) + .build(); + changeParameterNotifyRequest.setThreadPoolId(beforeProperties.getThreadPoolId()); + return changeParameterNotifyRequest; + } + + /** + * Check consistency. + * + * @param threadPoolId + * @param afterProperties + */ + private boolean checkConsistency(String threadPoolId, ExecutorProperties beforeProperties, ExecutorProperties afterProperties) { + AgentThreadPoolExecutorHolder holder = AgentThreadPoolInstanceRegistry.getInstance().getHolder(threadPoolId); + if (holder.isEmpty() || holder.getExecutor() == null) { + return false; + } + ThreadPoolExecutor executor = holder.getExecutor(); + return (afterProperties.getCorePoolSize() != null && !Objects.equals(beforeProperties.getCorePoolSize(), afterProperties.getCorePoolSize())) + || (afterProperties.getMaximumPoolSize() != null && !Objects.equals(beforeProperties.getMaximumPoolSize(), afterProperties.getMaximumPoolSize())) + || (afterProperties.getAllowCoreThreadTimeOut() != null && !Objects.equals(beforeProperties.getAllowCoreThreadTimeOut(), afterProperties.getAllowCoreThreadTimeOut())) + || (afterProperties.getExecuteTimeOut() != null && !Objects.equals(beforeProperties.getExecuteTimeOut(), afterProperties.getExecuteTimeOut())) + || (afterProperties.getKeepAliveTime() != null && !Objects.equals(beforeProperties.getKeepAliveTime(), afterProperties.getKeepAliveTime())) + || (afterProperties.getRejectedHandler() != null && !Objects.equals(beforeProperties.getRejectedHandler(), afterProperties.getRejectedHandler())) + || + ((afterProperties.getQueueCapacity() != null && !Objects.equals(beforeProperties.getQueueCapacity(), afterProperties.getQueueCapacity()) + && Objects.equals(BlockingQueueTypeEnum.RESIZABLE_LINKED_BLOCKING_QUEUE.getName(), executor.getQueue().getClass().getSimpleName()))); + } + + @Override + public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java new file mode 100644 index 00000000..1ac06ade --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1; + +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.plugin.spring.common.SpringEnvironmentSupport; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.ConfigurableEnvironment; + +import java.lang.reflect.Method; + +public class EventPublishingRunListenerEnvironmentPreparedInterceptor implements InstanceMethodsAroundInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(EventPublishingRunListenerEnvironmentPreparedInterceptor.class); + + @Override + public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + + } + + @Override + public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { + ConfigurableEnvironment environment = (ConfigurableEnvironment) allArguments[0]; + SpringEnvironmentSupport.disableNonAgentSwitch(environment); + LOGGER.info("[Hippo4j-Agent] Switch off in non-Agent mode."); + return ret; + } + + @Override + public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java new file mode 100644 index 00000000..f75980f4 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1; + +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.core.registry.AgentThreadPoolInstanceRegistry; +import cn.hippo4j.agent.core.util.ReflectUtil; +import cn.hippo4j.agent.core.util.ThreadPoolPropertyKey; +import cn.hippo4j.common.executor.support.BlockingQueueTypeEnum; +import cn.hippo4j.common.executor.support.RejectedPolicyTypeEnum; +import cn.hippo4j.common.toolkit.BooleanUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class SpringApplicationRunInterceptor implements InstanceMethodsAroundInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SpringApplicationRunInterceptor.class); + + @Override + public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + + } + + @Override + public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { + registerThreadPoolInstances(); + LOGGER.info("[Hippo4j-Agent] Registered thread pool instances successfully."); + return ret; + } + + private void registerThreadPoolInstances() { + Map> earlyConstructMap = AgentThreadPoolInstanceRegistry.getInstance().earlyConstructMap; + for (Map.Entry> entry : earlyConstructMap.entrySet()) { + ThreadPoolExecutor enhancedInstance = entry.getKey(); + Class declaredClass = entry.getValue(); + List declaredFields = ReflectUtil.getStaticFieldsFromType(declaredClass, ThreadPoolExecutor.class); + for (Field field : declaredFields) { + try { + Object value = field.get(null); + if (value == enhancedInstance) { + String threadPoolId = declaredClass.getName() + "#" + field.getName(); + register(threadPoolId, enhancedInstance); + break; + } + } catch (IllegalAccessException e) { + LOGGER.error("Get static field error.", e); + } + } + } + } + + private void register(String threadPoolId, ThreadPoolExecutor executor) { + // build parameter properties. + Properties properties = new Properties(); + properties.put(ThreadPoolPropertyKey.THREAD_POOL_ID, threadPoolId); + properties.put(ThreadPoolPropertyKey.CORE_POOL_SIZE, executor.getCorePoolSize()); + properties.put(ThreadPoolPropertyKey.MAXIMUM_POOL_SIZE, executor.getMaximumPoolSize()); + properties.put(ThreadPoolPropertyKey.ALLOW_CORE_THREAD_TIME_OUT, BooleanUtil.toBoolean(String.valueOf(executor.allowsCoreThreadTimeOut()))); + properties.put(ThreadPoolPropertyKey.KEEP_ALIVE_TIME, executor.getKeepAliveTime(TimeUnit.MILLISECONDS)); + properties.put(ThreadPoolPropertyKey.BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName(executor.getQueue().getClass().getSimpleName()).getName()); + properties.put(ThreadPoolPropertyKey.QUEUE_CAPACITY, executor.getQueue().remainingCapacity()); + properties.put(ThreadPoolPropertyKey.THREAD_NAME_PREFIX, threadPoolId); + properties.put(ThreadPoolPropertyKey.REJECTED_HANDLER, RejectedPolicyTypeEnum.getRejectedPolicyTypeEnumByName(executor.getRejectedExecutionHandler().getClass().getSimpleName()).getName()); + properties.put(ThreadPoolPropertyKey.EXECUTE_TIME_OUT, 10000L); + + // register executor. + AgentThreadPoolInstanceRegistry.getInstance().putHolder(threadPoolId, executor, properties); + + } + + @Override + public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java new file mode 100644 index 00000000..c4b5cc31 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1.define; + +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.match.ClassMatch; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +import static net.bytebuddy.matcher.ElementMatchers.named; +import static cn.hippo4j.agent.core.plugin.match.NameMatch.byName; + +public class EventPublishingRunListenerInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { + + private static final String ENHANCE_CLASS = "org.springframework.boot.context.event.EventPublishingRunListener"; + + private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.EventPublishingFinishedInterceptor"; + private static final String EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.EventPublishingRunListenerEnvironmentPreparedInterceptor"; + + @Override + protected ClassMatch enhanceClass() { + return byName(ENHANCE_CLASS); + } + + @Override + public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { + return new ConstructorInterceptPoint[0]; + } + + @Override + public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { + return new InstanceMethodsInterceptPoint[]{ + new InstanceMethodsInterceptPoint() { + + @Override + public ElementMatcher getMethodsMatcher() { + return named("finished"); + } + + @Override + public String getMethodsInterceptor() { + return EVENT_PUBLISHING_FINISHED_INTERCEPTOR; + } + + @Override + public boolean isOverrideArgs() { + return false; + } + }, + new InstanceMethodsInterceptPoint() { + + @Override + public ElementMatcher getMethodsMatcher() { + return named("environmentPrepared"); + } + + @Override + public String getMethodsInterceptor() { + return EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR; + } + + @Override + public boolean isOverrideArgs() { + return false; + } + } + }; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java new file mode 100644 index 00000000..ea2403a3 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1.define; + +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.match.ClassMatch; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +import static cn.hippo4j.agent.core.plugin.match.NameMatch.byName; +import static net.bytebuddy.matcher.ElementMatchers.named; + +public class SpringApplicationRunInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { + + private static final String ENHANCE_CLASS = "org.springframework.boot.SpringApplication"; + + private static final String SPRING_APPLICATION_RUN_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.SpringApplicationRunInterceptor"; + + @Override + protected ClassMatch enhanceClass() { + return byName(ENHANCE_CLASS); + } + + @Override + public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { + return new ConstructorInterceptPoint[0]; + } + + @Override + public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { + return new InstanceMethodsInterceptPoint[]{ + new InstanceMethodsInterceptPoint() { + + @Override + public ElementMatcher getMethodsMatcher() { + return named("run"); + } + + @Override + public String getMethodsInterceptor() { + return SPRING_APPLICATION_RUN_INTERCEPTOR; + } + + @Override + public boolean isOverrideArgs() { + return false; + } + } + }; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def new file mode 100644 index 00000000..bcea5121 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +spring-boot-1.x=cn.hippo4j.agent.plugin.spring.boot.v1.define.EventPublishingRunListenerInstrumentation +spring-boot-1.x=cn.hippo4j.agent.plugin.spring.boot.v1.define.SpringApplicationRunInstrumentation \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml new file mode 100644 index 00000000..bf7b5712 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + cn.hippo4j + spring-plugins + ${revision} + + + spring-boot-2.x-plugin + jar + + + 2.3.2.RELEASE + + + + + cn.hippo4j + spring-plugin-common + provided + + + + org.springframework.boot + spring-boot-autoconfigure + ${spring.boot.version} + provided + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java new file mode 100644 index 00000000..762b63a7 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v2; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.plugin.spring.common.SpringPropertiesLoader; +import org.springframework.context.ConfigurableApplicationContext; + +import java.lang.reflect.Method; + +public class EventPublishingStartedInterceptor implements InstanceMethodsAroundInterceptor { + + private static final ILog LOGGER = LogManager.getLogger(EventPublishingStartedInterceptor.class); + + @Override + public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + + } + + @Override + public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { + ConfigurableApplicationContext context = (ConfigurableApplicationContext) allArguments[0]; + SpringPropertiesLoader.loadSpringProperties(context.getEnvironment()); + return ret; + } + + @Override + public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java new file mode 100644 index 00000000..c3e46ed6 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v2.define; + +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.match.ClassMatch; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +import static net.bytebuddy.matcher.ElementMatchers.named; +import static cn.hippo4j.agent.core.plugin.match.NameMatch.byName; + +public class EventPublishingRunListenerInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { + + private static final String ENHANCE_CLASS = "org.springframework.boot.context.event.EventPublishingRunListener"; + + private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v2.EventPublishingStartedInterceptor"; + + @Override + protected ClassMatch enhanceClass() { + return byName(ENHANCE_CLASS); + } + + @Override + public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { + return new ConstructorInterceptPoint[0]; + } + + @Override + public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { + return new InstanceMethodsInterceptPoint[]{ + new InstanceMethodsInterceptPoint() { + + @Override + public ElementMatcher getMethodsMatcher() { + return named("started"); + } + + @Override + public String getMethodsInterceptor() { + return EVENT_PUBLISHING_FINISHED_INTERCEPTOR; + } + + @Override + public boolean isOverrideArgs() { + return false; + } + } + }; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/resources/hippo4j-plugin.def b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/resources/hippo4j-plugin.def new file mode 100644 index 00000000..8dad75ea --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/resources/hippo4j-plugin.def @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +spring-boot-2.x=cn.hippo4j.agent.plugin.spring.boot.v2.define.EventPublishingRunListenerInstrumentation \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-sdk-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml similarity index 55% rename from hippo4j-agent/hippo4j-sdk-plugin/pom.xml rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml index 7df2b687..f6ea99a8 100644 --- a/hippo4j-agent/hippo4j-sdk-plugin/pom.xml +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml @@ -5,16 +5,18 @@ 4.0.0 cn.hippo4j - hippo4j-agent + spring-plugins ${revision} - hippo4j-sdk-plugin + spring-plugin-common - - 8 - 8 - UTF-8 - + + + org.springframework + spring-core + provided + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java new file mode 100644 index 00000000..0d93bae3 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.common; + +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; + +import java.util.HashMap; +import java.util.Map; + +public class SpringEnvironmentSupport { + + public static void disableNonAgentSwitch(ConfigurableEnvironment environment) { + Map map = new HashMap<>(); + map.put("spring.dynamic.thread-pool.enable", false); // Switch off in non-Agent mode + MapPropertySource propertySource = new MapPropertySource("Hippo4j-Agent-Properties", map); + environment.getPropertySources().addFirst(propertySource); + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java new file mode 100644 index 00000000..485a7669 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.common; + +import cn.hippo4j.agent.core.boot.SpringBootConfigInitializer; +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.PropertySource; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; + +public class SpringPropertiesLoader { + + private static final ILog LOGGER = LogManager.getLogger(SpringPropertiesLoader.class); + + public static void loadSpringProperties(ConfigurableEnvironment environment) { + Iterator> iterator = environment.getPropertySources().iterator(); + Properties properties = new Properties(); + List> propertySourceList = new ArrayList<>(); + while (iterator.hasNext()) { + propertySourceList.add(iterator.next()); + } + for (int i = propertySourceList.size() - 1; i >= 0; i--) { + PropertySource propertySource = propertySourceList.get(i); + if (!(propertySource instanceof EnumerablePropertySource)) { + LOGGER.warn("Skip propertySource[{}] because {} not enumerable.", propertySource.getName(), propertySource.getClass()); + continue; + } + LOGGER.info("Load propertySource[{}] into SpringProperties.", propertySource.getName()); + EnumerablePropertySource enumerablePropertySource = (EnumerablePropertySource) propertySource; + String[] keys = enumerablePropertySource.getPropertyNames(); + for (String key : keys) { + Object value = null; + try { + value = enumerablePropertySource.getProperty(key); + if (value != null) { + properties.put(key.toLowerCase(), value.toString()); + } + } catch (Throwable e) { + LOGGER.warn("Put property to spring properties failed, key=[{}], value=[{}]", key, value); + } + } + } + SpringBootConfigInitializer.setSpringProperties(properties); + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/pom.xml new file mode 100644 index 00000000..ac99d683 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + cn.hippo4j + hippo4j-agent-plugin + ${revision} + + + thread-pool-plugin + + + + cn.hippo4j + hippo4j-core + ${project.version} + provided + + + cn.hippo4j + hippo4j-common + ${project.version} + + + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java new file mode 100644 index 00000000..1f6835b4 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.thread.pool; + +import cn.hippo4j.agent.core.conf.Config; +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor; +import cn.hippo4j.agent.core.registry.AgentThreadPoolInstanceRegistry; +import cn.hippo4j.agent.core.util.CollectionUtil; +import cn.hippo4j.agent.core.util.StringUtil; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadPoolExecutor; + +public class ThreadPoolExecutorConstructorMethodInterceptor implements InstanceConstructorInterceptor { + + private static final ILog LOGGER = LogManager.getLogger(ThreadPoolExecutorConstructorMethodInterceptor.class); + + private static final List EXCLUDE_STACK_TRACE_ELEMENT_CLASS_PREFIX = Arrays.asList("java", "cn.hippo4j.agent"); + + @Override + public void onConstruct(EnhancedInstance objInst, Object[] allArguments) throws Throwable { + + List stackTraceElements = getStackTraceElements(); + if (CollectionUtil.isEmpty(stackTraceElements)) { + return; + } + StackTraceElement declaredClassStackTraceElement = stackTraceElements.get(0); + String declaredClassName = declaredClassStackTraceElement.getClassName(); + Class declaredClass = Thread.currentThread().getContextClassLoader().loadClass(declaredClassName); + AgentThreadPoolInstanceRegistry.getInstance().earlyConstructMap.put((ThreadPoolExecutor) objInst, declaredClass); + } + + private List getStackTraceElements() { + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + int i; + for (i = 0; i < stackTraceElements.length; i++) { + String fullClassName = stackTraceElements[i].getClassName(); + if (isBusinessStackTraceClassName(fullClassName)) { + if (isExcludeThreadPoolClass(fullClassName)) { + return Collections.emptyList(); + } else { + break; + } + } + } + + List result = new ArrayList<>(3); // Find up to three layers + for (int j = 0; i < stackTraceElements.length && j < 3; i++, j++) { + String fullClassName = stackTraceElements[i].getClassName(); + if (isExcludeThreadPoolClass(fullClassName)) { + break; + } else { + result.add(stackTraceElements[i]); + } + } + + return result; + } + + private boolean isBusinessStackTraceClassName(String className) { + for (String prefix : EXCLUDE_STACK_TRACE_ELEMENT_CLASS_PREFIX) { + if (className.startsWith(prefix)) { + return false; + } + } + return true; + } + private boolean isExcludeThreadPoolClass(String className) { + if (StringUtil.isBlank(className)) { + return true; + } + List excludePackagePrefix = Config.Plugin.ThreadPool.EXCLUDE_PACKAGE_PREFIX; + for (String excludePrefix : excludePackagePrefix) { + if (className.startsWith(excludePrefix)) { + return true; + } + } + return false; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java new file mode 100644 index 00000000..d437e0d5 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.thread.pool.define; + +import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; +import cn.hippo4j.agent.core.plugin.match.ClassMatch; +import cn.hippo4j.agent.core.plugin.match.NameMatch; +import net.bytebuddy.description.method.MethodDescription; +import net.bytebuddy.matcher.ElementMatcher; + +import static net.bytebuddy.matcher.ElementMatchers.takesArguments; + +public class ThreadPoolExecutorInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { + + private static final String ENHANCE_CLASS = "java.util.concurrent.ThreadPoolExecutor"; + + private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.thread.pool.ThreadPoolExecutorConstructorMethodInterceptor"; + + private static final int CONSTRUCTOR_INTERCEPT_PARAMETER_LENGTH = 7; + + @Override + protected ClassMatch enhanceClass() { + return NameMatch.byName(ENHANCE_CLASS); + } + + @Override + public boolean isBootstrapInstrumentation() { + return true; + } + + /** + * The constructor method that only intercepts all parameters prevents repeated interception. + */ + @Override + public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { + return new ConstructorInterceptPoint[]{ + new ConstructorInterceptPoint() { + + @Override + public ElementMatcher getConstructorMatcher() { + return takesArguments(CONSTRUCTOR_INTERCEPT_PARAMETER_LENGTH); + } + + @Override + public String getConstructorInterceptor() { + return CONSTRUCTOR_INTERCEPT_CLASS; + } + } + }; + } + + @Override + public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { + return new InstanceMethodsInterceptPoint[0]; + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/resources/hippo4j-plugin.def b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/resources/hippo4j-plugin.def new file mode 100644 index 00000000..d84d9489 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/resources/hippo4j-plugin.def @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +thread-pool-plugin=cn.hippo4j.agent.plugin.thread.pool.define.ThreadPoolExecutorInstrumentation \ No newline at end of file diff --git a/hippo4j-agent/pom.xml b/hippo4j-agent/pom.xml index ccd31a3d..5eac2289 100644 --- a/hippo4j-agent/pom.xml +++ b/hippo4j-agent/pom.xml @@ -13,7 +13,8 @@ pom hippo4j-agent-core - hippo4j-sdk-plugin + hippo4j-agent-plugin + hippo4j-agent-bootstrap @@ -56,53 +57,56 @@ 1.33 1.5 true - + 1.7.25 + 30.1.1-jre + 2.16.0 - - - - org.powermock - powermock-api-mockito2 - test - - - net.bytebuddy - byte-buddy-agent - test - - - org.objenesis - objenesis - test - - - org.openjdk.jmh - jmh-core - ${jmh.version} - test - - - org.projectlombok - lombok - ${lombok.version} - provided - - - javax.annotation - javax.annotation-api - ${javax.annotation-api.version} - provided - - - org.powermock - powermock-module-junit4 - test - - - + + cn.hippo4j + hippo4j-agent-core + ${project.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.google.guava + guava + ${guava.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + javax.annotation + javax.annotation-api + ${javax.annotation-api.version} + provided + junit junit @@ -125,7 +129,6 @@ net.bytebuddy byte-buddy-agent ${bytebuddy.version} - test org.objenesis @@ -133,6 +136,12 @@ ${objenesis.version} test + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + org.openjdk.jmh jmh-generator-annprocess @@ -212,9 +221,6 @@ 1.8 - - 3.6 - diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/api/IExecutorProperties.java b/hippo4j-common/src/main/java/cn/hippo4j/common/api/IExecutorProperties.java index 7df4dd8c..6fb60f45 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/api/IExecutorProperties.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/api/IExecutorProperties.java @@ -17,6 +17,8 @@ package cn.hippo4j.common.api; +import cn.hippo4j.common.config.ExecutorNotifyProperties; + /** * Interface for thread pool configuration. */ diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/api/ThreadPoolCheckAlarm.java b/hippo4j-common/src/main/java/cn/hippo4j/common/api/ThreadPoolCheckAlarm.java index 4b3a3f2a..5c07bd98 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/api/ThreadPoolCheckAlarm.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/api/ThreadPoolCheckAlarm.java @@ -118,7 +118,7 @@ public interface ThreadPoolCheckAlarm extends CommandLineRunner { */ @Override public void asyncSendRejectedAlarm(String threadPoolId) { - log.info("Ignore async send rejected alarm for ExecuteService '{}'", threadPoolId); + log.debug("Ignore async send rejected alarm for ExecuteService '{}'", threadPoolId); } /** @@ -131,7 +131,7 @@ public interface ThreadPoolCheckAlarm extends CommandLineRunner { */ @Override public void asyncSendExecuteTimeOutAlarm(String threadPoolId, long executeTime, long executeTimeOut, ThreadPoolExecutor threadPoolExecutor) { - log.info("Ignore async send execute time out alarm for ExecuteService '{}'", threadPoolId); + log.debug("Ignore async send execute time out alarm for ExecuteService '{}'", threadPoolId); } @Override diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/api/ExecutorNotifyProperties.java b/hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorNotifyProperties.java similarity index 97% rename from hippo4j-common/src/main/java/cn/hippo4j/common/api/ExecutorNotifyProperties.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorNotifyProperties.java index 9334e9db..647c6d9b 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/api/ExecutorNotifyProperties.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorNotifyProperties.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.common.api; +package cn.hippo4j.common.config; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/ExecutorProperties.java b/hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorProperties.java similarity index 95% rename from hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/ExecutorProperties.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorProperties.java index 9d179d22..fb33a0dd 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/ExecutorProperties.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/config/ExecutorProperties.java @@ -15,9 +15,8 @@ * limitations under the License. */ -package cn.hippo4j.config.springboot.starter.config; +package cn.hippo4j.common.config; -import cn.hippo4j.common.api.ExecutorNotifyProperties; import cn.hippo4j.common.api.IExecutorProperties; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java index 32b79cce..2b651ffc 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java @@ -113,4 +113,6 @@ public class Constants { public static final int HTTP_EXECUTE_TIMEOUT = 5000; public static final String CLIENT_VERSION = "Client-Version"; + + public static final String CONFIGURATION_PROPERTIES_PREFIX = "spring.dynamic.thread-pool"; } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/executor/support/BlockingQueueTypeEnum.java b/hippo4j-common/src/main/java/cn/hippo4j/common/executor/support/BlockingQueueTypeEnum.java index 4f2205b4..933863ac 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/executor/support/BlockingQueueTypeEnum.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/executor/support/BlockingQueueTypeEnum.java @@ -20,8 +20,18 @@ package cn.hippo4j.common.executor.support; import cn.hippo4j.common.extension.support.ServiceLoaderRegistry; import lombok.Getter; -import java.util.*; -import java.util.concurrent.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.LinkedTransferQueue; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.SynchronousQueue; import java.util.function.Predicate; /** diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/annotation/Realization.java b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/annotation/Realization.java index d0981ac6..98da0631 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/annotation/Realization.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/annotation/Realization.java @@ -19,7 +19,11 @@ package cn.hippo4j.common.extension.annotation; import org.springframework.stereotype.Component; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Inherited @Retention(RetentionPolicy.RUNTIME) diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/config/ExtensionRegisterBootstrap.java b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/config/ExtensionRegisterBootstrap.java index 0dbae207..d1ee6baf 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/config/ExtensionRegisterBootstrap.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/config/ExtensionRegisterBootstrap.java @@ -20,7 +20,6 @@ package cn.hippo4j.common.extension.config; import cn.hippo4j.common.extension.IExtension; import cn.hippo4j.common.extension.annotation.Realization; import cn.hippo4j.common.extension.support.ExtensionRegistry; -import cn.hippo4j.common.toolkit.ClassUtil; import org.springframework.aop.scope.ScopedProxyUtils; import org.springframework.beans.BeansException; import org.springframework.boot.ApplicationArguments; @@ -28,9 +27,6 @@ import org.springframework.boot.ApplicationRunner; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import java.util.Map; -import java.util.stream.Collectors; - /** * Extension register bootstrap */ @@ -54,8 +50,8 @@ public class ExtensionRegisterBootstrap implements ApplicationContextAware, Appl } private boolean filterClass(String beanName, Object bean) { - return bean.getClass().isAssignableFrom(IExtension.class) || - ScopedProxyUtils.isScopedTarget(beanName) || - !(bean instanceof IExtension); + return bean.getClass().isAssignableFrom(IExtension.class) + || ScopedProxyUtils.isScopedTarget(beanName) + || !(bean instanceof IExtension); } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/reducer/Reducer.java b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/reducer/Reducer.java index 079625d2..2f3414ec 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/reducer/Reducer.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/reducer/Reducer.java @@ -24,7 +24,6 @@ import cn.hippo4j.common.extension.support.ReduceType; import lombok.Getter; import lombok.Setter; -import java.util.ArrayList; import java.util.List; public abstract class Reducer { diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ExtensionInvoker.java b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ExtensionInvoker.java index 0c748680..24d0465a 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ExtensionInvoker.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ExtensionInvoker.java @@ -33,7 +33,7 @@ import java.util.List; */ public class ExtensionInvoker { - private static final ExtensionRegistry registry = ExtensionRegistry.getInstance(); + private static final ExtensionRegistry REGISTRY = ExtensionRegistry.getInstance(); public static List reduceExecute(Class targetClz, ExtensionCallback callback) { @@ -47,7 +47,7 @@ public class ExtensionInvoker { Assert.isTrue(IExtension.class.isAssignableFrom(targetClz), "can not execute extension point. please implement base extension interface(" + IExtension.class.getName() + ") first."); - List realizations = registry.find(targetClz); + List realizations = REGISTRY.find(targetClz); if (CollectionUtil.isEmpty(realizations)) { realizations = new ArrayList<>(ServiceLoaderRegistry.getSingletonServiceInstances(targetClz)); } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ServiceLoaderRegistry.java b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ServiceLoaderRegistry.java index 493dd489..37d4a43d 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ServiceLoaderRegistry.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/extension/support/ServiceLoaderRegistry.java @@ -18,7 +18,6 @@ package cn.hippo4j.common.extension.support; import cn.hippo4j.common.extension.annotation.SingletonSPI; -import cn.hippo4j.common.extension.support.ServiceLoaderInstantiationException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java index a952351f..1de806a3 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java @@ -26,7 +26,12 @@ import lombok.NoArgsConstructor; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; /** * Bean util.
diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java index d694924a..5a1fbbca 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java @@ -17,7 +17,14 @@ package cn.hippo4j.common.toolkit; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; /** diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java index 9785698c..6df46504 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java @@ -21,7 +21,12 @@ import cn.hippo4j.common.web.exception.IllegalException; import lombok.SneakyThrows; import org.springframework.core.io.ClassPathResource; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java index 26fad185..60300777 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java @@ -74,17 +74,17 @@ public class IdUtil { long mostSigBits = uuid.getMostSignificantBits(); long leastSigBits = uuid.getLeastSignificantBits(); if (isSimple) { - return (digits(mostSigBits >> 32, 8) + - digits(mostSigBits >> 16, 4) + - digits(mostSigBits, 4) + - digits(leastSigBits >> 48, 4) + - digits(leastSigBits, 12)); + return (digits(mostSigBits >> 32, 8) + + digits(mostSigBits >> 16, 4) + + digits(mostSigBits, 4) + + digits(leastSigBits >> 48, 4) + + digits(leastSigBits, 12)); } else { - return (digits(mostSigBits >> 32, 8) + "-" + - digits(mostSigBits >> 16, 4) + "-" + - digits(mostSigBits, 4) + "-" + - digits(leastSigBits >> 48, 4) + "-" + - digits(leastSigBits, 12)); + return (digits(mostSigBits >> 32, 8) + "-" + + digits(mostSigBits >> 16, 4) + "-" + + digits(mostSigBits, 4) + "-" + + digits(leastSigBits >> 48, 4) + "-" + + digits(leastSigBits, 12)); } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java index 73948b09..5c6b00fb 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java @@ -20,7 +20,20 @@ package cn.hippo4j.common.toolkit; import cn.hippo4j.common.constant.Constants; import lombok.SneakyThrows; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.CharArrayWriter; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; import java.net.HttpURLConnection; import java.nio.channels.FileChannel; import java.util.ArrayList; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java index f86f0df2..5148c5a3 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java @@ -22,7 +22,10 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.type.CollectionType; import lombok.SneakyThrows; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java index f23b0a04..6a15ca92 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java @@ -17,7 +17,12 @@ package cn.hippo4j.common.toolkit; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Dictionary; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Predicate; @@ -176,7 +181,7 @@ public class MapUtil { * @return */ private static boolean checkKey(String key, String filters) { - if (key.indexOf(filters) > -1) { + if (key.contains(filters)) { return true; } else { return false; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java index 317740ba..6f6c2efe 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java @@ -299,8 +299,8 @@ public class ReflectUtil { public static Field findField(Object obj, String filedName, String fieldType) { Field[] fields = ReflectUtil.getFields(obj.getClass()); for (Field field : fields) { - if (field.getName().contains(filedName) && - (field.getType().getName().contains(fieldType))) { + if (field.getName().contains(filedName) + && (field.getType().getName().contains(fieldType))) { return field; } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java index 14d85b6f..b59c509d 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java @@ -23,7 +23,11 @@ import cn.hippo4j.common.constant.HttpMediaType; import cn.hippo4j.common.toolkit.MapUtil; import cn.hippo4j.common.toolkit.StringUtil; -import java.util.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; /** * Http header. diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/extension/ExtensionInvokerTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/extension/ExtensionInvokerTest.java index 343bb745..78dd68e7 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/extension/ExtensionInvokerTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/extension/ExtensionInvokerTest.java @@ -35,7 +35,9 @@ import org.junit.Test; import java.util.List; import java.util.Objects; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class ExtensionInvokerTest { diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java index 4c92830b..a73b34c1 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java @@ -20,9 +20,6 @@ package cn.hippo4j.common.toolkit; import org.junit.Test; import org.junit.Assert; -import java.util.Arrays; -import java.util.Optional; - public class StringUtilTest { @Test diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/enable/EnableDynamicThreadPool.java b/hippo4j-core/src/main/java/cn/hippo4j/core/enable/EnableDynamicThreadPool.java index 75b2a640..0b8e2488 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/enable/EnableDynamicThreadPool.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/enable/EnableDynamicThreadPool.java @@ -19,7 +19,11 @@ package cn.hippo4j.core.enable; import org.springframework.context.annotation.Import; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * Annotation to activate dynamic threadPool related configuration. diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java index bccd9e56..6a61c23d 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java @@ -25,7 +25,11 @@ import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.springframework.core.task.TaskDecorator; -import java.util.concurrent.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * Abstract build threadPool template. diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractDynamicExecutorSupport.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractDynamicExecutorSupport.java index 8dcf65fa..91de8469 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractDynamicExecutorSupport.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractDynamicExecutorSupport.java @@ -22,7 +22,14 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; -import java.util.concurrent.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * Dynamic executor configuration support. @@ -154,14 +161,14 @@ public abstract class AbstractDynamicExecutorSupport extends ThreadPoolExecutor try { if (!executor.awaitTermination(this.awaitTerminationMillis, TimeUnit.MILLISECONDS)) { if (log.isWarnEnabled()) { - log.warn("Timed out while waiting for executor" + - (this.threadPoolId != null ? " '" + this.threadPoolId + "'" : "") + " to terminate."); + log.warn("Timed out while waiting for executor" + + (this.threadPoolId != null ? " '" + this.threadPoolId + "'" : "") + " to terminate."); } } } catch (InterruptedException ex) { if (log.isWarnEnabled()) { - log.warn("Interrupted while waiting for executor" + - (this.threadPoolId != null ? " '" + this.threadPoolId + "'" : "") + " to terminate."); + log.warn("Interrupted while waiting for executor" + + (this.threadPoolId != null ? " '" + this.threadPoolId + "'" : "") + " to terminate."); } Thread.currentThread().interrupt(); } diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadPoolExecutorTemplate.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadPoolExecutorTemplate.java index 0a1d1faf..8d073065 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadPoolExecutorTemplate.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadPoolExecutorTemplate.java @@ -19,7 +19,13 @@ package cn.hippo4j.core.executor.support; import cn.hippo4j.common.toolkit.ArrayUtil; -import java.util.concurrent.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * ThreadPool executor template. diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/handler/DynamicThreadPoolBannerHandler.java b/hippo4j-core/src/main/java/cn/hippo4j/core/handler/DynamicThreadPoolBannerHandler.java index 491499a3..0704c93e 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/handler/DynamicThreadPoolBannerHandler.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/handler/DynamicThreadPoolBannerHandler.java @@ -58,12 +58,12 @@ public class DynamicThreadPoolBannerHandler implements InitializingBean { * Print banner. */ private void printBanner() { - String banner = " __ __ ___ ___ __ \n" + - " | |--.|__|.-----..-----..-----.| | | |__|\n" + - " | || || _ || _ || _ || | | | |\n" + - " |__|__||__|| __|| __||_____||____ | | |\n" + - " |__| |__| |: ||___|\n" + - " `---' \n"; + String banner = " __ __ ___ ___ __ \n" + + " | |--.|__|.-----..-----..-----.| | | |__|\n" + + " | || || _ || _ || _ || | | | |\n" + + " |__|__||__|| __|| __||_____||____ | | |\n" + + " |__| |__| |: ||___|\n" + + " `---' \n"; if (Boolean.TRUE.equals(properties.getBanner())) { String bannerVersion = StringUtil.isNotEmpty(version) ? " (v" + version + ")" : "no version."; StringBuilder padding = new StringBuilder(); diff --git a/hippo4j-core/src/test/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandlerTest.java b/hippo4j-core/src/test/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandlerTest.java index ada71ae0..782ba281 100644 --- a/hippo4j-core/src/test/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandlerTest.java +++ b/hippo4j-core/src/test/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandlerTest.java @@ -40,7 +40,9 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static cn.hippo4j.core.toolkit.IdentifyUtil.CLIENT_IDENTIFICATION_VALUE; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class ThreadPoolRunStateHandlerTest { @@ -66,8 +68,7 @@ public class ThreadPoolRunStateHandlerTest { "Allocation: ", ByteConvertUtil.getPrintSize(used), " / Maximum available: ", - ByteConvertUtil.getPrintSize(max) - ); + ByteConvertUtil.getPrintSize(max)); String ipAddress = "127.0.0.1"; @@ -124,4 +125,3 @@ public class ThreadPoolRunStateHandlerTest { } } - diff --git a/hippo4j-core/src/test/java/cn/hippo4j/core/plugin/manager/DefaultThreadPoolPluginRegistrarTest.java b/hippo4j-core/src/test/java/cn/hippo4j/core/plugin/manager/DefaultThreadPoolPluginRegistrarTest.java index 435a8c11..ee6e5644 100644 --- a/hippo4j-core/src/test/java/cn/hippo4j/core/plugin/manager/DefaultThreadPoolPluginRegistrarTest.java +++ b/hippo4j-core/src/test/java/cn/hippo4j/core/plugin/manager/DefaultThreadPoolPluginRegistrarTest.java @@ -18,7 +18,11 @@ package cn.hippo4j.core.plugin.manager; import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor; -import cn.hippo4j.core.plugin.impl.*; +import cn.hippo4j.core.plugin.impl.TaskDecoratorPlugin; +import cn.hippo4j.core.plugin.impl.TaskRejectCountRecordPlugin; +import cn.hippo4j.core.plugin.impl.TaskRejectNotifyAlarmPlugin; +import cn.hippo4j.core.plugin.impl.TaskTimeoutNotifyAlarmPlugin; +import cn.hippo4j.core.plugin.impl.ThreadPoolExecutorShutdownPlugin; import org.junit.Assert; import org.junit.Test; diff --git a/hippo4j-core/src/test/java/cn/hippo4j/core/proxy/RejectedProxyInvocationHandlerTest.java b/hippo4j-core/src/test/java/cn/hippo4j/core/proxy/RejectedProxyInvocationHandlerTest.java new file mode 100644 index 00000000..54f36bc4 --- /dev/null +++ b/hippo4j-core/src/test/java/cn/hippo4j/core/proxy/RejectedProxyInvocationHandlerTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.core.proxy; + +import cn.hippo4j.common.api.ThreadPoolCheckAlarm; +import cn.hippo4j.common.config.ApplicationContextHolder; +import org.junit.Before; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.context.ApplicationContext; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicLong; + +@RunWith(MockitoJUnitRunner.class) +public class RejectedProxyInvocationHandlerTest { + + @Mock + private ThreadPoolCheckAlarm mockAlarmHandler; + + @Mock + private ApplicationContext applicationContext; + + @Mock + private Object target; + + @Mock + private Method mockMethod; + + private RejectedProxyInvocationHandler handler; + + private AtomicLong rejectCount; + @Before + public void setUp() { + String threadPoolId = "test-pool"; + rejectCount = new AtomicLong(0); + handler = new RejectedProxyInvocationHandler(target, threadPoolId, rejectCount); + } + + @Test + public void testInvoke() throws Throwable { + Object[] mockArgs = new Object[]{"arg1", "arg2"}; + MockedStatic mockedStatic = Mockito.mockStatic(ApplicationContextHolder.class); + mockedStatic.when(ApplicationContextHolder::getInstance).thenReturn(applicationContext); + mockedStatic.when(() -> ApplicationContextHolder.getBean(ThreadPoolCheckAlarm.class)).thenReturn(mockAlarmHandler); + Mockito.doNothing().when(mockAlarmHandler).asyncSendRejectedAlarm("test-pool"); + handler.invoke(null, mockMethod, mockArgs); + Mockito.doThrow(new InvocationTargetException(new Throwable())).when(mockMethod).invoke(target, mockArgs); + Assertions.assertThrows(Throwable.class, () -> handler.invoke(null, mockMethod, mockArgs)); + Assertions.assertSame(rejectCount.get(), 2L); + } +} diff --git a/hippo4j-example/hippo4j-config-apollo-spring-boot-1x-starter-example/pom.xml b/hippo4j-example/hippo4j-config-apollo-spring-boot-1x-starter-example/pom.xml index 33f94765..cfdab36b 100644 --- a/hippo4j-example/hippo4j-config-apollo-spring-boot-1x-starter-example/pom.xml +++ b/hippo4j-example/hippo4j-config-apollo-spring-boot-1x-starter-example/pom.xml @@ -78,4 +78,21 @@ 1.1.3
+ + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + diff --git a/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/src/main/resources/apollo-config.properties b/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/src/main/resources/apollo-config.properties index 2c83a611..5cdf82ce 100644 --- a/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/src/main/resources/apollo-config.properties +++ b/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/src/main/resources/apollo-config.properties @@ -50,3 +50,21 @@ spring.dynamic.thread-pool.executors[1].active-alarm=80 spring.dynamic.thread-pool.executors[1].capacity-alarm=80 spring.dynamic.thread-pool.executors[1].notify.interval=8 spring.dynamic.thread-pool.executors[1].notify.receives=chen.ma + + +# For hippo4j-agent mode (Optional) +spring.dynamic.thread-pool.executors[2].thread-pool-id = cn.hippo4j.example.core.config.DynamicThreadPoolConfig#FIELD1 +spring.dynamic.thread-pool.executors[2].thread-name-prefix = DynamicThreadPoolConfig#FIELD1 +spring.dynamic.thread-pool.executors[2].core-pool-size = 2 +spring.dynamic.thread-pool.executors[2].maximum-pool-size = 52 +spring.dynamic.thread-pool.executors[2].queue-capacity = 1024 +spring.dynamic.thread-pool.executors[2].blocking-queue = ResizableCapacityLinkedBlockingQueue +spring.dynamic.thread-pool.executors[2].execute-time-out = 800 +spring.dynamic.thread-pool.executors[2].rejected-handler = AbortPolicy +spring.dynamic.thread-pool.executors[2].keep-alive-time = 6691 +spring.dynamic.thread-pool.executors[2].allow-core-thread-time-out = true +spring.dynamic.thread-pool.executors[2].alarm = true +spring.dynamic.thread-pool.executors[2].active-alarm = 80 +spring.dynamic.thread-pool.executors[2].capacity-alarm = 80 +spring.dynamic.thread-pool.executors[2].notify.interval = 8 +spring.dynamic.thread-pool.executors[2].notify.receives = nobodyiam diff --git a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/config/DynamicThreadPoolConfig.java b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/config/DynamicThreadPoolConfig.java index 517a190b..9f21ddf7 100644 --- a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/config/DynamicThreadPoolConfig.java +++ b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/config/DynamicThreadPoolConfig.java @@ -28,8 +28,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import static cn.hippo4j.common.constant.Constants.AVAILABLE_PROCESSORS; import static cn.hippo4j.example.core.constant.GlobalTestConstant.MESSAGE_CONSUME; @@ -42,6 +44,12 @@ import static cn.hippo4j.example.core.constant.GlobalTestConstant.MESSAGE_PRODUC @Configuration public class DynamicThreadPoolConfig { + public static final ThreadPoolExecutor FIELD1 = new ThreadPoolExecutor(10, 20, + 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(20)); + + public static final ThreadPoolExecutor FIELD2 = new ThreadPoolExecutor(10, 20, + 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(20)); + @Bean @DynamicThreadPool public Executor messageConsumeTtlDynamicThreadPool() { diff --git a/hippo4j-example/hippo4j-example-core/src/test/java/cn/hippo4j/example/core/TaskTimeRecordPluginBenchmarkTest.java b/hippo4j-example/hippo4j-example-core/src/test/java/cn/hippo4j/example/core/TaskTimeRecordPluginBenchmarkTest.java index 408af6e0..27631afa 100644 --- a/hippo4j-example/hippo4j-example-core/src/test/java/cn/hippo4j/example/core/TaskTimeRecordPluginBenchmarkTest.java +++ b/hippo4j-example/hippo4j-example-core/src/test/java/cn/hippo4j/example/core/TaskTimeRecordPluginBenchmarkTest.java @@ -21,7 +21,16 @@ import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor; import cn.hippo4j.core.plugin.impl.TaskTimeRecordPlugin; import cn.hippo4j.core.plugin.manager.DefaultThreadPoolPluginManager; import lombok.SneakyThrows; -import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.Runner; diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/DingSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/DingSendMessageHandler.java index e7c078e3..c92ea715 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/DingSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/DingSendMessageHandler.java @@ -17,12 +17,12 @@ package cn.hippo4j.message.platform; +import cn.hippo4j.common.toolkit.Assert; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.FileUtil; +import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.Singleton; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.common.toolkit.JSONUtil; -import cn.hippo4j.common.toolkit.Assert; import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.enums.NotifyPlatformEnum; @@ -42,7 +42,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Objects; -import static cn.hippo4j.message.platform.constant.DingAlarmConstants.*; +import static cn.hippo4j.message.platform.constant.DingAlarmConstants.DING_ALARM_TIMEOUT_REPLACE_TXT; +import static cn.hippo4j.message.platform.constant.DingAlarmConstants.DING_ALARM_TIMEOUT_TRACE_REPLACE_TXT; +import static cn.hippo4j.message.platform.constant.DingAlarmConstants.DING_ALARM_TITLE; +import static cn.hippo4j.message.platform.constant.DingAlarmConstants.DING_NOTICE_TITLE; /** * doc:自定义机器人接入 diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java index 0a7fbcd4..6de50aab 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java @@ -17,14 +17,18 @@ package cn.hippo4j.message.platform; -import cn.hippo4j.common.toolkit.*; +import cn.hippo4j.common.toolkit.Assert; +import cn.hippo4j.common.toolkit.FileUtil; +import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.Singleton; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.enums.NotifyPlatformEnum; import cn.hippo4j.message.enums.NotifyTypeEnum; -import cn.hippo4j.message.service.SendMessageHandler; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; +import cn.hippo4j.message.service.SendMessageHandler; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -36,7 +40,10 @@ import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; -import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.*; +import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.LARK_AT_FORMAT_OPENID; +import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.LARK_AT_FORMAT_USERNAME; +import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.LARK_BOT_URL; +import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.LARK_OPENID_PREFIX; /** * Send lark notification message. diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java index e5b397fa..c502fc4f 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java @@ -30,7 +30,9 @@ import lombok.Data; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; -import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.*; +import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.WE_CHAT_ALARM_TIMOUT_REPLACE_TXT; +import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.WE_CHAT_ALARM_TIMOUT_TRACE_REPLACE_TXT; +import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.WE_CHAT_SERVER_URL; /** * WeChat send message handler. diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/request/base/BaseNotifyRequest.java b/hippo4j-message/src/main/java/cn/hippo4j/message/request/base/BaseNotifyRequest.java index 4e0f6a7b..5db9a63c 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/request/base/BaseNotifyRequest.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/request/base/BaseNotifyRequest.java @@ -18,7 +18,6 @@ package cn.hippo4j.message.request.base; import cn.hippo4j.common.api.NotifyRequest; -import cn.hippo4j.message.enums.NotifyTypeEnum; import lombok.Data; /** diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/service/SendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/service/SendMessageHandler.java index 25d6f27d..042c4818 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/service/SendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/service/SendMessageHandler.java @@ -18,7 +18,6 @@ package cn.hippo4j.message.service; import cn.hippo4j.message.dto.NotifyConfigDTO; -import cn.hippo4j.common.api.NotifyRequest; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.message.request.WebChangeParameterNotifyRequest; diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/service/WebThreadPoolConfigChangeHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/service/WebThreadPoolConfigChangeHandler.java index 70e8c9f1..f2422d67 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/service/WebThreadPoolConfigChangeHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/service/WebThreadPoolConfigChangeHandler.java @@ -20,7 +20,6 @@ package cn.hippo4j.message.service; import cn.hippo4j.common.api.ThreadPoolConfigChange; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.core.toolkit.IdentifyUtil; -import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.message.request.WebChangeParameterNotifyRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/Client.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/Client.java index ad7f1271..c4efcd25 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/Client.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/Client.java @@ -23,12 +23,37 @@ import cn.hippo4j.rpc.model.Response; import java.io.Closeable; /** - * the client for RPC, Explain the role of the client in the request + *

CLIENT

+ * The highest level interface for the client, it does not care how to communicate with the server, + * nor can it know the specific connection information. The client plays the role of message producer + * in the whole connection.By sending a Request to the server ({@link Request}), the client will be + * able to communicate with the server. Wait for the server's Response ({@link Response}) + *

METHOD

+ *
    + *
  • {@link #connection(Request)}
  • + *
  • {@link #isActive()}
  • + *
  • {@link #close()}
  • + *
+ * You can usually use the client in this way: + *
+ *     Request request = new Request();
+ *     try(Client client = new Client()){
+ *         Response response = client.connection(request);
+ *     }
+ * 
+ * + * The client implements Closeable and supports automatic shutdown, However, you can manually + * disable it when you want to use it + * + * @since 1.5.1 */ public interface Client extends Closeable { /** * Start the client and try to send and receive data + * + * @param request Request information, Requested methods and parameters + * @return response Response from server side */ Response connection(Request request); diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/ClientConnection.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/ClientConnection.java index 43791228..e3fb241c 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/ClientConnection.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/ClientConnection.java @@ -22,7 +22,9 @@ import cn.hippo4j.rpc.model.Request; import cn.hippo4j.rpc.model.Response; /** - * Applicable to client connections + * Applicable to client connections
+ * + * @since 1.5.1 */ public interface ClientConnection extends Connection { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/NettyClientConnection.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/NettyClientConnection.java index fce2deba..e6337999 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/NettyClientConnection.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/NettyClientConnection.java @@ -22,8 +22,6 @@ import cn.hippo4j.common.web.exception.IllegalException; import cn.hippo4j.rpc.exception.TimeOutException; import cn.hippo4j.rpc.model.Request; import cn.hippo4j.rpc.model.Response; -import cn.hippo4j.rpc.process.ActivePostProcess; -import cn.hippo4j.rpc.process.ActiveProcessChain; import cn.hippo4j.rpc.support.NettyConnectPool; import cn.hippo4j.rpc.support.NettyConnectPoolHolder; import cn.hippo4j.rpc.support.ResultHolder; @@ -35,12 +33,13 @@ import io.netty.channel.pool.ChannelPoolHandler; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.List; +import java.util.Optional; import java.util.concurrent.locks.LockSupport; /** * Client implemented using netty + * + * @since 1.5.1 */ @Slf4j public class NettyClientConnection implements ClientConnection { @@ -51,33 +50,28 @@ public class NettyClientConnection implements ClientConnection { */ long timeout = 30000L; EventLoopGroup worker = new NioEventLoopGroup(); - ActiveProcessChain activeProcessChain; NettyConnectPool connectionPool; ChannelFuture future; Channel channel; public NettyClientConnection(InetSocketAddress address, - List activeProcesses, ChannelPoolHandler handler) { Assert.notNull(worker); this.address = address; - this.activeProcessChain = new ActiveProcessChain(activeProcesses); this.connectionPool = NettyConnectPoolHolder.getPool(address, timeout, worker, handler); } - public NettyClientConnection(InetSocketAddress address, ChannelPoolHandler handler) { - this(address, new LinkedList<>(), handler); - } - @Override public Response connect(Request request) { - activeProcessChain.applyPreHandle(request); this.channel = connectionPool.acquire(timeout); - Response response = null; + boolean debugEnabled = log.isDebugEnabled(); + Response response; try { String key = request.getKey(); this.future = channel.writeAndFlush(request); - log.info("Call successful, target address is {}:{}, request key is {}", address.getHostName(), address.getPort(), key); + if (debugEnabled) { + log.debug("Call successful, target address is {}:{}, request key is {}", address.getHostName(), address.getPort(), key); + } // Wait for execution to complete ResultHolder.putThread(key, Thread.currentThread()); LockSupport.parkNanos(timeout() * 1000000); @@ -85,14 +79,13 @@ public class NettyClientConnection implements ClientConnection { if (response == null) { throw new TimeOutException("Timeout waiting for server-side response"); } - activeProcessChain.applyPostHandle(request, response); - log.info("The response from {}:{} was received successfully with the response key {}.", address.getHostName(), address.getPort(), key); + if (debugEnabled) { + log.debug("The response from {}:{} was received successfully with the response key {}.", address.getHostName(), address.getPort(), key); + } return response; } catch (Exception ex) { - activeProcessChain.afterCompletion(request, response, ex); throw new IllegalException(ex); } finally { - activeProcessChain.afterCompletion(request, response, null); connectionPool.release(this.channel); } } @@ -108,13 +101,13 @@ public class NettyClientConnection implements ClientConnection { } @Override - public synchronized void close() { - if (this.channel == null) { - return; - } - worker.shutdownGracefully(); - this.future.channel().close(); - this.channel.close(); + public void close() { + Optional.ofNullable(this.channel) + .ifPresent(c -> { + worker.shutdownGracefully(); + this.future.channel().close(); + this.channel.close(); + }); } @Override diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/RPCClient.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/RPCClient.java index abc3ed9e..f9eb8eea 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/RPCClient.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/client/RPCClient.java @@ -23,7 +23,10 @@ import cn.hippo4j.rpc.model.Response; import java.io.IOException; /** - * The client, which provides a closing mechanism, maintains a persistent connection if not closed + * The client, which provides a closing mechanism, maintains a persistent connection if not closed
+ * Delegate the method to the {@link ClientConnection} for implementation + * + * @since 1.5.1 */ public class RPCClient implements Client { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/CompactObjectOutputStream.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/CompactObjectOutputStream.java index 599cf118..36c34f9c 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/CompactObjectOutputStream.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/CompactObjectOutputStream.java @@ -24,6 +24,8 @@ import java.io.OutputStream; /** * object OutputStream + * + * @since 1.5.1 */ public class CompactObjectOutputStream extends ObjectOutputStream { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyDecoder.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyDecoder.java deleted file mode 100644 index 42223e44..00000000 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyDecoder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package cn.hippo4j.rpc.coder; - -import cn.hippo4j.rpc.exception.CoderException; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; - -/** - * According to the decoder for java objects implemented by ObjectDecoder, - * it is necessary to ensure that the transmitted objects can be serialized - */ -public class NettyDecoder extends ObjectDecoder { - - public NettyDecoder(ClassResolver classResolver) { - super(classResolver); - } - - @Override - protected Object decode(ChannelHandlerContext ctx, ByteBuf in) { - ByteBuf byteBuf = in.retainedDuplicate(); - try { - Object o = super.decode(ctx, in); - if (o == null) { - return byteBuf; - } else { - return o; - } - } catch (Exception e) { - throw new CoderException("The encoding is abnormal, which may be caused by the failure of the transfer object to be deserialized"); - } - } -} diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyEncoder.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyEncoder.java index 856aae2a..7cbfaff7 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyEncoder.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/coder/NettyEncoder.java @@ -29,6 +29,8 @@ import java.io.Serializable; /** * this is a encoder, For custom gluing and unpacking
* {@link io.netty.handler.codec.serialization.ObjectEncoder} + * + * @since 1.5.1 */ public class NettyEncoder extends MessageToByteEncoder { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ClassRegistry.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ClassRegistry.java index 5af58c87..d01f510e 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ClassRegistry.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ClassRegistry.java @@ -25,11 +25,13 @@ import java.util.concurrent.ConcurrentHashMap; /** * the registration center for Client and Server + * + * @since 1.5.1 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ClassRegistry { - private static final Map> serverRegister = new ConcurrentHashMap<>(); + private static final Map> SERVER_REGISTER = new ConcurrentHashMap<>(); /** * get a Obj in Registry center
@@ -38,7 +40,7 @@ public class ClassRegistry { * @return t element */ public static Class get(String s) { - return serverRegister.get(s); + return SERVER_REGISTER.get(s); } /** @@ -51,7 +53,7 @@ public class ClassRegistry { * @return final mapped value */ public static Class set(String s, Class cls) { - return serverRegister.putIfAbsent(s, cls); + return SERVER_REGISTER.putIfAbsent(s, cls); } /** @@ -62,13 +64,13 @@ public class ClassRegistry { * @param cls element */ public static Class put(String s, Class cls) { - return serverRegister.put(s, cls); + return SERVER_REGISTER.put(s, cls); } /** * clear */ public static void clear() { - serverRegister.clear(); + SERVER_REGISTER.clear(); } } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DefaultInstance.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DefaultInstance.java index 4c6d6741..44b9a6f4 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DefaultInstance.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DefaultInstance.java @@ -27,6 +27,8 @@ import java.util.ServiceLoader; * You simply create an instance of a class based on its name and specific type. * Load through the ServiceLoader first. If the load fails, load directly through the instantiation. * If it is an interface, throw an exception. This is not elegant implementation + * + * @since 1.5.1 */ public class DefaultInstance implements Instance { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DiscoveryAdapter.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DiscoveryAdapter.java index 3a788f30..119fde6e 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DiscoveryAdapter.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/DiscoveryAdapter.java @@ -22,6 +22,8 @@ import java.net.InetSocketAddress; /** * The adaptation layer of different service centers is used to know * the host of different services through the registration center + * + * @since 1.5.1 */ public interface DiscoveryAdapter { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/Instance.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/Instance.java index aab7163c..83f649f0 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/Instance.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/Instance.java @@ -19,6 +19,8 @@ package cn.hippo4j.rpc.discovery; /** * Instance interface to get an instance + * + * @since 1.5.1 */ public interface Instance { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ServerPort.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ServerPort.java index 5795058c..82e240a7 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ServerPort.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/ServerPort.java @@ -19,6 +19,8 @@ package cn.hippo4j.rpc.discovery; /** * Gets the top-level interface of the instance port + * + * @since 1.5.1 */ @FunctionalInterface public interface ServerPort { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/SpringContextInstance.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/SpringContextInstance.java index 5cbc79c7..fa25d4c9 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/SpringContextInstance.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/discovery/SpringContextInstance.java @@ -21,6 +21,8 @@ import cn.hippo4j.common.config.ApplicationContextHolder; /** * Adapter Spring, The requested object is managed by spring + * + * @since 1.5.1 */ public class SpringContextInstance implements Instance { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/CoderException.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/CoderException.java index 5ac64a5a..e891772c 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/CoderException.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/CoderException.java @@ -20,6 +20,8 @@ package cn.hippo4j.rpc.exception; /** * During decoding and encoding, if an exception occurs, an exception of type {@link CoderException} is thrown, * which is not different from a {@link RuntimeException}, but is more explicit about the type of exception + * + * @since 1.5.1 */ public class CoderException extends RuntimeException { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/ConnectionException.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/ConnectionException.java index 87e29423..aaf6edd2 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/ConnectionException.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/ConnectionException.java @@ -21,6 +21,8 @@ package cn.hippo4j.rpc.exception; * If an exception occurs during the connection between the server and the client, an exception of type * {@link ConnectionException} is thrown, which is not different from {@link RuntimeException}, but is more explicit * about the type of exception + * + * @since 1.5.1 */ public class ConnectionException extends RuntimeException { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/TimeOutException.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/TimeOutException.java index ef808b57..43d51057 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/TimeOutException.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/exception/TimeOutException.java @@ -20,6 +20,8 @@ package cn.hippo4j.rpc.exception; /** * If there is a timeout between the server and the client, you will get a {@link TimeOutException}, * which is not different from {@link RuntimeException}, but it will be more explicit about the type of exception, right + * + * @since 1.5.1 */ public class TimeOutException extends RuntimeException { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/AbstractNettyHandlerManager.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/AbstractNettyHandlerManager.java index 0460bb5e..a3d5eae2 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/AbstractNettyHandlerManager.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/AbstractNettyHandlerManager.java @@ -20,12 +20,18 @@ package cn.hippo4j.rpc.handler; import cn.hippo4j.common.toolkit.Assert; import io.netty.channel.ChannelHandler; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; /** * Processor manager for ChannelHandler in netty + * + * @since 1.5.1 */ public abstract class AbstractNettyHandlerManager implements HandlerManager { @@ -81,28 +87,4 @@ public abstract class AbstractNettyHandlerManager implements HandlerManager { + throw new ConnectionException(cause); + }); } /** diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/ConnectHandler.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/ConnectHandler.java index f12a846e..35c900fc 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/ConnectHandler.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/ConnectHandler.java @@ -25,6 +25,7 @@ import cn.hippo4j.rpc.model.Response; * must be specified, such as serialization and parsing, requesting and receiving * requests, and so on
* + * @since 1.5.1 */ public interface ConnectHandler { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/Connection.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/Connection.java index 77ce2211..943b4f54 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/Connection.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/Connection.java @@ -20,7 +20,14 @@ package cn.hippo4j.rpc.handler; import java.io.Closeable; /** - * Represents a network request connection and provides IO layer support + * Represents a network request connection and provides IO layer support
+ *

+ * This is not a strict and stateless Connection interface, it contains the necessary + * operations that should be done in the connection. It is more like integrating the + * connection and the connection channel together, so creating {@link Connection} is + * very resource intensive, for which caching is recommended + * + * @since 1.5.1 */ public interface Connection extends Closeable { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/HandlerManager.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/HandlerManager.java index f4ebb4b9..18460ac3 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/HandlerManager.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/HandlerManager.java @@ -17,12 +17,16 @@ package cn.hippo4j.rpc.handler; +import cn.hippo4j.common.web.exception.IllegalException; +import io.netty.channel.ChannelHandler; import lombok.AllArgsConstructor; import lombok.Getter; /** * Manage the Handler used in the processing.
* The Handler must be able to exist multiple times and be invoked once in a single execution + * + * @since 1.5.1 */ public interface HandlerManager { @@ -42,20 +46,6 @@ public interface HandlerManager { */ HandlerManager addFirst(String name, T handler); - /** - * Add handler to the end of the Handler chain, without specifying a name - * - * @param handler handler - */ - HandlerManager addLast(T handler); - - /** - * Adds handler to the head of the Handler chain, without specifying a name - * - * @param handler handler - */ - HandlerManager addFirst(T handler); - /** * Whether handler exists * @@ -72,6 +62,14 @@ public interface HandlerManager { * @return HandlerEntity */ default HandlerEntity getHandlerEntity(long order, T handler, String name) { + Class cls = handler.getClass(); + boolean b = cls.isAnnotationPresent(ChannelHandler.Sharable.class) + || HandlerManager.class.isAssignableFrom(cls); + if (!b) { + throw new IllegalException("Join the execution of the handler must add io.netty.channel.ChannelHandler." + + "Sharable annotations, Please for the handler class " + cls.getName() + " add io.netty.channel." + + "ChannelHandler.Sharable annotation"); + } return new HandlerEntity<>(order, handler, name); } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientPoolHandler.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientPoolHandler.java index eced889a..42d5fbaf 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientPoolHandler.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientPoolHandler.java @@ -17,7 +17,6 @@ package cn.hippo4j.rpc.handler; -import cn.hippo4j.rpc.coder.NettyDecoder; import cn.hippo4j.rpc.coder.NettyEncoder; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; @@ -26,12 +25,15 @@ import io.netty.channel.ChannelPipeline; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; +import io.netty.handler.codec.serialization.ObjectDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * Processing by the client connection pool handler to clean the buffer and define new connection properties + * + * @since 1.5.1 */ @Slf4j public class NettyClientPoolHandler extends AbstractNettyHandlerManager implements ChannelPoolHandler { @@ -60,22 +62,12 @@ public class NettyClientPoolHandler extends AbstractNettyHandlerManager implemen return this; } - @Override - public NettyClientPoolHandler addLast(ChannelHandler handler) { - super.addLast(handler); - return this; - } - - @Override - public NettyClientPoolHandler addFirst(ChannelHandler handler) { - super.addFirst(handler); - return this; - } - @Override public void channelReleased(Channel ch) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER); - log.info("The connection buffer has been emptied of data"); + if (log.isDebugEnabled()) { + log.debug("The connection buffer has been emptied of data"); + } } @Override @@ -90,7 +82,7 @@ public class NettyClientPoolHandler extends AbstractNettyHandlerManager implemen .setTcpNoDelay(false); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new NettyEncoder()); - pipeline.addLast(new NettyDecoder(ClassResolvers.cacheDisabled(null))); + pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null))); this.handlerEntities.stream() .sorted() .forEach(h -> { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientTakeHandler.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientTakeHandler.java index 1841d7f9..b1852bd5 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientTakeHandler.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyClientTakeHandler.java @@ -24,6 +24,8 @@ import io.netty.channel.ChannelHandlerContext; /** * Interconnect with the netty mediation layer + * + * @since 1.5.1 */ @ChannelHandler.Sharable public class NettyClientTakeHandler extends AbstractNettyTakeHandler implements ConnectHandler { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyServerTakeHandler.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyServerTakeHandler.java index a4eaddc2..e0951c03 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyServerTakeHandler.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/handler/NettyServerTakeHandler.java @@ -19,36 +19,28 @@ package cn.hippo4j.rpc.handler; import cn.hippo4j.common.toolkit.Assert; import cn.hippo4j.common.toolkit.ReflectUtil; -import cn.hippo4j.rpc.process.ActivePostProcess; -import cn.hippo4j.rpc.process.ActiveProcessChain; -import cn.hippo4j.rpc.model.Request; -import cn.hippo4j.rpc.model.DefaultResponse; -import cn.hippo4j.rpc.model.Response; import cn.hippo4j.rpc.discovery.ClassRegistry; import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.model.DefaultResponse; +import cn.hippo4j.rpc.model.Request; +import cn.hippo4j.rpc.model.Response; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import java.lang.reflect.Method; -import java.util.LinkedList; -import java.util.List; /** * netty adaptation layer + * + * @since 1.5.1 */ @ChannelHandler.Sharable public class NettyServerTakeHandler extends AbstractNettyTakeHandler implements ConnectHandler { - ActiveProcessChain activeProcessChain; Instance instance; - public NettyServerTakeHandler(List processes, Instance instance) { - this.activeProcessChain = new ActiveProcessChain(processes); - this.instance = instance; - } - public NettyServerTakeHandler(Instance instance) { - this(new LinkedList<>(), instance); + this.instance = instance; } @Override @@ -63,24 +55,17 @@ public class NettyServerTakeHandler extends AbstractNettyTakeHandler implements @Override public Response sendHandler(Request request) { - if (!activeProcessChain.applyPreHandle(request)) { - return null; - } - Response response = null; + Response response; try { Class cls = ClassRegistry.get(request.getClassName()); Method method = ReflectUtil.getMethodByName(cls, request.getMethodName(), request.getParameterTypes()); Assert.notNull(method); Object invoke = ReflectUtil.invoke(instance.getInstance(cls), method, request.getParameters()); response = new DefaultResponse(request.getKey(), invoke.getClass(), invoke); - activeProcessChain.applyPostHandle(request, response); return response; } catch (Exception e) { response = new DefaultResponse(request.getKey(), e, e.getMessage()); - activeProcessChain.afterCompletion(request, response, e); return response; - } finally { - activeProcessChain.afterCompletion(request, response, null); } } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultRequest.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultRequest.java index 04ca4191..4dc30bb8 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultRequest.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultRequest.java @@ -25,6 +25,8 @@ import java.util.Objects; /** * default request
* Use the fully qualified name key of the interface and override equals and hashCode + * + * @since 1.5.1 */ public final class DefaultRequest implements Request { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultResponse.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultResponse.java index d6602a72..0fc68f44 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultResponse.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/DefaultResponse.java @@ -25,6 +25,8 @@ import java.util.Objects; /** * default request
* Use the fully qualified name key of the interface and override equals and hashCode + * + * @since 1.5.1 */ public class DefaultResponse implements Response { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Request.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Request.java index 461e40e5..128d069e 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Request.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Request.java @@ -21,6 +21,8 @@ import java.io.Serializable; /** * request + * + * @since 1.5.1 */ public interface Request extends Serializable { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Response.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Response.java index 83b31444..a7b2642a 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Response.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/model/Response.java @@ -21,6 +21,8 @@ import java.io.Serializable; /** * Response + * + * @since 1.5.1 */ public interface Response extends Serializable { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActivePostProcess.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActivePostProcess.java deleted file mode 100644 index 9e7fee18..00000000 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActivePostProcess.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package cn.hippo4j.rpc.process; - -import cn.hippo4j.rpc.model.Request; -import cn.hippo4j.rpc.model.Response; - -/** - * Callback while the connection is in progress - */ -public interface ActivePostProcess { - - /** - * Client: After establishing a connection and before passing parameters
- * Server: Receives parameters and performs pre-call operations
- * - * @param request request - * @return Whether to continue the execution. If it is a client, the returned value does not affect subsequent execution - */ - default boolean preHandler(Request request) { - return true; - } - - /** - * Client: Action after receiving a response
- * Server: performs the operation after the call
- * - * @param request request - * @param response response - */ - default void postHandler(Request request, Response response) { - // NO SOMETHING - } - - /** - * Called when an exception or resource is cleaned - * - * @param request request - * @param response response - * @param e Exception - */ - default void afterCompletion(Request request, Response response, Exception e) { - // NO SOMETHING - } -} diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActiveProcessChain.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActiveProcessChain.java deleted file mode 100644 index 4882dc74..00000000 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/process/ActiveProcessChain.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package cn.hippo4j.rpc.process; - -import cn.hippo4j.rpc.model.Request; -import cn.hippo4j.rpc.model.Response; -import lombok.extern.slf4j.Slf4j; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Processor chain for easier processing of processors in different scenarios
- * reference resources: spring HandlerExecutionChain - * - * @see ActivePostProcess - */ -@Slf4j -public final class ActiveProcessChain { - - /** - * A collection of processors that will be applied to their assigned programs. - * Processors will perform different actions on different occasions for both the server and the client, - * but the execution period of that action must be the same - */ - List processes; - - /** - * index
- * that identifies where the {@link ActivePostProcess#preHandler(Request)} processing is performed
- * This allows for the fact that some processors will add shutable operations to the class
- * eg: {@link java.io.Closeable}, The {@link ActivePostProcess#afterCompletion(Request, Response, Exception)} - * operation is not performed after an exception if the preprocessor is not executed - */ - int index = -1; - - public ActiveProcessChain(List processes) { - this.processes = processes; - } - - public ActiveProcessChain(ActivePostProcess... processes) { - this((processes != null ? Arrays.asList(processes) : Collections.emptyList())); - } - - /** - * Apply postHandle methods of registered processes. - */ - public boolean applyPreHandle(Request request) { - for (int i = 0; i < this.processes.size(); i++) { - ActivePostProcess handle = processes.get(i); - if (!handle.preHandler(request)) { - afterCompletion(request, null, null); - return false; - } - this.index = i; - } - return true; - } - - /** - * Apply postHandle methods of registered processes. - */ - public void applyPostHandle(Request request, Response response) { - for (int i = processes.size() - 1; i >= 0; i--) { - ActivePostProcess handle = processes.get(i); - handle.postHandler(request, response); - } - } - - /** - * Trigger afterCompletion callbacks on the mapped ActivePostProcess. - * Will just invoke afterCompletion for all interceptors whose preHandle invocation - * has successfully completed and returned true. - */ - public void afterCompletion(Request request, Response response, Exception ex) { - for (int i = this.index; i >= 0; i--) { - ActivePostProcess handle = processes.get(i); - try { - handle.afterCompletion(request, response, ex); - } catch (Throwable e) { - log.error("HandlerInterceptor.afterCompletion threw exception", e); - } - } - } - -} diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/NettyServerConnection.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/NettyServerConnection.java index 49083c03..a6adc0d1 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/NettyServerConnection.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/NettyServerConnection.java @@ -18,17 +18,24 @@ package cn.hippo4j.rpc.server; import cn.hippo4j.common.toolkit.Assert; -import cn.hippo4j.rpc.coder.NettyDecoder; import cn.hippo4j.rpc.coder.NettyEncoder; import cn.hippo4j.rpc.discovery.ServerPort; import cn.hippo4j.rpc.exception.ConnectionException; import cn.hippo4j.rpc.handler.AbstractNettyHandlerManager; import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.*; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.ServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; +import io.netty.handler.codec.serialization.ObjectDecoder; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; @@ -37,6 +44,8 @@ import java.util.List; /** * adapter to the netty server + * + * @since 1.5.1 */ @Slf4j public class NettyServerConnection extends AbstractNettyHandlerManager implements ServerConnection { @@ -70,6 +79,10 @@ public class NettyServerConnection extends AbstractNettyHandlerManager implement @Override public void bind(ServerPort port) { + int serverPort = port.getPort(); + if (serverPort < 0 || serverPort > 65535) { + throw new ConnectionException("The port number " + serverPort + " is outside 0~65535, which is not a legal port number"); + } ServerBootstrap server = new ServerBootstrap(); server.group(leader, worker) .channel(socketChannelCls) @@ -77,10 +90,10 @@ public class NettyServerConnection extends AbstractNettyHandlerManager implement .childHandler(new ChannelInitializer() { @Override - protected void initChannel(SocketChannel ch) throws Exception { + protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new NettyEncoder()); - pipeline.addLast(new NettyDecoder(ClassResolvers.cacheDisabled(null))); + pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null))); handlerEntities.stream() .sorted() .forEach(h -> { @@ -93,9 +106,11 @@ public class NettyServerConnection extends AbstractNettyHandlerManager implement } }); try { - this.future = server.bind(port.getPort()).sync(); + this.future = server.bind(serverPort).sync(); this.channel = this.future.channel(); - log.info("The server is started and can receive requests. The listening port is {}", port.getPort()); + if (log.isDebugEnabled()) { + log.debug("The server is started and can receive requests. The listening port is {}", serverPort); + } this.port = port; this.future.channel().closeFuture().sync(); } catch (InterruptedException ex) { @@ -113,7 +128,9 @@ public class NettyServerConnection extends AbstractNettyHandlerManager implement this.worker.shutdownGracefully(); this.channel.close(); this.future.channel().close(); - log.info("The server is shut down and no more requests are received. The release port is {}", port.getPort()); + if (log.isDebugEnabled()) { + log.debug("The server is shut down and no more requests are received. The release port is {}", port.getPort()); + } } @Override @@ -136,16 +153,4 @@ public class NettyServerConnection extends AbstractNettyHandlerManager implement return this; } - @Override - public NettyServerConnection addLast(ChannelHandler handler) { - super.addLast(handler); - return this; - } - - @Override - public NettyServerConnection addFirst(ChannelHandler handler) { - super.addFirst(handler); - return this; - } - } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/RPCServer.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/RPCServer.java index 8588b8f6..b50c0f85 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/RPCServer.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/RPCServer.java @@ -24,6 +24,8 @@ import java.io.IOException; /** * Server Implementation + * + * @since 1.5.1 */ public class RPCServer implements Server { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/Server.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/Server.java index 9c21f788..5c346525 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/Server.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/Server.java @@ -21,6 +21,8 @@ import java.io.Closeable; /** * the service for RPC, Explain the role of the service in the request + * + * @since 1.5.1 */ public interface Server extends Closeable { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/ServerConnection.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/ServerConnection.java index 37edfc62..a1a830ca 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/ServerConnection.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/server/ServerConnection.java @@ -22,6 +22,8 @@ import cn.hippo4j.rpc.handler.Connection; /** * This applies to server-side connections + * + * @since 1.5.1 */ public interface ServerConnection extends Connection { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ClientFactoryBean.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ClientFactoryBean.java index b63e81b6..37b63596 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ClientFactoryBean.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ClientFactoryBean.java @@ -17,6 +17,7 @@ package cn.hippo4j.rpc.support; +import cn.hippo4j.common.toolkit.Assert; import cn.hippo4j.rpc.client.Client; import cn.hippo4j.rpc.discovery.DiscoveryAdapter; import cn.hippo4j.rpc.exception.ConnectionException; @@ -30,11 +31,30 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.net.InetSocketAddress; +import java.util.Optional; /** * A FactoryBean that builds interfaces to invoke proxy objects * is responsible for managing the entire life cycle of the proxy objects
+ *

APPLICATION START

+ * When the application is started, the request initiator needs to complete the proxy of the calling interface, + * which ensures that the method can be requested to the server side when the method is called, rather than simply + * request an interface that cannot be instantiated. The classes involved in adding proxy to the interface are: + *
    + *
  • {@link NettyClientSupport}
  • + *
  • {@link NettyProxyCenter}
  • + *
  • {@link NettyClientPoolHandler}
  • + *
+ *

AND SPRING

+ * In order to fully integrate {@link ClientFactoryBean} into the life cycle of spring beans, + * {@link ClientFactoryBean} also needs to implement the following interfaces: + *
    + *
  • {@link InitializingBean}
  • + *
  • {@link ApplicationContextAware}
  • + *
  • {@link DisposableBean}
  • + *
* + * @since 1.5.1 * @deprecated With {@link cn.hippo4j.config.service.ThreadPoolAdapterService} structure, FactoryBean is not the best choice */ @Deprecated @@ -52,10 +72,16 @@ public class ClientFactoryBean implements FactoryBean, InitializingBean, */ private String discoveryAdapterName; + /** + * The adaptation interface for obtaining ip information in the registry is used together with + * {@link #discoveryAdapterName}, so that the adapter implementation can be obtained in the container + * during the initialization phase + */ private DiscoveryAdapter discoveryAdapter; /** - * the channel handler + * the channel handler, To ensure the security and reliability of netty calls, + * {@link ChannelHandler} must be identified by {@link ChannelHandler.Sharable} */ private ChannelHandler[] handlers; @@ -70,11 +96,13 @@ public class ClientFactoryBean implements FactoryBean, InitializingBean, private ApplicationContext applicationContext; /** - * InetSocketAddress + * InetSocketAddress, It is usually converted from {@link #applicationName} and {@link #discoveryAdapter} */ InetSocketAddress address; public ClientFactoryBean(String applicationName, String discoveryAdapterName, Class cls) { + Assert.notNull(applicationName); + Assert.notNull(cls); this.applicationName = applicationName; this.discoveryAdapterName = discoveryAdapterName; this.cls = cls; @@ -82,16 +110,17 @@ public class ClientFactoryBean implements FactoryBean, InitializingBean, @Override public Object getObject() throws Exception { - this.address = discoveryAdapter.getSocketAddress(applicationName); - if (this.address == null) { - String[] addressStr = applicationName.split(":"); - if (addressStr.length < 2) { - throw new ConnectionException("Failed to connect to the server because the IP address is invalid. Procedure"); - } - this.address = InetSocketAddress.createUnresolved(addressStr[0], Integer.parseInt(addressStr[1])); - } - NettyClientPoolHandler handler = new NettyClientPoolHandler(handlers); - Client client = NettyClientSupport.getClient(this.address, handler); + this.address = Optional.ofNullable(applicationName) + .map(a -> discoveryAdapter.getSocketAddress(a)) + .map(a -> { + String[] addressStr = applicationName.split(":"); + if (addressStr.length < 2) { + throw new ConnectionException("Failed to connect to the server because the IP address is invalid. Procedure"); + } + return InetSocketAddress.createUnresolved(addressStr[0], Integer.parseInt(addressStr[1])); + }) + .orElseThrow(() -> new ConnectionException("Failed to connect to the server because the IP address is invalid. Procedure")); + Client client = NettyClientSupport.getClient(this.address, new NettyClientPoolHandler(handlers)); return NettyProxyCenter.createProxy(client, cls, this.address); } @@ -102,15 +131,15 @@ public class ClientFactoryBean implements FactoryBean, InitializingBean, @Override public void afterPropertiesSet() throws Exception { - this.discoveryAdapter = (DiscoveryAdapter) applicationContext.getBean(discoveryAdapterName); + this.discoveryAdapter = Optional.ofNullable(discoveryAdapterName) + .map(s -> (DiscoveryAdapter) applicationContext.getBean(discoveryAdapterName)) + .orElse(null); } @Override public void destroy() throws Exception { - if (this.address == null) { - return; - } - NettyClientSupport.closeClient(this.address); + Optional.ofNullable(this.address) + .ifPresent(a -> NettyClientSupport.closeClient(this.address)); } @Override diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyClientSupport.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyClientSupport.java index d11530f4..84797f44 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyClientSupport.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyClientSupport.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.lang.ref.WeakReference; import java.net.InetSocketAddress; import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** @@ -51,6 +52,7 @@ import java.util.concurrent.ConcurrentHashMap; * @see cn.hippo4j.rpc.client.NettyClientConnection * @see NettyServerSupport * @see ClientFactoryBean + * @since 1.5.1 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class NettyClientSupport { @@ -58,7 +60,7 @@ public final class NettyClientSupport { /** * the cache for client */ - private static final Map clientMap = new ConcurrentHashMap<>(); + private static final Map CLIENT_MAP = new ConcurrentHashMap<>(); /** * Obtain the client connected to the server through the server address. If the client does not exist, create one @@ -68,12 +70,12 @@ public final class NettyClientSupport { * @return Client */ public static Client getClient(InetSocketAddress address, HandlerManager handlerManager) { - return clientMap.computeIfAbsent(address, a -> { + return CLIENT_MAP.computeIfAbsent(address, a -> { NettyClientPoolHandler handler = (handlerManager instanceof NettyClientPoolHandler) ? (NettyClientPoolHandler) handlerManager : new NettyClientPoolHandler(); if (handler.isEmpty()) { - handler.addFirst(new NettyClientTakeHandler()); + handler.addFirst(null, new NettyClientTakeHandler()); } NettyClientConnection connection = new NettyClientConnection(address, handler); return new RPCClient(connection); @@ -96,13 +98,14 @@ public final class NettyClientSupport { * @param address the address */ public static void closeClient(InetSocketAddress address) { - Client client = clientMap.remove(address); - try { - if (client != null) { - client.close(); - } - } catch (IOException e) { - throw new IllegalException(e); - } + Client client = CLIENT_MAP.remove(address); + Optional.ofNullable(client) + .ifPresent(c -> { + try { + c.close(); + } catch (IOException e) { + throw new IllegalException(e); + } + }); } } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPool.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPool.java index 670520d4..dc2f9b57 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPool.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPool.java @@ -30,10 +30,13 @@ import io.netty.util.concurrent.Future; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; +import java.util.Optional; import java.util.concurrent.TimeUnit; /** * This parameter applies only to the connection pool of netty + * + * @since 1.5.1 */ @Slf4j public class NettyConnectPool { @@ -58,7 +61,9 @@ public class NettyConnectPool { this.handler = handler; this.pool = new FixedChannelPool(bootstrap, handler, healthCheck, acquireTimeoutAction, timeout, maxConnect, maxPendingAcquires, true, true); - log.info("The connection pool is established with the connection target {}:{}", address.getHostName(), address.getPort()); + if (log.isDebugEnabled()) { + log.info("The connection pool is established with the connection target {}:{}", address.getHostName(), address.getPort()); + } NettyConnectPoolHolder.createPool(address, this); } @@ -82,14 +87,15 @@ public class NettyConnectPool { } public void release(Channel channel) { - try { - if (channel != null) { - pool.release(channel); - } - } catch (Exception e) { - NettyClientSupport.closeClient(address); - throw new ConnectionException("Failed to release the connection", e); - } + Optional.ofNullable(channel) + .ifPresent(c -> { + try { + pool.release(channel); + } catch (Exception e) { + NettyClientSupport.closeClient(address); + throw new ConnectionException("Failed to release the connection", e); + } + }); } public void close() { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPoolHolder.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPoolHolder.java index f1f88856..6af34cd6 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPoolHolder.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyConnectPoolHolder.java @@ -31,6 +31,8 @@ import java.util.concurrent.ConcurrentHashMap; /** * To avoid creating multiple connection pools for the same host:port, save all connection pools of the client + * + * @since 1.5.1 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class NettyConnectPoolHolder { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyProxyCenter.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyProxyCenter.java index 836070ea..1a0dd1fd 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyProxyCenter.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyProxyCenter.java @@ -36,6 +36,8 @@ import java.util.concurrent.ConcurrentHashMap; /** * Add a proxy for the request, {@link Proxy} and {@link InvocationHandler} + * + * @since 1.5.1 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class NettyProxyCenter { diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyServerSupport.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyServerSupport.java index 0099663a..b2cc2af1 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyServerSupport.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/NettyServerSupport.java @@ -40,6 +40,7 @@ import java.util.List; * @see RPCServer * @see NettyServerConnection * @see NettyClientSupport + * @since 1.5.1 */ public class NettyServerSupport implements Server { @@ -95,7 +96,7 @@ public class NettyServerSupport implements Server { : new NettyServerConnection(); // Assign a default handler if no handler exists if (connection.isEmpty()) { - connection.addFirst(new NettyServerTakeHandler(new DefaultInstance())); + connection.addFirst(null, new NettyServerTakeHandler(new DefaultInstance())); } server = new RPCServer(connection, serverPort); } diff --git a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ResultHolder.java b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ResultHolder.java index 613a079b..fa57b9f1 100644 --- a/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ResultHolder.java +++ b/hippo4j-rpc/src/main/java/cn/hippo4j/rpc/support/ResultHolder.java @@ -31,13 +31,15 @@ import java.util.concurrent.locks.LockSupport; * The unique remote call can be determined by the key of request and * response, and the result of the call is stored in the secondary cache, * which is convenient for the client to use at any time. + * + * @since 1.5.1 */ @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ResultHolder { - private static final Map map = new ConcurrentHashMap<>(); - private static final Map threadMap = new HashMap<>(); + private static final Map MAP = new ConcurrentHashMap<>(); + private static final Map THREAD_MAP = new HashMap<>(); /** * Writes when the client receives a response @@ -49,7 +51,7 @@ public class ResultHolder { if (log.isDebugEnabled()) { log.debug("Write the result, wake up the thread"); } - map.put(key, o); + MAP.put(key, o); } /** @@ -62,7 +64,7 @@ public class ResultHolder { if (log.isDebugEnabled()) { log.debug("Write thread, waiting to wake up"); } - threadMap.put(key, t); + THREAD_MAP.put(key, t); } /** @@ -74,7 +76,7 @@ public class ResultHolder { if (log.isDebugEnabled()) { log.debug("The future has been fetched, wake up the thread"); } - Thread thread = threadMap.remove(key); + Thread thread = THREAD_MAP.remove(key); LockSupport.unpark(thread); } @@ -91,7 +93,7 @@ public class ResultHolder { if (log.isDebugEnabled()) { log.debug("Get the future"); } - return (T) map.remove(key); + return (T) MAP.remove(key); } } diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/CallManager.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/CallManager.java index 6ad49004..23367936 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/CallManager.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/CallManager.java @@ -17,6 +17,8 @@ package cn.hippo4j.rpc.client; +import cn.hippo4j.common.toolkit.ThreadUtil; + public class CallManager { public int call() { @@ -27,4 +29,10 @@ public class CallManager { return a + b; } + public int callTestTimeout() { + // thread sleep for 10 seconds + ThreadUtil.sleep(10000); + return 1; + } + } diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RPCClientTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RPCClientTest.java index 46806762..f10cb0eb 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RPCClientTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RPCClientTest.java @@ -109,19 +109,53 @@ public class RPCClientTest { rpcServer.close(); } + @Test(expected = Exception.class) + public void responseNullExceptionTest() throws IOException { + Class cls = CallManager.class; + String className = cls.getName(); + ClassRegistry.put(className, cls); + // The mode connection was denied when the server was started on the specified port + Instance instance = new DefaultInstance(); + NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); + ServerConnection connection = new NettyServerConnection(handler); + RPCServer rpcServer = new RPCServer(connection, port); + rpcServer.bind(); + while (!rpcServer.isActive()) { + ThreadUtil.sleep(100L); + } + InetSocketAddress address = InetSocketAddress.createUnresolved(host, port.getPort()); + ChannelPoolHandler channelPoolHandler = new NettyClientPoolHandler(new NettyClientTakeHandler()); + ClientConnection clientConnection = new NettyClientConnection(address, channelPoolHandler); + clientConnection.setTimeout(300L); + try (RPCClient rpcClient = new RPCClient(clientConnection)) { + Request request = new DefaultRequest("127.0.0.18888", className, "callTestTimeout", null, null); + Response response = rpcClient.connection(request); + Assert.assertNotNull(response.getErrMsg()); + Assert.assertNotNull(response.getThrowable()); + } catch (IOException e) { + // no something + } finally { + rpcServer.close(); + } + } + static class TestServerPort implements ServerPort { + int port = RandomPort.getSafeRandomPort(); + @Override public int getPort() { - return 8888; + return port; } } static class TestPortServerPort implements ServerPort { + int port = RandomPort.getSafeRandomPort(); + @Override public int getPort() { - return 8889; + return port; } } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RandomPort.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RandomPort.java new file mode 100644 index 00000000..63c21d41 --- /dev/null +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/client/RandomPort.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.rpc.client; + +import java.io.IOException; +import java.net.ServerSocket; + +public class RandomPort { + + public static int getSafeRandomPort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/ConnectHandlerTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/ConnectHandlerTest.java index 1b40366a..6351364e 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/ConnectHandlerTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/ConnectHandlerTest.java @@ -20,7 +20,16 @@ package cn.hippo4j.rpc.handler; import cn.hippo4j.common.toolkit.ThreadUtil; import cn.hippo4j.rpc.client.NettyClientConnection; import cn.hippo4j.rpc.client.RPCClient; -import cn.hippo4j.rpc.discovery.*; +import cn.hippo4j.rpc.client.RandomPort; +import cn.hippo4j.rpc.discovery.ClassRegistry; +import cn.hippo4j.rpc.discovery.DefaultInstance; +import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.discovery.InstanceServerLoader; +import cn.hippo4j.rpc.discovery.ServerPort; +import cn.hippo4j.rpc.model.DefaultRequest; +import cn.hippo4j.rpc.model.DefaultResponse; +import cn.hippo4j.rpc.model.Request; +import cn.hippo4j.rpc.model.Response; import cn.hippo4j.rpc.server.NettyServerConnection; import cn.hippo4j.rpc.server.RPCServer; import cn.hippo4j.rpc.support.NettyProxyCenter; @@ -38,7 +47,7 @@ public class ConnectHandlerTest { // server Class cls = InstanceServerLoader.class; ClassRegistry.put(cls.getName(), cls); - ServerPort port = () -> 8892; + ServerPort port = new TestServerPort(); Instance instance = new DefaultInstance(); NettyServerTakeHandler serverHandler = new NettyServerTakeHandler(instance); NettyServerConnection connection = new NettyServerConnection(serverHandler); @@ -59,4 +68,36 @@ public class ConnectHandlerTest { rpcServer.close(); } + @Test + public void testConnectHandlerDefault() { + ConnectHandler handler = new TestConnectHandler(); + + Request request = new DefaultRequest("key", "className", "methodName", new Class[0], new Object[0]); + Response response = handler.sendHandler(request); + Assert.assertNull(response); + Response response1 = new DefaultResponse("key", this.getClass(), handler); + String key = response1.getKey(); + Class cls = response1.getCls(); + Object obj = response1.getObj(); + handler.handler(response1); + Assert.assertEquals(key, response1.getKey()); + Assert.assertEquals(cls, response1.getCls()); + Assert.assertEquals(obj, response1.getObj()); + + } + + static class TestConnectHandler implements ConnectHandler { + + } + + static class TestServerPort implements ServerPort { + + int port = RandomPort.getSafeRandomPort(); + + @Override + public int getPort() { + return port; + } + } + } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/NettyClientPoolHandlerTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/NettyClientPoolHandlerTest.java index e1806508..7914df63 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/NettyClientPoolHandlerTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/NettyClientPoolHandlerTest.java @@ -17,10 +17,32 @@ package cn.hippo4j.rpc.handler; +import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.common.web.exception.IllegalException; +import cn.hippo4j.rpc.client.CallManager; +import cn.hippo4j.rpc.client.ClientConnection; +import cn.hippo4j.rpc.client.NettyClientConnection; +import cn.hippo4j.rpc.client.RPCClient; +import cn.hippo4j.rpc.client.RandomPort; +import cn.hippo4j.rpc.discovery.ClassRegistry; +import cn.hippo4j.rpc.discovery.DefaultInstance; +import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.discovery.ServerPort; +import cn.hippo4j.rpc.model.DefaultRequest; +import cn.hippo4j.rpc.model.Request; +import cn.hippo4j.rpc.model.Response; +import cn.hippo4j.rpc.server.NettyServerConnection; +import cn.hippo4j.rpc.server.RPCServer; +import cn.hippo4j.rpc.server.ServerConnection; import io.netty.channel.ChannelHandler; import org.junit.Assert; import org.junit.Test; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; + public class NettyClientPoolHandlerTest { @Test @@ -54,7 +76,7 @@ public class NettyClientPoolHandlerTest { public void addLast() { NettyClientPoolHandler handler = new NettyClientPoolHandler(); Assert.assertTrue(handler.isEmpty()); - handler.addLast(new TestHandler()); + handler.addLast(null, new TestHandler()); Assert.assertFalse(handler.isEmpty()); } @@ -62,7 +84,7 @@ public class NettyClientPoolHandlerTest { public void addFirst() { NettyClientPoolHandler handler = new NettyClientPoolHandler(); Assert.assertTrue(handler.isEmpty()); - handler.addFirst(new TestHandler()); + handler.addFirst(null, new TestHandler()); Assert.assertFalse(handler.isEmpty()); } @@ -81,4 +103,54 @@ public class NettyClientPoolHandlerTest { handler.addFirst("Test", new TestHandler()); Assert.assertFalse(handler.isEmpty()); } + + @Test(expected = IllegalException.class) + public void testGetHandlerEntityFalse() { + TestFalseHandler handler = new TestFalseHandler(); + long order = 0; + String name = "Test"; + NettyClientPoolHandler poolHandler = new NettyClientPoolHandler(); + poolHandler.getHandlerEntity(order, handler, name); + } + + @Test + public void connectionTest() throws IOException { + ServerPort port = new ServerPort() { + + final int a = RandomPort.getSafeRandomPort(); + + @Override + public int getPort() { + return a; + } + }; + Class cls = CallManager.class; + String className = cls.getName(); + ClassRegistry.put(className, cls); + // The mode connection was denied when the server was started on the specified port + Instance instance = new DefaultInstance(); + NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); + ServerConnection connection = new NettyServerConnection(handler); + RPCServer rpcServer = new RPCServer(connection, port); + rpcServer.bind(); + while (!rpcServer.isActive()) { + ThreadUtil.sleep(100L); + } + InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", port.getPort()); + List handlers = new ArrayList<>(); + handlers.add(new NettyClientTakeHandler()); + NettyClientPoolHandler channelPoolHandler = new NettyClientPoolHandler(handlers); + channelPoolHandler.addLast("test", new TestHandler()); + ClientConnection clientConnection = new NettyClientConnection(address, channelPoolHandler); + RPCClient rpcClient = new RPCClient(clientConnection); + Request request = new DefaultRequest("127.0.0.18888", className, "call", null, null); + for (int i = 0; i < 50; i++) { + Response response = rpcClient.connection(request); + boolean active = rpcClient.isActive(); + Assert.assertTrue(active); + Assert.assertEquals(response.getObj(), 1); + } + rpcClient.close(); + rpcServer.close(); + } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestFalseHandler.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestFalseHandler.java new file mode 100644 index 00000000..0109bbdf --- /dev/null +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestFalseHandler.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.rpc.handler; + +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; + +public class TestFalseHandler implements ChannelHandler { + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + + } +} diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestHandler.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestHandler.java index e99cba66..8d63d081 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestHandler.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/handler/TestHandler.java @@ -19,7 +19,7 @@ package cn.hippo4j.rpc.handler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; - +@ChannelHandler.Sharable public class TestHandler implements ChannelHandler { @Override diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultRequestTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultRequestTest.java index 26316a72..ada1121f 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultRequestTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultRequestTest.java @@ -21,7 +21,11 @@ import cn.hippo4j.rpc.discovery.InstanceServerLoaderImpl; import org.junit.Assert; import org.junit.Test; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.lang.reflect.Method; public class DefaultRequestTest { @@ -59,4 +63,18 @@ public class DefaultRequestTest { Assert.assertEquals(request1, request); } + @Test + public void testEquals() throws NoSuchMethodException { + String key = "name"; + String clsName = InstanceServerLoaderImpl.class.getName(); + Method method = InstanceServerLoaderImpl.class.getMethod("setName", String.class); + String methodName = method.getName(); + Class[] parameterTypes = method.getParameterTypes(); + Object[] parameters = new Object[1]; + parameters[0] = "hippo4j"; + Request request = new DefaultRequest(key, clsName, methodName, parameterTypes, parameters); + Assert.assertTrue(request.equals(request)); + Assert.assertFalse(request.equals(null)); + } + } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultResponseTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultResponseTest.java index d6c97993..33f4fb49 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultResponseTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/model/DefaultResponseTest.java @@ -21,7 +21,11 @@ import cn.hippo4j.common.web.exception.IllegalException; import org.junit.Assert; import org.junit.Test; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; public class DefaultResponseTest { @@ -83,4 +87,13 @@ public class DefaultResponseTest { Assert.assertTrue(response1.isErr()); } + @Test + public void testEquals() throws NoSuchMethodException { + String key = "name"; + Object o = "obj"; + Class cls = String.class; + Response response = new DefaultResponse(key, cls, o); + Assert.assertTrue(response.equals(response)); + Assert.assertFalse(response.equals(null)); + } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/NettyServerConnectionTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/NettyServerConnectionTest.java index 1a55a2ae..250429a8 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/NettyServerConnectionTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/NettyServerConnectionTest.java @@ -27,7 +27,7 @@ public class NettyServerConnectionTest { public void addLast() { NettyServerConnection connection = new NettyServerConnection(); Assert.assertTrue(connection.isEmpty()); - connection.addLast(new TestHandler()); + connection.addLast(null, new TestHandler()); Assert.assertFalse(connection.isEmpty()); } @@ -35,7 +35,7 @@ public class NettyServerConnectionTest { public void addFirst() { NettyServerConnection connection = new NettyServerConnection(); Assert.assertTrue(connection.isEmpty()); - connection.addFirst(new TestHandler()); + connection.addFirst(null, new TestHandler()); Assert.assertFalse(connection.isEmpty()); } diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/RPCServerTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/RPCServerTest.java index 91acd86c..ac6f2637 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/RPCServerTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/server/RPCServerTest.java @@ -18,15 +18,30 @@ package cn.hippo4j.rpc.server; import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.rpc.client.CallManager; +import cn.hippo4j.rpc.client.ClientConnection; +import cn.hippo4j.rpc.client.NettyClientConnection; +import cn.hippo4j.rpc.client.RPCClient; +import cn.hippo4j.rpc.client.RandomPort; +import cn.hippo4j.rpc.discovery.ClassRegistry; import cn.hippo4j.rpc.discovery.DefaultInstance; import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.discovery.ServerPort; +import cn.hippo4j.rpc.handler.NettyClientPoolHandler; +import cn.hippo4j.rpc.handler.NettyClientTakeHandler; import cn.hippo4j.rpc.handler.NettyServerTakeHandler; +import cn.hippo4j.rpc.handler.TestHandler; +import cn.hippo4j.rpc.model.DefaultRequest; +import cn.hippo4j.rpc.model.Request; +import cn.hippo4j.rpc.model.Response; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.pool.ChannelPoolHandler; import org.junit.Assert; import org.junit.Test; import java.io.IOException; +import java.net.InetSocketAddress; public class RPCServerTest { @@ -35,7 +50,7 @@ public class RPCServerTest { Instance instance = new DefaultInstance(); NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); ServerConnection connection = new NettyServerConnection(handler); - RPCServer rpcServer = new RPCServer(connection, () -> 8893); + RPCServer rpcServer = new RPCServer(connection, RandomPort::getSafeRandomPort); rpcServer.bind(); while (!rpcServer.isActive()) { ThreadUtil.sleep(100L); @@ -52,7 +67,7 @@ public class RPCServerTest { EventLoopGroup worker = new NioEventLoopGroup(); NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); ServerConnection connection = new NettyServerConnection(leader, worker, handler); - RPCServer rpcServer = new RPCServer(connection, () -> 8894); + RPCServer rpcServer = new RPCServer(connection, RandomPort::getSafeRandomPort); rpcServer.bind(); while (!rpcServer.isActive()) { ThreadUtil.sleep(100L); @@ -61,4 +76,57 @@ public class RPCServerTest { Assert.assertTrue(active); rpcServer.close(); } + + @Test + public void bindPipelineTest() throws IOException { + ServerPort serverPort = new ServerPort() { + + final int port = RandomPort.getSafeRandomPort(); + + @Override + public int getPort() { + return port; + } + }; + Class cls = CallManager.class; + String className = cls.getName(); + ClassRegistry.put(className, cls); + // The mode connection was denied when the server was started on the specified port + Instance instance = new DefaultInstance(); + NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); + NettyServerConnection connection = new NettyServerConnection(handler); + connection.addLast("Test", new TestHandler()); + RPCServer rpcServer = new RPCServer(connection, serverPort); + rpcServer.bind(); + while (!rpcServer.isActive()) { + ThreadUtil.sleep(100L); + } + InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", serverPort.getPort()); + ChannelPoolHandler channelPoolHandler = new NettyClientPoolHandler(new NettyClientTakeHandler()); + ClientConnection clientConnection = new NettyClientConnection(address, channelPoolHandler); + RPCClient rpcClient = new RPCClient(clientConnection); + Request request = new DefaultRequest("127.0.0.18888", className, "call", null, null); + for (int i = 0; i < 50; i++) { + Response response = rpcClient.connection(request); + boolean active = rpcClient.isActive(); + Assert.assertTrue(active); + Assert.assertEquals(response.getObj(), 1); + } + rpcClient.close(); + rpcServer.close(); + } + + @Test + public void bindNegativeTest() { + ServerPort serverPort = () -> -1; + Class cls = CallManager.class; + String className = cls.getName(); + ClassRegistry.put(className, cls); + // The mode connection was denied when the server was started on the specified port + Instance instance = new DefaultInstance(); + NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); + NettyServerConnection connection = new NettyServerConnection(handler); + RPCServer rpcServer = new RPCServer(connection, serverPort); + rpcServer.bind(); + } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyClientSupportTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyClientSupportTest.java new file mode 100644 index 00000000..f1d5e09f --- /dev/null +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyClientSupportTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.rpc.support; + +import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.rpc.client.CallManager; +import cn.hippo4j.rpc.client.ClientConnection; +import cn.hippo4j.rpc.client.NettyClientConnection; +import cn.hippo4j.rpc.client.RPCClient; +import cn.hippo4j.rpc.client.RandomPort; +import cn.hippo4j.rpc.discovery.ClassRegistry; +import cn.hippo4j.rpc.discovery.DefaultInstance; +import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.discovery.ServerPort; +import cn.hippo4j.rpc.handler.NettyClientPoolHandler; +import cn.hippo4j.rpc.handler.NettyClientTakeHandler; +import cn.hippo4j.rpc.handler.NettyServerTakeHandler; +import cn.hippo4j.rpc.handler.TestHandler; +import cn.hippo4j.rpc.server.NettyServerConnection; +import cn.hippo4j.rpc.server.RPCServer; +import io.netty.channel.pool.ChannelPoolHandler; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; + +public class NettyClientSupportTest { + + @Test + public void closeTest() throws IOException { + int port = RandomPort.getSafeRandomPort(); + ServerPort serverPort = () -> port; + Class cls = CallManager.class; + String className = cls.getName(); + ClassRegistry.put(className, cls); + // The mode connection was denied when the server was started on the specified port + Instance instance = new DefaultInstance(); + NettyServerTakeHandler handler = new NettyServerTakeHandler(instance); + NettyServerConnection connection = new NettyServerConnection(handler); + connection.addLast("Test", new TestHandler()); + RPCServer rpcServer = new RPCServer(connection, serverPort); + rpcServer.bind(); + while (!rpcServer.isActive()) { + ThreadUtil.sleep(100L); + } + InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", port); + ChannelPoolHandler channelPoolHandler = new NettyClientPoolHandler(new NettyClientTakeHandler()); + ClientConnection clientConnection = new NettyClientConnection(address, channelPoolHandler); + RPCClient rpcClient = new RPCClient(clientConnection); + + NettyClientSupport.closeClient(new InetSocketAddress("localhost", port)); + + rpcClient.close(); + rpcServer.close(); + } + +} diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolHolderTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolHolderTest.java index b367b1d9..a08b3adb 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolHolderTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolHolderTest.java @@ -17,6 +17,7 @@ package cn.hippo4j.rpc.support; +import cn.hippo4j.rpc.client.RandomPort; import cn.hippo4j.rpc.discovery.ServerPort; import cn.hippo4j.rpc.handler.NettyClientPoolHandler; import cn.hippo4j.rpc.handler.NettyClientTakeHandler; @@ -78,7 +79,7 @@ public class NettyConnectPoolHolderTest { @Override public int getPort() { - return 8895; + return RandomPort.getSafeRandomPort(); } } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolTest.java index b9a0685f..bdc45d42 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyConnectPoolTest.java @@ -18,6 +18,7 @@ package cn.hippo4j.rpc.support; import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.rpc.client.RandomPort; import cn.hippo4j.rpc.discovery.DefaultInstance; import cn.hippo4j.rpc.discovery.Instance; import cn.hippo4j.rpc.discovery.ServerPort; @@ -112,9 +113,10 @@ public class NettyConnectPoolTest { static class TestServerPort implements ServerPort { + int port = RandomPort.getSafeRandomPort(); @Override public int getPort() { - return 8890; + return port; } } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyProxyCenterTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyProxyCenterTest.java index b75cef3b..aafff550 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyProxyCenterTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyProxyCenterTest.java @@ -17,13 +17,28 @@ package cn.hippo4j.rpc.support; +import cn.hippo4j.common.toolkit.ThreadUtil; import cn.hippo4j.common.web.exception.IllegalException; +import cn.hippo4j.rpc.client.Client; +import cn.hippo4j.rpc.client.NettyClientConnection; +import cn.hippo4j.rpc.client.RPCClient; +import cn.hippo4j.rpc.client.RandomPort; +import cn.hippo4j.rpc.discovery.ClassRegistry; +import cn.hippo4j.rpc.discovery.DefaultInstance; +import cn.hippo4j.rpc.discovery.Instance; +import cn.hippo4j.rpc.discovery.InstanceServerLoader; import cn.hippo4j.rpc.discovery.ServerPort; +import cn.hippo4j.rpc.exception.ConnectionException; import cn.hippo4j.rpc.handler.NettyClientPoolHandler; import cn.hippo4j.rpc.handler.NettyClientTakeHandler; +import cn.hippo4j.rpc.handler.NettyServerTakeHandler; +import cn.hippo4j.rpc.server.NettyServerConnection; +import cn.hippo4j.rpc.server.RPCServer; +import io.netty.channel.pool.ChannelPoolHandler; import org.junit.Assert; import org.junit.Test; +import java.io.IOException; import java.net.InetSocketAddress; public class NettyProxyCenterTest { @@ -42,6 +57,27 @@ public class NettyProxyCenterTest { public void createProxy() { ProxyInterface localhost = NettyProxyCenter.getProxy(ProxyInterface.class, "localhost:8894"); Assert.assertNotNull(localhost); + NettyProxyCenter.getProxy(ProxyInterface.class, "localhost:8894"); + InetSocketAddress socketAddress = InetSocketAddress.createUnresolved("localhost", 8894); + Client client = NettyClientSupport.getClient(socketAddress); + ProxyInterface proxy = NettyProxyCenter.createProxy(client, ProxyInterface.class, socketAddress); + Assert.assertNotNull(proxy); + } + + @Test(expected = ConnectionException.class) + public void createProxyException() { + NettyProxyCenter.getProxy(ProxyInterface.class, "localhost8894"); + } + + @Test + public void removeProxy() { + NettyProxyCenter.getProxy(ProxyInterface.class, "localhost:8894"); + NettyProxyCenter.removeProxy(ProxyInterface.class, "localhost:8894"); + } + + @Test(expected = ConnectionException.class) + public void removeProxyException() { + NettyProxyCenter.removeProxy(ProxyInterface.class, "localhost8894"); } @Test(expected = IllegalException.class) @@ -52,6 +88,32 @@ public class NettyProxyCenterTest { Assert.assertNotNull(localhost); } + @Test + public void bindPipelineTest() throws IOException { + // server + Class cls = InstanceServerLoader.class; + ClassRegistry.put(cls.getName(), cls); + ServerPort port = new TestServerPort(); + Instance instance = new DefaultInstance(); + NettyServerTakeHandler serverHandler = new NettyServerTakeHandler(instance); + NettyServerConnection connection = new NettyServerConnection(serverHandler); + RPCServer rpcServer = new RPCServer(connection, port); + rpcServer.bind(); + while (!rpcServer.isActive()) { + ThreadUtil.sleep(100L); + } + InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", port.getPort()); + ChannelPoolHandler channelPoolHandler = new NettyClientPoolHandler(new NettyClientTakeHandler()); + NettyClientConnection clientConnection = new NettyClientConnection(address, channelPoolHandler); + RPCClient rpcClient = new RPCClient(clientConnection); + + InstanceServerLoader loader = NettyProxyCenter.createProxy(rpcClient, cls, address); + String name = loader.getName(); + Assert.assertEquals("name", name); + rpcClient.close(); + rpcServer.close(); + } + interface ProxyInterface { void hello(); @@ -63,9 +125,11 @@ public class NettyProxyCenterTest { static class TestServerPort implements ServerPort { + int port = RandomPort.getSafeRandomPort(); + @Override public int getPort() { - return 8894; + return port; } } } \ No newline at end of file diff --git a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyServerSupportTest.java b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyServerSupportTest.java index 4db1759e..bb9a9be0 100644 --- a/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyServerSupportTest.java +++ b/hippo4j-rpc/src/test/java/cn/hippo4j/rpc/support/NettyServerSupportTest.java @@ -18,17 +18,33 @@ package cn.hippo4j.rpc.support; import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.rpc.client.RandomPort; import cn.hippo4j.rpc.discovery.InstanceServerLoader; import org.junit.Assert; import org.junit.Test; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class NettyServerSupportTest { @Test - public synchronized void bind() throws IOException { - NettyServerSupport support = new NettyServerSupport(() -> 8891, InstanceServerLoader.class); + public void bind() throws IOException { + NettyServerSupport support = new NettyServerSupport(RandomPort::getSafeRandomPort, InstanceServerLoader.class); + support.bind(); + while (!support.isActive()) { + ThreadUtil.sleep(100L); + } + Assert.assertTrue(support.isActive()); + support.close(); + } + + @Test + public void bindTest() throws IOException { + List> classes = new ArrayList<>(); + classes.add(InstanceServerLoader.class); + NettyServerSupport support = new NettyServerSupport(RandomPort::getSafeRandomPort, classes); support.bind(); while (!support.isActive()) { ThreadUtil.sleep(100L); diff --git a/hippo4j-server/hippo4j-auth/src/main/java/cn/hippo4j/auth/config/GlobalSecurityConfig.java b/hippo4j-server/hippo4j-auth/src/main/java/cn/hippo4j/auth/config/GlobalSecurityConfig.java index b053a48f..b239b42c 100644 --- a/hippo4j-server/hippo4j-auth/src/main/java/cn/hippo4j/auth/config/GlobalSecurityConfig.java +++ b/hippo4j-server/hippo4j-auth/src/main/java/cn/hippo4j/auth/config/GlobalSecurityConfig.java @@ -28,7 +28,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.BeanIds; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/controller/MonitorController.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/controller/MonitorController.java index 29c64afa..ef48fbba 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/controller/MonitorController.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/controller/MonitorController.java @@ -18,9 +18,7 @@ package cn.hippo4j.config.controller; import cn.hippo4j.common.constant.Constants; -import cn.hippo4j.common.monitor.Message; import cn.hippo4j.common.monitor.MessageWrapper; -import cn.hippo4j.common.toolkit.MessageConvert; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.model.biz.monitor.MonitorActiveRespDTO; @@ -31,7 +29,11 @@ import cn.hippo4j.config.service.biz.HisRunDataService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import java.util.List; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/mapper/HisRunDataMapper.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/mapper/HisRunDataMapper.java index 7918828a..8405f529 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/mapper/HisRunDataMapper.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/mapper/HisRunDataMapper.java @@ -39,13 +39,13 @@ public interface HisRunDataMapper extends BaseMapper { * @param endTime * @return */ - @Select("SELECT " + - "tenant_id, item_id, tp_id, max(completed_task_count) as max_completed_task_count " + - "FROM his_run_data " + - "where timestamp between #{startTime} and #{endTime} " + - "group by tenant_id, item_id, tp_id " + - "order by max_completed_task_count desc " + - "limit 8") + @Select("SELECT " + + "tenant_id, item_id, tp_id, max(completed_task_count) as max_completed_task_count " + + "FROM his_run_data " + + "where timestamp between #{startTime} and #{endTime} " + + "group by tenant_id, item_id, tp_id " + + "order by max_completed_task_count desc " + + "limit 8") List queryThreadPoolTaskSumRanking(@Param("startTime") Long startTime, @Param("endTime") Long endTime); /** @@ -55,13 +55,13 @@ public interface HisRunDataMapper extends BaseMapper { * @param endTime * @return */ - @Select("SELECT " + - "tenant_id, item_id, tp_id, max(queue_size) as max_queue_size, max(reject_count) as max_reject_count, max(completed_task_count) as max_completed_task_count " + - "FROM his_run_data " + - "where timestamp between #{startTime} and #{endTime} " + - "group by tenant_id, item_id, tp_id " + - "order by max_completed_task_count desc " + - "limit 4") + @Select("SELECT " + + "tenant_id, item_id, tp_id, max(queue_size) as max_queue_size, max(reject_count) as max_reject_count, max(completed_task_count) as max_completed_task_count " + + "FROM his_run_data " + + "where timestamp between #{startTime} and #{endTime} " + + "group by tenant_id, item_id, tp_id " + + "order by max_completed_task_count desc " + + "limit 4") List queryThreadPoolMaxRanking(@Param("startTime") Long startTime, @Param("endTime") Long endTime); @Data diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ConfigInstanceInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ConfigInstanceInfo.java index 7d4b52a1..8b0db0e3 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ConfigInstanceInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ConfigInstanceInfo.java @@ -17,7 +17,11 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisConfigVerifyInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisConfigVerifyInfo.java index 4fdab92a..d1bf7ec6 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisConfigVerifyInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisConfigVerifyInfo.java @@ -17,8 +17,11 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; -import com.fasterxml.jackson.annotation.JsonIgnore; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisRunDataInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisRunDataInfo.java index 80c9f758..3e264f18 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisRunDataInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/HisRunDataInfo.java @@ -17,7 +17,11 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ItemInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ItemInfo.java index 90995085..ded6310a 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ItemInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/ItemInfo.java @@ -17,7 +17,12 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/NotifyInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/NotifyInfo.java index aaabc6e8..77b616bf 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/NotifyInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/NotifyInfo.java @@ -17,7 +17,11 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/TenantInfo.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/TenantInfo.java index 768d988b..df94d4f3 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/TenantInfo.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/model/TenantInfo.java @@ -17,7 +17,11 @@ package cn.hippo4j.config.model; -import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java index f97fe5d0..77580eb3 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java @@ -30,7 +30,6 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import java.time.LocalDateTime; -import java.util.Date; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java index 082c25ca..5a3dfda4 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java @@ -22,7 +22,12 @@ import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.design.observer.AbstractSubjectCenter; import cn.hippo4j.common.design.observer.Observer; import cn.hippo4j.common.design.observer.ObserverMessage; -import cn.hippo4j.common.toolkit.*; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.Joiner; +import cn.hippo4j.common.toolkit.MapUtil; +import cn.hippo4j.common.toolkit.Md5Util; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.event.LocalDataChangeEvent; import cn.hippo4j.config.model.CacheItem; import cn.hippo4j.config.model.ConfigAllInfo; @@ -31,7 +36,12 @@ import cn.hippo4j.config.service.biz.ConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java index a63f8cf6..76ee8340 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java @@ -17,7 +17,11 @@ package cn.hippo4j.config.service; -import cn.hippo4j.common.toolkit.*; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.MapUtil; +import cn.hippo4j.common.toolkit.Md5Util; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.event.AbstractEvent; import cn.hippo4j.config.event.LocalDataChangeEvent; @@ -34,7 +38,11 @@ import org.springframework.stereotype.Service; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.*; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java index 03b23bb5..5035a88d 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java @@ -33,7 +33,14 @@ import com.fasterxml.jackson.core.type.TypeReference; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; diff --git a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java index ab5c43a2..b6010f7e 100644 --- a/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java +++ b/hippo4j-server/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java @@ -22,7 +22,15 @@ import cn.hippo4j.common.enums.DelEnum; import cn.hippo4j.common.model.register.DynamicThreadPoolRegisterParameter; import cn.hippo4j.common.model.register.DynamicThreadPoolRegisterWrapper; import cn.hippo4j.common.model.register.notify.DynamicThreadPoolRegisterServerNotifyParameter; -import cn.hippo4j.common.toolkit.*; +import cn.hippo4j.common.toolkit.Assert; +import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.ConditionUtil; +import cn.hippo4j.common.toolkit.ContentUtil; +import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.Md5Util; +import cn.hippo4j.common.toolkit.StringUtil; +import cn.hippo4j.common.toolkit.UserContext; import cn.hippo4j.common.web.exception.ServiceException; import cn.hippo4j.config.event.LocalDataChangeEvent; import cn.hippo4j.config.mapper.ConfigInfoMapper; @@ -34,8 +42,11 @@ import cn.hippo4j.config.model.LogRecordInfo; import cn.hippo4j.config.model.biz.notify.NotifyReqDTO; import cn.hippo4j.config.service.ConfigCacheService; import cn.hippo4j.config.service.ConfigChangePublisher; -import cn.hippo4j.config.service.biz.*; -import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.config.service.biz.ConfigService; +import cn.hippo4j.config.service.biz.ItemService; +import cn.hippo4j.config.service.biz.NotifyService; +import cn.hippo4j.config.service.biz.OperationLogService; +import cn.hippo4j.config.service.biz.TenantService; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; @@ -44,7 +55,13 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.SynchronousQueue; import java.util.stream.Collectors; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/config/WebThreadPoolHandlerConfiguration1x.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/config/WebThreadPoolHandlerConfiguration1x.java index 7ba71536..3340b3fc 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/config/WebThreadPoolHandlerConfiguration1x.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/config/WebThreadPoolHandlerConfiguration1x.java @@ -17,8 +17,8 @@ package cn.hippo4j.config.springboot1x.starter.config; -import cn.hippo4j.adapter.web.*; import cn.hippo4j.adapter.web.WebThreadPoolRunStateHandler; +import cn.hippo4j.adapter.web.WebThreadPoolService; import cn.hippo4j.config.springboot1x.starter.web.jetty.JettyWebThreadPoolHandler1x; import cn.hippo4j.config.springboot1x.starter.web.tomcat.TomcatWebThreadPoolHandler1x; import cn.hippo4j.config.springboot1x.starter.web.undertow.UndertowWebThreadPoolHandler1x; @@ -29,6 +29,7 @@ import org.apache.catalina.Server; import org.apache.catalina.startup.Tomcat; import org.eclipse.jetty.webapp.WebAppContext; import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.SearchStrategy; @@ -47,6 +48,7 @@ public class WebThreadPoolHandlerConfiguration1x { @Configuration @ConditionalOnClass({Servlet.class, Tomcat.class}) + @ConditionalOnBean(WebThreadPoolRunStateHandler.class) @ConditionalOnMissingBean(value = WebThreadPoolService.class, search = SearchStrategy.CURRENT) static class EmbeddedTomcat { @@ -64,6 +66,7 @@ public class WebThreadPoolHandlerConfiguration1x { */ @Configuration @ConditionalOnClass({Servlet.class, Server.class, Loader.class, WebAppContext.class}) + @ConditionalOnBean(WebThreadPoolRunStateHandler.class) @ConditionalOnMissingBean(value = WebThreadPoolService.class, search = SearchStrategy.CURRENT) static class EmbeddedJetty { @@ -78,6 +81,7 @@ public class WebThreadPoolHandlerConfiguration1x { */ @Configuration @ConditionalOnClass({Servlet.class, Undertow.class, SslClientAuthMode.class}) + @ConditionalOnBean(WebThreadPoolRunStateHandler.class) @ConditionalOnMissingBean(value = WebThreadPoolService.class, search = SearchStrategy.CURRENT) static class EmbeddedUndertow { diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/refresher/SpringBoot1xBootstrapConfigPropertiesBinderAdapt.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/refresher/SpringBoot1xBootstrapConfigPropertiesBinderAdapt.java index 26a35088..4e4cf009 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/refresher/SpringBoot1xBootstrapConfigPropertiesBinderAdapt.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/refresher/SpringBoot1xBootstrapConfigPropertiesBinderAdapt.java @@ -73,7 +73,7 @@ public class SpringBoot1xBootstrapConfigPropertiesBinderAdapt implements Applica return bindableCoreProperties; } - private static Set getNames(Object target, Iterable prefixes) { + public static Set getNames(Object target, Iterable prefixes) { Set names = new LinkedHashSet<>(); if (target != null) { PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(target.getClass()); diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/AbstractWebThreadPoolService1x.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/AbstractWebThreadPoolService1x.java index 148a5deb..f0213907 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/AbstractWebThreadPoolService1x.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/AbstractWebThreadPoolService1x.java @@ -23,9 +23,6 @@ import cn.hippo4j.common.config.ApplicationContextHolder; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.embedded.EmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Field; /** * Abstract class for adapting WebThreadPoolService to Spring 1.x version. diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/tomcat/TomcatWebThreadPoolHandler1x.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/tomcat/TomcatWebThreadPoolHandler1x.java index 614c8ecf..5d87bb67 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/tomcat/TomcatWebThreadPoolHandler1x.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/tomcat/TomcatWebThreadPoolHandler1x.java @@ -17,14 +17,7 @@ package cn.hippo4j.config.springboot1x.starter.web.tomcat; -import cn.hippo4j.adapter.web.IWebThreadPoolHandlerSupport; import cn.hippo4j.adapter.web.tomcat.TomcatWebThreadPoolHandlerSupport; -import cn.hippo4j.common.enums.WebContainerEnum; -import cn.hippo4j.common.model.ThreadPoolBaseInfo; -import cn.hippo4j.common.model.ThreadPoolParameter; -import cn.hippo4j.common.model.ThreadPoolParameterInfo; -import cn.hippo4j.common.model.ThreadPoolRunStateInfo; -import cn.hippo4j.common.web.exception.ServiceException; import cn.hippo4j.config.springboot1x.starter.web.AbstractWebThreadPoolService1x; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; import lombok.extern.slf4j.Slf4j; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/undertow/UndertowWebThreadPoolHandler1x.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/undertow/UndertowWebThreadPoolHandler1x.java index c44a8e95..53e34907 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/undertow/UndertowWebThreadPoolHandler1x.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-1x-starter/src/main/java/cn/hippo4j/config/springboot1x/starter/web/undertow/UndertowWebThreadPoolHandler1x.java @@ -17,14 +17,7 @@ package cn.hippo4j.config.springboot1x.starter.web.undertow; -import cn.hippo4j.adapter.web.IWebThreadPoolHandlerSupport; import cn.hippo4j.adapter.web.undertow.UndertowWebThreadPoolHandlerSupport; -import cn.hippo4j.common.enums.WebContainerEnum; -import cn.hippo4j.common.model.ThreadPoolBaseInfo; -import cn.hippo4j.common.model.ThreadPoolParameter; -import cn.hippo4j.common.model.ThreadPoolParameterInfo; -import cn.hippo4j.common.model.ThreadPoolRunStateInfo; -import cn.hippo4j.common.web.exception.ServiceException; import cn.hippo4j.config.springboot1x.starter.web.AbstractWebThreadPoolService1x; import io.undertow.Undertow; import lombok.extern.slf4j.Slf4j; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/BootstrapConfigProperties.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/BootstrapConfigProperties.java index 4d4ee17c..04cd9033 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/BootstrapConfigProperties.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/BootstrapConfigProperties.java @@ -17,12 +17,14 @@ package cn.hippo4j.config.springboot.starter.config; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.config.springboot.starter.parser.ConfigFileTypeEnum; import cn.hippo4j.core.config.BootstrapPropertiesInterface; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; +import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -85,7 +87,7 @@ public class BootstrapConfigProperties implements BootstrapPropertiesInterface { /** * Notify platforms. */ - private List notifyPlatforms; + private List notifyPlatforms = new ArrayList<>(); /** * Check thread pool running status interval. diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/WebExecutorProperties.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/WebExecutorProperties.java index 95569405..c0a31472 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/WebExecutorProperties.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/config/WebExecutorProperties.java @@ -17,7 +17,7 @@ package cn.hippo4j.config.springboot.starter.config; -import cn.hippo4j.common.api.ExecutorNotifyProperties; +import cn.hippo4j.common.config.ExecutorNotifyProperties; import cn.hippo4j.common.api.IExecutorProperties; import lombok.Data; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/ConfigModeNotifyConfigBuilder.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/ConfigModeNotifyConfigBuilder.java index f765ada5..b12ab6ed 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/ConfigModeNotifyConfigBuilder.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/ConfigModeNotifyConfigBuilder.java @@ -18,18 +18,26 @@ package cn.hippo4j.config.springboot.starter.notify; import cn.hippo4j.adapter.web.WebThreadPoolService; -import cn.hippo4j.common.api.ExecutorNotifyProperties; import cn.hippo4j.common.api.IExecutorProperties; +import cn.hippo4j.common.config.ExecutorNotifyProperties; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.config.springboot.starter.config.*; +import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; +import cn.hippo4j.config.springboot.starter.config.NotifyPlatformProperties; +import cn.hippo4j.config.springboot.starter.config.WebExecutorProperties; import cn.hippo4j.message.api.NotifyConfigBuilder; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.service.AlarmControlHandler; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; /** diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/ConfigParserHandler.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/ConfigParserHandler.java index 61eb3056..3b34bf25 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/ConfigParserHandler.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/ConfigParserHandler.java @@ -18,7 +18,11 @@ package cn.hippo4j.config.springboot.starter.parser; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; /** * Config parser handler. diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/YamlConfigParser.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/YamlConfigParser.java index 9613e882..e05f8bea 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/YamlConfigParser.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/parser/YamlConfigParser.java @@ -22,7 +22,9 @@ import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.io.ByteArrayResource; import org.springframework.util.StringUtils; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Yaml config parser. diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/EtcdRefresherHandler.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/EtcdRefresherHandler.java index 1ae52abb..af4a2080 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/EtcdRefresherHandler.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/EtcdRefresherHandler.java @@ -19,7 +19,11 @@ package cn.hippo4j.config.springboot.starter.refresher; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.StringUtil; -import io.etcd.jetcd.*; +import io.etcd.jetcd.ByteSequence; +import io.etcd.jetcd.Client; +import io.etcd.jetcd.ClientBuilder; +import io.etcd.jetcd.KeyValue; +import io.etcd.jetcd.Watch; import io.etcd.jetcd.kv.GetResponse; import io.etcd.jetcd.watch.WatchEvent; import io.etcd.jetcd.watch.WatchResponse; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/DynamicThreadPoolRefreshListener.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/DynamicThreadPoolRefreshListener.java index f802c27b..99f97ca0 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/DynamicThreadPoolRefreshListener.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/DynamicThreadPoolRefreshListener.java @@ -24,13 +24,12 @@ import cn.hippo4j.common.executor.support.ResizableCapacityLinkedBlockingQueue; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.ThreadPoolExecutorUtil; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; -import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.config.springboot.starter.notify.ConfigModeNotifyConfigBuilder; import cn.hippo4j.config.springboot.starter.support.GlobalCoreThreadPoolManage; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.message.dto.NotifyConfigDTO; -import cn.hippo4j.message.enums.NotifyTypeEnum; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.message.service.GlobalNotifyAlarmManage; import cn.hippo4j.message.service.Hippo4jBaseSendMessageService; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/PlatformsRefreshListener.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/PlatformsRefreshListener.java index f117082f..8191b0b5 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/PlatformsRefreshListener.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/PlatformsRefreshListener.java @@ -19,7 +19,7 @@ package cn.hippo4j.config.springboot.starter.refresher.event; import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; -import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.config.springboot.starter.notify.ConfigModeNotifyConfigBuilder; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolConfigService.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolConfigService.java index 4a997d77..df9a265e 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolConfigService.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolConfigService.java @@ -23,7 +23,7 @@ import cn.hippo4j.common.model.register.DynamicThreadPoolRegisterParameter; import cn.hippo4j.common.model.register.DynamicThreadPoolRegisterWrapper; import cn.hippo4j.common.model.register.notify.DynamicThreadPoolRegisterCoreNotifyParameter; import cn.hippo4j.common.toolkit.BooleanUtil; -import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.support.service.AbstractDynamicThreadPoolService; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolPostProcessor.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolPostProcessor.java index 70137141..98db66ce 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolPostProcessor.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/DynamicThreadPoolPostProcessor.java @@ -23,8 +23,8 @@ import cn.hippo4j.common.executor.support.RejectedPolicyTypeEnum; import cn.hippo4j.common.toolkit.ReflectUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; -import cn.hippo4j.common.api.ExecutorNotifyProperties; -import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; +import cn.hippo4j.common.config.ExecutorNotifyProperties; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.core.executor.DynamicThreadPool; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/GlobalCoreThreadPoolManage.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/GlobalCoreThreadPoolManage.java index bef01cac..7a8cacf2 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/GlobalCoreThreadPoolManage.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/support/GlobalCoreThreadPoolManage.java @@ -17,7 +17,7 @@ package cn.hippo4j.config.springboot.starter.support; -import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; +import cn.hippo4j.common.config.ExecutorProperties; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-elasticsearch/src/main/java/cn/hippo4j/springboot/starter/monitor/elasticsearch/ElasticSearchMonitorAutoConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-elasticsearch/src/main/java/cn/hippo4j/springboot/starter/monitor/elasticsearch/ElasticSearchMonitorAutoConfiguration.java index b9d73921..73954005 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-elasticsearch/src/main/java/cn/hippo4j/springboot/starter/monitor/elasticsearch/ElasticSearchMonitorAutoConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-elasticsearch/src/main/java/cn/hippo4j/springboot/starter/monitor/elasticsearch/ElasticSearchMonitorAutoConfiguration.java @@ -17,10 +17,12 @@ package cn.hippo4j.springboot.starter.monitor.elasticsearch; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.monitor.elasticsearch.AdapterThreadPoolElasticSearchMonitorHandler; import cn.hippo4j.monitor.elasticsearch.DynamicThreadPoolElasticSearchMonitorHandler; import cn.hippo4j.monitor.elasticsearch.WebThreadPoolElasticSearchMonitorHandler; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -29,6 +31,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration @ConditionalOnExpression("'${spring.dynamic.thread-pool.monitor.collect-types:}'.contains('elasticsearch')") +@ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") public class ElasticSearchMonitorAutoConfiguration { @Bean diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-local-log/src/main/java/cn/hippo4j/springboot/starter/monitor/local/log/LocalLogMonitorAutoConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-local-log/src/main/java/cn/hippo4j/springboot/starter/monitor/local/log/LocalLogMonitorAutoConfiguration.java index d59c8912..ae6e50d3 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-local-log/src/main/java/cn/hippo4j/springboot/starter/monitor/local/log/LocalLogMonitorAutoConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-local-log/src/main/java/cn/hippo4j/springboot/starter/monitor/local/log/LocalLogMonitorAutoConfiguration.java @@ -18,11 +18,13 @@ package cn.hippo4j.springboot.starter.monitor.local.log; import cn.hippo4j.adapter.web.WebThreadPoolService; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.monitor.local.log.AdapterThreadPoolLocalLogMonitorHandler; import cn.hippo4j.monitor.local.log.DynamicThreadPoolLocalLogMonitorHandler; import cn.hippo4j.monitor.local.log.WebThreadPoolLocalLogMonitorHandler; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,6 +33,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration @ConditionalOnExpression("'${spring.dynamic.thread-pool.monitor.collect-types:}'.contains('log')") +@ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") public class LocalLogMonitorAutoConfiguration { @Bean diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java index d523575f..1ae9406e 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java @@ -18,11 +18,13 @@ package cn.hippo4j.springboot.starter.monitor.micrometer; import cn.hippo4j.adapter.web.WebThreadPoolService; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.monitor.micrometer.AdapterThreadPoolMicrometerMonitorHandler; import cn.hippo4j.monitor.micrometer.DynamicThreadPoolMicrometerMonitorHandler; import cn.hippo4j.monitor.micrometer.WebThreadPoolMicrometerMonitorHandler; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,6 +33,7 @@ import org.springframework.context.annotation.Configuration; */ @Configuration @ConditionalOnExpression("'${spring.dynamic.thread-pool.monitor.collect-types:}'.contains('micrometer')") +@ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") public class MicrometerMonitorAutoConfiguration { @Bean diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/BootstrapProperties.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/BootstrapProperties.java index 8faf4dcc..ba348c75 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/BootstrapProperties.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/BootstrapProperties.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.config; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.core.config.BootstrapPropertiesInterface; import lombok.Getter; import lombok.Setter; @@ -29,11 +30,9 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @Slf4j @Getter @Setter -@ConfigurationProperties(prefix = BootstrapProperties.PREFIX) +@ConfigurationProperties(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX) public class BootstrapProperties implements BootstrapPropertiesInterface { - public static final String PREFIX = "spring.dynamic.thread-pool"; - /** * Username */ diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DynamicThreadPoolAutoConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DynamicThreadPoolAutoConfiguration.java index 124f9810..5b9ee75a 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DynamicThreadPoolAutoConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DynamicThreadPoolAutoConfiguration.java @@ -24,6 +24,7 @@ import cn.hippo4j.common.api.ThreadPoolCheckAlarm; import cn.hippo4j.common.api.ThreadPoolConfigChange; import cn.hippo4j.common.api.ThreadPoolDynamicRefresh; import cn.hippo4j.common.config.ApplicationContextHolder; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.core.config.UtilAutoConfiguration; import cn.hippo4j.core.enable.MarkerConfiguration; import cn.hippo4j.core.executor.state.ThreadPoolRunStateHandler; @@ -90,7 +91,7 @@ import org.springframework.core.env.ConfigurableEnvironment; @AllArgsConstructor @ConditionalOnBean(MarkerConfiguration.Marker.class) @EnableConfigurationProperties(BootstrapProperties.class) -@ConditionalOnProperty(prefix = BootstrapProperties.PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") +@ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") @ImportAutoConfiguration({WebAdapterConfiguration.class, NettyClientConfiguration.class, DiscoveryConfiguration.class, MessageConfiguration.class, UtilAutoConfiguration.class}) public class DynamicThreadPoolAutoConfiguration { diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/NettyClientConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/NettyClientConfiguration.java index 0eb02844..e628a831 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/NettyClientConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/NettyClientConfiguration.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.config; +import cn.hippo4j.common.constant.Constants; import cn.hippo4j.springboot.starter.monitor.send.netty.NettyConnectSender; import cn.hippo4j.springboot.starter.monitor.send.MessageSender; import cn.hippo4j.springboot.starter.remote.ServerNettyAgent; @@ -26,7 +27,7 @@ import org.springframework.context.annotation.Bean; /** * Netty client configuration. */ -@ConditionalOnProperty(prefix = BootstrapProperties.PREFIX, name = "report-type", havingValue = "netty") +@ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, name = "report-type", havingValue = "netty") public class NettyClientConfiguration { @Bean diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/controller/WebThreadPoolController.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/controller/WebThreadPoolController.java index a6ba1e51..ba9d3353 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/controller/WebThreadPoolController.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/controller/WebThreadPoolController.java @@ -25,7 +25,12 @@ import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import lombok.AllArgsConstructor; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * Web thread pool controller. diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java index 5af0460d..1e5af1a7 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java @@ -17,13 +17,13 @@ package cn.hippo4j.springboot.starter.core; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.common.model.ThreadPoolParameterInfo; import cn.hippo4j.common.toolkit.ContentUtil; import cn.hippo4j.common.toolkit.GroupKey; import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.web.base.Result; -import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.springboot.starter.remote.HttpAgent; import cn.hippo4j.springboot.starter.remote.ServerHealthCheck; import lombok.SneakyThrows; @@ -32,7 +32,12 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.util.StringUtils; import java.net.URLDecoder; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java index 33fc7259..31f4116e 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java @@ -23,7 +23,6 @@ import cn.hippo4j.common.monitor.Message; import cn.hippo4j.common.monitor.MessageTypeEnum; import cn.hippo4j.common.monitor.RuntimeMessage; import cn.hippo4j.common.toolkit.BeanUtil; -import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; import cn.hippo4j.springboot.starter.config.BootstrapProperties; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java index 5166cd9b..cc5abd36 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java @@ -23,7 +23,11 @@ import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Random; /** * Server list manager.