diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/classloader/ClassLoaderManager.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/classloader/ClassLoaderManager.java index 58a18eafa4..da1f7041ea 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/classloader/ClassLoaderManager.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/classloader/ClassLoaderManager.java @@ -17,6 +17,7 @@ package com.huaweicloud.sermant.core.classloader; import com.huaweicloud.sermant.core.common.CommonConstant; +import com.huaweicloud.sermant.core.exception.FileCheckException; import com.huaweicloud.sermant.core.plugin.classloader.PluginClassFinder; import com.huaweicloud.sermant.core.plugin.classloader.PluginClassLoader; import com.huaweicloud.sermant.core.utils.FileUtils; @@ -25,6 +26,8 @@ import java.io.File; import java.net.MalformedURLException; import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -76,7 +79,12 @@ private static FrameworkClassLoader initFrameworkClassLoader(String path) throws * @return PluginClassLoader */ public static PluginClassLoader createPluginClassLoader() { - return new PluginClassLoader(new URL[0], sermantClassLoader); + return AccessController.doPrivileged(new PrivilegedAction() { + @Override + public PluginClassLoader run() { + return new PluginClassLoader(new URL[0], sermantClassLoader); + } + }); } public static SermantClassLoader getSermantClassLoader() { @@ -99,11 +107,11 @@ public static PluginClassFinder getPluginClassFinder() { private static URL[] listCoreImplementUrls(String coreImplementPath) throws MalformedURLException { File coreImplementDir = new File(FileUtils.validatePath(coreImplementPath)); if (!coreImplementDir.exists() || !coreImplementDir.isDirectory()) { - throw new RuntimeException("core implement directory is not exist or is not directory."); + throw new FileCheckException("core implement directory is not exist or is not directory."); } File[] jars = coreImplementDir.listFiles((file, name) -> name.endsWith(".jar")); if (jars == null || jars.length == 0) { - throw new RuntimeException("core implement directory is empty"); + throw new FileCheckException("core implement directory is empty"); } List urlList = new ArrayList<>(); for (File jar : jars) { @@ -115,11 +123,11 @@ private static URL[] listCoreImplementUrls(String coreImplementPath) throws Malf private static URL[] listCommonLibUrls(String commonLibPath) throws MalformedURLException { File commonLibDir = new File(FileUtils.validatePath(commonLibPath)); if (!commonLibDir.exists() || !commonLibDir.isDirectory()) { - throw new RuntimeException("common lib is not exist or is not directory."); + throw new FileCheckException("common lib is not exist or is not directory."); } File[] jars = commonLibDir.listFiles((file, name) -> name.endsWith(".jar")); if (jars == null || jars.length == 0) { - throw new RuntimeException("common lib directory is empty"); + throw new FileCheckException("common lib directory is empty"); } List urlList = new ArrayList<>(); for (File jar : jars) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/common/LoggerFactory.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/common/LoggerFactory.java index 6a1018cce3..4606a9046b 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/common/LoggerFactory.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/common/LoggerFactory.java @@ -18,6 +18,7 @@ import com.huaweicloud.sermant.core.classloader.ClassLoaderManager; import com.huaweicloud.sermant.core.classloader.FrameworkClassLoader; +import com.huaweicloud.sermant.core.exception.LoggerInitException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -35,9 +36,9 @@ public class LoggerFactory { private static final String LOGGER_INIT_METHOD = "init"; - private static Logger defaultLogger; + private static volatile Logger defaultLogger; - private static Logger sermantLogger; + private static volatile Logger sermantLogger; private LoggerFactory() { } @@ -46,19 +47,23 @@ private LoggerFactory() { * 初始化logback配置文件路径 * * @param artifact 归属产品 - * @throws RuntimeException RuntimeException + * @throws LoggerInitException LoggerInitException */ public static void init(String artifact) { if (sermantLogger == null) { - FrameworkClassLoader frameworkClassLoader = ClassLoaderManager.getFrameworkClassLoader(); - try { - Method initMethod = frameworkClassLoader - .loadClass(LOGGER_FACTORY_IMPL_CLASS) - .getMethod(LOGGER_INIT_METHOD, String.class); - sermantLogger = (Logger) initMethod.invoke(null, artifact); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException - | InvocationTargetException e) { - throw new RuntimeException(e); + synchronized (LoggerFactory.class) { + if (sermantLogger == null) { + FrameworkClassLoader frameworkClassLoader = ClassLoaderManager.getFrameworkClassLoader(); + try { + Method initMethod = frameworkClassLoader + .loadClass(LOGGER_FACTORY_IMPL_CLASS) + .getMethod(LOGGER_INIT_METHOD, String.class); + sermantLogger = (Logger) initMethod.invoke(null, artifact); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + throw new LoggerInitException(e.getMessage()); + } + } } } } @@ -75,7 +80,11 @@ public static Logger getLogger() { // 避免日志重复获取 if (defaultLogger == null) { - defaultLogger = java.util.logging.Logger.getLogger("sermant"); + synchronized (LoggerFactory.class) { + if (defaultLogger == null) { + defaultLogger = java.util.logging.Logger.getLogger("sermant"); + } + } } return defaultLogger; } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/ConfigManager.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/ConfigManager.java index 4c548dccc4..8217bba4ee 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/ConfigManager.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/ConfigManager.java @@ -205,6 +205,7 @@ private static LoadConfigStrategy getLoadConfigStrategy(File configFile, Clas *

文件中声明的所有实现都将会进行遍历,每一个实现类都会通过spi获取实例,然后调用{@code configConsumer}进行消费 * * @param configConsumer 配置处理方法 + * @param classLoader 类加载器 */ private static void foreachConfig(ConfigConsumer configConsumer, ClassLoader classLoader) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigFieldKey.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigFieldKey.java index 0718c09827..8b03406770 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigFieldKey.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigFieldKey.java @@ -16,8 +16,6 @@ package com.huaweicloud.sermant.core.config.common; -import com.huaweicloud.sermant.core.config.utils.ConfigKeyUtil; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -25,9 +23,9 @@ /** * 通用字段键注解 - *

用于修饰配置对象的属性,与{@link ConfigTypeKey}一并构建配置信息键 + *

用于修饰配置对象的属性,与ConfigTypeKey一并构建配置信息键 *

主要作用是修正成员属性和配置键之间的差异 - *

见{@link ConfigKeyUtil#getFieldKey(java.lang.reflect.Field)} + *

见ConfigKeyUtil#getFieldKey(java.lang.reflect.Field) * * @author HapThorin * @version 1.0.0 @@ -36,5 +34,10 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface ConfigFieldKey { + /** + * 属性名 + * + * @return 属性名 + */ String value(); } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigTypeKey.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigTypeKey.java index 002764cad0..6b233be57f 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigTypeKey.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/common/ConfigTypeKey.java @@ -16,8 +16,6 @@ package com.huaweicloud.sermant.core.config.common; -import com.huaweicloud.sermant.core.config.utils.ConfigKeyUtil; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -27,7 +25,7 @@ * 通用配置对象前缀 *

如果配置对象中的所有属性对应的配置键都包含相同的前缀,那么可以使用该注解声明 *

与{@link ConfigFieldKey}一同构建配置键,{@link ConfigFieldKey}不存在时,直接使用属性名 - *

见{@link ConfigKeyUtil#getTypeKey(Class)} + *

见ConfigKeyUtil#getTypeKey(Class) * * @author HapThorin * @version 1.0.0 @@ -36,5 +34,10 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ConfigTypeKey { + /** + * 类型名 + * + * @return 类型名 + */ String value(); } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigFieldUtil.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigFieldUtil.java index 2d532f13b5..116477fe93 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigFieldUtil.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigFieldUtil.java @@ -39,11 +39,34 @@ public class ConfigFieldUtil { */ private static final Logger LOGGER = LoggerFactory.getLogger(); + /** + * boolean类型的get或set方法中属性名的最短长度 + */ + private static final int FIELD_NAME_MIN_LENGTH = 3; + + /** + * boolean类型的get或set方法中属性名的首字母下标 + */ + private static final int FIELD_NAME_CHECK_INDEX = 2; + + /** + * boolean类型的get方法前缀,首字母小写字母 + */ + private static final String BOOLEAN_FUNCTION_PREFIX_LOWERCASE = "is"; + + /** + * boolean类型的get方法前缀,首字母大写字母 + */ + private static final String BOOLEAN_FUNCTION_PREFIX_UPPERCASE = "Is"; + + private ConfigFieldUtil() { + } + /** * 设置值,优先查找{@code setter}调用,不存在时尝试直接赋值 *

因此,要求配置对象的属性值需要拥有相应的{@code setter},或者要求改属性值是公有的 * - * @param obj 被设置值的对象 + * @param obj 被设置值的对象 * @param field 被设置的字段 * @param value 被设置的字段值 */ @@ -69,17 +92,16 @@ public static void setField(Object obj, Field field, Object value) { /** * 通过属性名称获取{@code setter} * - * @param cls 配置对象类 + * @param cls 配置对象类 * @param fieldName 属性名称 - * @param type 属性类型 + * @param type 属性类型 * @return setter方法 */ private static Method getSetter(Class cls, String fieldName, Class type) { final String setterName; - if ((type == boolean.class || type == Boolean.class) && - fieldName.length() >= 3 && (fieldName.startsWith("is") || fieldName.startsWith("Is")) && - fieldName.charAt(2) >= 'A' && fieldName.charAt(2) <= 'Z') { - setterName = "set" + fieldName.substring(2); + if ((type == boolean.class || type == Boolean.class) && fieldName.length() >= FIELD_NAME_MIN_LENGTH + && checkFieldName(fieldName)) { + setterName = "set" + fieldName.substring(FIELD_NAME_CHECK_INDEX); } else { final char head = fieldName.charAt(0); setterName = "set" + ( @@ -109,6 +131,13 @@ private static void forceSet(Object obj, Field field, Object value) { } } + /** + * 获取属性对象 + * + * @param obj 目标对象 + * @param field 属性 + * @return 属性对象 + */ public static Object getField(Object obj, Field field) { try { final Method getter = getGetter(field.getDeclaringClass(), field.getName(), field.getType()); @@ -130,10 +159,9 @@ public static Object getField(Object obj, Field field) { private static Method getGetter(Class cls, String fieldName, Class type) { final String getterName; - if ((type == boolean.class || type == Boolean.class) && - fieldName.length() >= 3 && (fieldName.startsWith("is") || fieldName.startsWith("Is")) && - fieldName.charAt(2) >= 'A' && fieldName.charAt(2) <= 'Z') { - getterName = "is" + fieldName.substring(2); + if ((type == boolean.class || type == Boolean.class) && fieldName.length() >= FIELD_NAME_MIN_LENGTH + && checkFieldName(fieldName)) { + getterName = BOOLEAN_FUNCTION_PREFIX_LOWERCASE + fieldName.substring(FIELD_NAME_CHECK_INDEX); } else { final char head = fieldName.charAt(0); getterName = "get" + ( @@ -168,4 +196,11 @@ private static Object forceGet(Object obj, Field field) { private static boolean checkMethod(Method method, Field field) { return method != null && Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(field.getModifiers()); } + + private static boolean checkFieldName(String fieldName) { + return (fieldName.startsWith(BOOLEAN_FUNCTION_PREFIX_LOWERCASE) || fieldName.startsWith( + BOOLEAN_FUNCTION_PREFIX_UPPERCASE)) + && fieldName.charAt(FIELD_NAME_CHECK_INDEX) >= 'A' + && fieldName.charAt(FIELD_NAME_CHECK_INDEX) <= 'Z'; + } } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigValueUtil.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigValueUtil.java index 7fb63c6cb2..502f2f64fe 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigValueUtil.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/config/utils/ConfigValueUtil.java @@ -92,7 +92,7 @@ public class ConfigValueUtil { key -> key.toUpperCase(Locale.ROOT).replace('.', '-'), key -> key.toLowerCase(Locale.ROOT), key -> key.toLowerCase(Locale.ROOT).replace('.', '_'), - key -> key.toLowerCase(Locale.ROOT).replace('.', '-'), + key -> key.toLowerCase(Locale.ROOT).replace('.', '-') }; /** @@ -326,6 +326,7 @@ public static String fixValue(String configKey, String configVal, Map argsMap, @@ -347,17 +348,18 @@ private static String getFormatKeyFixVal(String key, String defaultVal, Map argsMap) { - // 1. xxx.xxx.appName直接获取 2. xxx.xxx.app-name处理为xxx.xxx.app.name再获取 + // appName直接获取、app-name处理为app.name再获取 String keyReplaceMiddleLine = transFromMiddleLine(key); Optional fixedValue = getValueByOrder(argsMap, keyReplaceMiddleLine); if (fixedValue.isPresent()) { return fixedValue.get(); } - // 3. xxx.xxx.appName分割为xxx.xxx.app.name + // appName分割为app.name String keyWithoutCamel = transFromCamel(keyReplaceMiddleLine); if (!keyReplaceMiddleLine.equals(keyWithoutCamel)) { fixedValue = getValueByOrder(argsMap, keyWithoutCamel); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/event/collector/FrameworkEventDefinitions.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/event/collector/FrameworkEventDefinitions.java index 20a4c9fdec..e67ca1e334 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/event/collector/FrameworkEventDefinitions.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/event/collector/FrameworkEventDefinitions.java @@ -88,6 +88,11 @@ public EventLevel getEventLevel() { return eventLevel; } + /** + * 获取范围 + * + * @return framework + */ public String getScope() { return "framework"; } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/FileCheckException.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/FileCheckException.java new file mode 100644 index 0000000000..ca4898186c --- /dev/null +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/FileCheckException.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2023 Huawei Technologies Co., Ltd. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.huaweicloud.sermant.core.exception; + +/** + * 文件检查异常 + * + * @author tangle + * @since 2023-11-07 + */ +public class FileCheckException extends RuntimeException { + private static final long serialVersionUID = 1339575470808108623L; + + /** + * 文件检查异常 + * + * @param message 异常信息 + */ + public FileCheckException(String message) { + super(message); + } +} diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/LoggerInitException.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/LoggerInitException.java new file mode 100644 index 0000000000..711e0e8775 --- /dev/null +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/LoggerInitException.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2023 Huawei Technologies Co., Ltd. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.huaweicloud.sermant.core.exception; + +/** + * 日志初始化异常 + * + * @author tangle + * @since 2023-11-08 + */ +public class LoggerInitException extends RuntimeException { + private static final long serialVersionUID = 4472931852795263687L; + + /** + * 日志初始化异常 + * + * @param message 异常信息 + */ + public LoggerInitException(String message) { + super(message); + } +} diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/NetInterfacesCheckException.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/NetInterfacesCheckException.java new file mode 100644 index 0000000000..0fd8fbfdba --- /dev/null +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/exception/NetInterfacesCheckException.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2023 Huawei Technologies Co., Ltd. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.huaweicloud.sermant.core.exception; + +/** + * ӿڼ쳣 + * + * @author tangle + * @since 2023-11-21 + */ +public class NetInterfacesCheckException extends RuntimeException { + private static final long serialVersionUID = -5485122231044249395L; + + /** + * ӿڼ쳣 + * + * @param message 쳣Ϣ + */ + public NetInterfacesCheckException(String message) { + super(message); + } +} diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/notification/NotificationManager.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/notification/NotificationManager.java index 5a6141e603..7a15348815 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/notification/NotificationManager.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/notification/NotificationManager.java @@ -50,12 +50,12 @@ private NotificationManager() { * @param typeClass 通知类型 */ public static void registry(NotificationListener notificationListener, - Class typeClass) { + Class typeClass) { if (!isEnable()) { return; } List listenerList = NOTIFICATION_LISTENER_MAP.computeIfAbsent( - typeClass.getCanonicalName(), s -> new ArrayList<>()); + typeClass.getCanonicalName(), key -> new ArrayList<>()); listenerList.add(notificationListener); } @@ -66,7 +66,7 @@ public static void registry(NotificationListener notificationListener, * @param typeClass 通知类型 */ public static void unRegistry(NotificationListener notificationListener, - Class typeClass) { + Class typeClass) { if (!isEnable()) { return; } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/annotations/BeanPropertyFlag.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/annotations/BeanPropertyFlag.java index 82c0412413..f780fdcd18 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/annotations/BeanPropertyFlag.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/annotations/BeanPropertyFlag.java @@ -16,8 +16,6 @@ package com.huaweicloud.sermant.core.plugin.agent.annotations; -import com.huaweicloud.sermant.core.plugin.agent.declarer.SuperTypeDeclarer; - import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; @@ -26,7 +24,7 @@ /** * Java Bean标记,被该注解修饰的接口,将根据该注解定义的属性在被增强类中实现get、set方法 - *

见{@link SuperTypeDeclarer.ForBeanProperty} + *

见SuperTypeDeclarer.ForBeanProperty * * @author HapThorin * @version 1.0.0 diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/collector/PluginCollector.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/collector/PluginCollector.java index df67d8a0cc..05b6956eb7 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/collector/PluginCollector.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/collector/PluginCollector.java @@ -74,6 +74,7 @@ public static List getDescriptions(Plugin plugin) { /** * 从插件收集器中获取所有插件描述器 * + * @param classLoader 类加载器 * @return 插件描述器集 */ private static List getDescriptions(ClassLoader classLoader) { @@ -99,7 +100,7 @@ private static PluginDescription combinePluginDeclarers(Plugin plugin) { if (classMatcher instanceof ClassTypeMatcher) { for (String typeName : ((ClassTypeMatcher) classMatcher).getTypeNames()) { List nameCombinedList = nameCombinedMap.computeIfAbsent(typeName, - k -> new ArrayList<>()); + key -> new ArrayList<>()); nameCombinedList.add(pluginDeclarer); } } else { @@ -126,7 +127,7 @@ public boolean matches(TypeDescription target) { for (PluginDeclarer declarer : combinedList) { if (matchTarget(declarer.getClassMatcher(), target)) { List declarers = nameCombinedMap.computeIfAbsent(typeName, - k -> new ArrayList<>()); + key -> new ArrayList<>()); if (!declarers.contains(declarer)) { declarers.add(declarer); } @@ -140,6 +141,7 @@ public boolean matches(TypeDescription target) { /** * 从插件收集器中获取所有插件声明器 * + * @param classLoader 类加载器 * @return 插件声明器集 */ private static List getDeclarers(ClassLoader classLoader) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/declarer/InterceptDeclarer.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/declarer/InterceptDeclarer.java index 6246aafd36..8008bb2f26 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/declarer/InterceptDeclarer.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/declarer/InterceptDeclarer.java @@ -71,6 +71,7 @@ public Interceptor[] getInterceptors(ClassLoader classLoader) { * @param interceptors 拦截器集 * @return 拦截声明器 * @throws IllegalArgumentException IllegalArgumentException + * @deprecated 已过时 */ @Deprecated public static InterceptDeclarer build(MethodMatcher methodMatcher, String... interceptors) { @@ -104,6 +105,7 @@ public Interceptor[] getInterceptors(ClassLoader classLoader) { * @throws ClassNotFoundException 找不到类 * @throws IllegalAccessException 无法访问addURL方法或defineClass方法 * @throws InstantiationException 实例化失败 + * @deprecated 已过时 */ @Deprecated private static Interceptor[] createInterceptors(String[] interceptors) diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/matcher/ClassMatcher.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/matcher/ClassMatcher.java index efe19eebe3..6cfdeeaec0 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/matcher/ClassMatcher.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/matcher/ClassMatcher.java @@ -234,7 +234,7 @@ public boolean matches(TypeDescription typeDescription) { * 超类检查 * * @param typeDescription 类型描述 - * @param superTypeNames 超类名称集 + * @param superTypeNames 超类名称集 * @return 检查是否通过 */ private static boolean superTypeCheck(TypeDescription typeDescription, Collection superTypeNames) { @@ -245,8 +245,8 @@ private static boolean superTypeCheck(TypeDescription typeDescription, Collectio final Queue queue = new LinkedList(); queue.add(typeDescription); for (TypeDefinition current = queue.poll(); - current != null && !superTypeNameSet.isEmpty(); - current = queue.poll()) { + current != null && !superTypeNameSet.isEmpty(); + current = queue.poll()) { superTypeNameSet.remove(current.getActualName()); final TypeList.Generic interfaces = current.getInterfaces(); if (!interfaces.isEmpty()) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/AbstractTransformer.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/AbstractTransformer.java index 73424324e6..d3232116e1 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/AbstractTransformer.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/AbstractTransformer.java @@ -161,6 +161,7 @@ private List getInterceptors(MethodDescription.InDefinedShape metho * @param methodDesc 方法定义 * @param interceptors 拦截器列表 * @param templateCls 增强模板类 + * @param classLoader 类加载器 * @return 构建器 * @throws InvocationTargetException 调用方法错误 * @throws IllegalAccessException 无法访问属性或方法,正常不会报出 diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/ReentrantTransformer.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/ReentrantTransformer.java index 33d5a7175c..87ecd33f15 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/ReentrantTransformer.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/agent/transformer/ReentrantTransformer.java @@ -61,9 +61,9 @@ protected Builder resolve(Builder builder, InDefinedShape methodDesc, List throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException { final String adviceKey = getAdviceKey(templateCls, classLoader, methodDesc); List interceptorsForAdviceKey = BaseAdviseHandler.getInterceptorListMap() - .computeIfAbsent(adviceKey, k -> new ArrayList<>()); + .computeIfAbsent(adviceKey, key -> new ArrayList<>()); Set createdInterceptorForAdviceKey = plugin.getInterceptors() - .computeIfAbsent(adviceKey, k -> new HashSet<>()); + .computeIfAbsent(adviceKey, key -> new HashSet<>()); for (Interceptor interceptor : interceptors) { // 需要先校验该Interceptor是否被创建过 if (checkInterceptor(adviceKey, interceptor.getClass().getCanonicalName())) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassFinder.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassFinder.java index e44159131d..93bb543a70 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassFinder.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassFinder.java @@ -16,12 +16,15 @@ package com.huaweicloud.sermant.core.plugin.classloader; +import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.plugin.Plugin; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; /** * 用于适配从多个PluginClassLoader中寻找对应类和资源 @@ -30,6 +33,11 @@ * @since 2023-05-30 */ public class PluginClassFinder { + /** + * 日志 + */ + private static final Logger LOGGER = LoggerFactory.getLogger(); + private final Map pluginClassLoaderMap = new HashMap<>(); /** @@ -64,8 +72,8 @@ public Class loadSermantClass(String name) throws ClassNotFoundException { if (clazz != null) { return clazz; } - } catch (ClassNotFoundException ignore) { - // ignore + } catch (ClassNotFoundException e) { + LOGGER.log(Level.WARNING, "load sermant class failed, msg is {0}", e.getMessage()); } } throw new ClassNotFoundException("Can not load class in pluginClassLoaders: " + name); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassLoader.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassLoader.java index 0b6359e192..926941a8bd 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassLoader.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/classloader/PluginClassLoader.java @@ -16,6 +16,7 @@ package com.huaweicloud.sermant.core.plugin.classloader; +import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.config.ConfigManager; import com.huaweicloud.sermant.core.plugin.agent.config.AgentConfig; @@ -23,6 +24,8 @@ import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; /** * 加载插件主模块的类加载器 @@ -31,6 +34,11 @@ * @since 2023-04-27 */ public class PluginClassLoader extends URLClassLoader { + /** + * 日志 + */ + private static final Logger LOGGER = LoggerFactory.getLogger(); + private final HashMap localLoader = new HashMap<>(); /** @@ -94,9 +102,10 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce if (clazz == null) { try { clazz = super.loadClass(name, resolve); - } catch (ClassNotFoundException ignored) { + } catch (ClassNotFoundException e) { // 捕获类找不到的异常,下一步会进入localLoader中去加载类 // ignored + LOGGER.log(Level.WARNING, "load class failed, msg is {0}", e.getMessage()); } } @@ -114,6 +123,7 @@ public Class loadClass(String name, boolean resolve) throws ClassNotFoundExce clazz = loader.loadClass(name); } catch (ClassNotFoundException e) { // 无法找到类,忽略,后续抛出异常 + LOGGER.log(Level.WARNING, "load class failed, msg is {0}", e.getMessage()); } } } @@ -145,8 +155,9 @@ public Class loadSermantClass(String name) throws ClassNotFoundException { if (clazz == null) { try { clazz = super.loadClass(name, false); - } catch (ClassNotFoundException ignored) { + } catch (ClassNotFoundException e) { // 无法找到类,忽略,后续抛出异常 + LOGGER.log(Level.WARNING, "load sermant class failed, msg is {0}", e.getMessage()); } } @@ -175,4 +186,4 @@ public void setLocalLoader(ClassLoader loader) { public ClassLoader removeTmpLoader() { return localLoader.remove(Thread.currentThread().getId()); } -} +} \ No newline at end of file diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigDataHolder.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigDataHolder.java index f89a113c61..6ce6b3ca9d 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigDataHolder.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/ConfigDataHolder.java @@ -58,6 +58,16 @@ public int compareTo(ConfigDataHolder target) { return Integer.compare(target.order, this.order); } + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + public String getGroup() { return group; } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/OrderConfigEvent.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/OrderConfigEvent.java index 1a5da2e3df..33130c04a2 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/OrderConfigEvent.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/plugin/subscribe/processor/OrderConfigEvent.java @@ -36,14 +36,14 @@ public class OrderConfigEvent extends DynamicConfigEvent { /** * 构造器 * - * @param key 配置键 - * @param group 组 - * @param content 配置内容 + * @param key 配置键 + * @param group 组 + * @param content 配置内容 * @param eventType 事件类型 - * @param allData 所有数据 + * @param allData 所有数据 */ public OrderConfigEvent(String key, String group, String content, DynamicConfigEventType eventType, Map allData) { + Object> allData) { super(key, group, content, eventType); this.allData = allData; } @@ -56,4 +56,19 @@ public OrderConfigEvent(String key, String group, String content, DynamicConfigE public Map getAllData() { return this.allData; } + + @Override + public String toString() { + return super.toString(); + } + + @Override + public boolean equals(Object target) { + return super.equals(target); + } + + @Override + public int hashCode() { + return super.hashCode(); + } } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/BaseService.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/BaseService.java index 9a4b2f329f..e2142f354a 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/BaseService.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/BaseService.java @@ -1,41 +1,37 @@ /* - * Copyright (C) 2021-2021 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (C) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * */ package com.huaweicloud.sermant.core.service; -import com.huaweicloud.sermant.core.utils.SpiLoadUtils; - /** * Agent服务接口 *

- * 实现{@link BaseService}的服务实例会在agent启动时被创建, - * 并在创建完成之后,依次调用的它们的{@link #start()}方法, + * 实现{@link BaseService}的服务实例会在agent启动时被创建, 并在创建完成之后,依次调用的它们的{@link #start()}方法, * 同时为他们创建钩子,用于在JVM结束时调用服务是{@link #stop()}方法 *

* 所有{@link BaseService}实例将由{@link ServiceManager}管理, * 可通过{@link ServiceManager#getService(Class)}方法传入{@link BaseService}子类获取服务实例。 - * {@link ServiceManager}将根据传入的{@link BaseService}类型,返回最佳的实现类。 - * 可以通过{@link SpiLoadUtils.SpiWeight}注解设置多实现类的权重。 + * {@link ServiceManager}将根据传入的{@link BaseService}类型,返回最佳的实现类。 可以通过SpiLoadUtils.SpiWeight注解设置多实现类的权重。 * * @author justforstudy-A, beetle-man, HapThorin * @version 1.0.0 * @since 2022-01-21 */ public interface BaseService { - /** * 服务启动方法 */ diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/ServiceManager.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/ServiceManager.java index b589d28200..de41b7b6a0 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/ServiceManager.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/ServiceManager.java @@ -181,11 +181,11 @@ protected static void stopService(String serviceName) { private static void addStopHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { offerEvent(); - for (String serviceName : SERVICES.keySet()) { + for (Map.Entry entry : SERVICES.entrySet()) { try { - SERVICES.get(serviceName).stop(); + entry.getValue().stop(); } catch (Exception ex) { - LOGGER.log(Level.SEVERE, "Error occurs while stopping service: " + serviceName, ex); + LOGGER.log(Level.SEVERE, "Error occurs while stopping service: " + entry.getKey(), ex); } } })); diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/dynamicconfig/common/DynamicConfigServiceType.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/dynamicconfig/common/DynamicConfigServiceType.java index f7b0bf091e..8430da64af 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/dynamicconfig/common/DynamicConfigServiceType.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/dynamicconfig/common/DynamicConfigServiceType.java @@ -16,16 +16,13 @@ package com.huaweicloud.sermant.core.service.dynamicconfig.common; - /** + * Enum for DynamicConfigType, Currently support ZooKeeper, Kie, Nop. Probably will support Nacos, etcd in the future. * - * Enum for DynamicConfigType, - * Currently support ZooKeeper, Kie, Nop. - * Probably will support Nacos, etcd in the future. - * + * @author yangyshdan, HapThorin + * @since 2021-12-27 */ public enum DynamicConfigServiceType { - /** * zookeeper 配置中心 */ @@ -40,9 +37,9 @@ public enum DynamicConfigServiceType { * Nacos 配置中心 */ NACOS, + /** * 配置中心无实现 */ NOP; - } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/heartbeat/common/HeartbeatMessage.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/heartbeat/common/HeartbeatMessage.java index e63354395f..6fbe20071e 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/heartbeat/common/HeartbeatMessage.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/heartbeat/common/HeartbeatMessage.java @@ -52,7 +52,7 @@ public class HeartbeatMessage { * 构造函数 */ public HeartbeatMessage() { - this.hostName = NetworkUtils.getHostName(); + this.hostName = NetworkUtils.getHostName().orElse(null); this.ip = NetworkUtils.getAllNetworkIp(); this.service = BootArgsIndexer.getServiceName(); this.appType = BootArgsIndexer.getAppType(); @@ -68,7 +68,7 @@ public HeartbeatMessage() { public void updateHeartbeatVersion() { this.lastHeartbeatTime = this.heartbeatTime; this.heartbeatTime = System.currentTimeMillis(); - this.hostName = NetworkUtils.getHostName(); + this.hostName = NetworkUtils.getHostName().orElse(null); this.ip = NetworkUtils.getAllNetworkIp(); } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/tracing/common/TracingRequest.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/tracing/common/TracingRequest.java index ce1ac6ea13..9e30484d5b 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/tracing/common/TracingRequest.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/service/tracing/common/TracingRequest.java @@ -46,7 +46,7 @@ public class TracingRequest { /** * 构造函数 * - * @param traceId traceId + * @param traceId traceId * @param parentSpanId parentSpanId * @param spanIdPrefix spanIdPrefix * @param className className diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ClassLoaderUtils.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ClassLoaderUtils.java index d21def284e..3d1ffb6969 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ClassLoaderUtils.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ClassLoaderUtils.java @@ -23,7 +23,10 @@ import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.Enumeration; +import java.util.Optional; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -54,17 +57,23 @@ private ClassLoaderUtils() { *

若类加载不是{@link URLClassLoader},则调用{@link #loadJarFile(ClassLoader, JarFile)}方法加载 * * @param classLoader 类加载器 - * @param jarUrl jar包URL - * @throws NoSuchMethodException 无法找到addURL方法或defineClass方法,正常不会报出 + * @param jarUrl jar包URL + * @throws NoSuchMethodException 无法找到addURL方法或defineClass方法,正常不会报出 * @throws InvocationTargetException 调用addURL方法或defineClass方法错误 - * @throws IllegalAccessException 无法访问addURL方法或defineClass方法,正常不会报出 - * @throws IOException 从jar包中加载class文件失败 + * @throws IllegalAccessException 无法访问addURL方法或defineClass方法,正常不会报出 + * @throws IOException 从jar包中加载class文件失败 */ public static void loadJarFile(ClassLoader classLoader, URL jarUrl) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException { if (classLoader instanceof URLClassLoader) { Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - addUrl.setAccessible(true); + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + addUrl.setAccessible(true); + return Optional.empty(); + } + }); addUrl.invoke(classLoader, jarUrl); } else { JarFile jarFile = null; @@ -84,11 +93,11 @@ public static void loadJarFile(ClassLoader classLoader, URL jarUrl) *

注意,该方法不会加载任何resource,无法通过{@link ClassLoader#getResource(String)}获取本方法加载的内容 * * @param classLoader 类加载器 - * @param jarFile jar包 - * @throws IOException 从jar包中加载class文件失败 + * @param jarFile jar包 + * @throws IOException 从jar包中加载class文件失败 * @throws InvocationTargetException 调用defineClass方法错误 - * @throws IllegalAccessException 无法访问defineClass方法,正常不会报出 - * @throws NoSuchMethodException 无法找到defineClass方法,正常不会报出 + * @throws IllegalAccessException 无法访问defineClass方法,正常不会报出 + * @throws NoSuchMethodException 无法找到defineClass方法,正常不会报出 */ public static void loadJarFile(ClassLoader classLoader, JarFile jarFile) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { @@ -149,7 +158,7 @@ private static byte[] readBytes(InputStream inputStream) throws IOException { * 从类加载器中获取类的字节码 * * @param classLoader 类加载器 - * @param clsName 类全限定名 + * @param clsName 类全限定名 * @return 类的字节码 * @throws IOException 读取类失败 */ @@ -168,24 +177,35 @@ public static byte[] getClassResource(ClassLoader classLoader, String clsName) t /** * 定义类到类加载器中 * - * @param className 定义类的全限定名 + * @param className 定义类的全限定名 * @param classLoader 类加载器 - * @param bytes 类字节码 + * @param bytes 类字节码 * @return 类对象 * @throws InvocationTargetException 调用defineClass方法错误 - * @throws IllegalAccessException 无法访问defineClass方法,正常不会报出 - * @throws NoSuchMethodException 无法找到defineClass方法,正常不会报出 + * @throws IllegalAccessException 无法访问defineClass方法,正常不会报出 + * @throws NoSuchMethodException 无法找到defineClass方法,正常不会报出 */ public static Class defineClass(String className, ClassLoader classLoader, byte[] bytes) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { final Method loadingLock = ClassLoader.class.getDeclaredMethod("getClassLoadingLock", String.class); - loadingLock.setAccessible(true); + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + loadingLock.setAccessible(true); + return Optional.empty(); + } + }); synchronized (loadingLock.invoke(classLoader, className)) { final Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); - defineClass.setAccessible(true); + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + defineClass.setAccessible(true); + return Optional.empty(); + } + }); return (Class) defineClass.invoke(classLoader, null, bytes, 0, bytes.length); } - } } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/LabelGroupUtils.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/LabelGroupUtils.java index 1d92d991ad..ba919ea593 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/LabelGroupUtils.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/LabelGroupUtils.java @@ -27,6 +27,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -84,7 +85,7 @@ public static String createLabelGroup(Map labels) { String value = labels.get(key); if (key == null || value == null) { LOGGER.warning(String.format(Locale.ENGLISH, "Invalid group label, key = %s, value = %s", - key, value)); + key, value)); continue; } group.append(key).append(KV_SEPARATOR).append(value).append(GROUP_SEPARATOR); @@ -148,8 +149,8 @@ public static Map resolveGroupLabels(String group) { LOGGER.warning(String.format(Locale.ENGLISH, "Invalid label [%s]", label)); } } - } catch (UnsupportedEncodingException ignored) { - // ignored + } catch (UnsupportedEncodingException e) { + LOGGER.log(Level.WARNING, "UnsupportedEncodingException, msg is {0}.", e.getMessage()); } return result; } @@ -169,8 +170,8 @@ public static String getLabelCondition(String group) { final StringBuilder finalGroup = new StringBuilder(); for (Map.Entry entry : labels.entrySet()) { finalGroup.append(LABEL_PREFIX) - .append(buildSingleLabel(entry.getKey(), entry.getValue())) - .append(GROUP_SEPARATOR); + .append(buildSingleLabel(entry.getKey(), entry.getValue())) + .append(GROUP_SEPARATOR); } return finalGroup.deleteCharAt(finalGroup.length() - 1).toString(); } @@ -178,9 +179,9 @@ public static String getLabelCondition(String group) { private static String buildSingleLabel(String key, String value) { try { return URLEncoder.encode(key + LABEL_QUERY_SEPARATOR + value, "UTF-8"); - } catch (UnsupportedEncodingException ignored) { - // ignored + } catch (UnsupportedEncodingException e) { + LOGGER.log(Level.WARNING, "UnsupportedEncodingException, msg is {0}.", e.getMessage()); + return StringUtils.EMPTY; } - return StringUtils.EMPTY; } } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/NetworkUtils.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/NetworkUtils.java index 08f3ac75ab..a31ca10ffc 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/NetworkUtils.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/NetworkUtils.java @@ -17,6 +17,7 @@ package com.huaweicloud.sermant.core.utils; import com.huaweicloud.sermant.core.common.LoggerFactory; +import com.huaweicloud.sermant.core.exception.NetInterfacesCheckException; import java.net.InetAddress; import java.net.NetworkInterface; @@ -25,6 +26,7 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.List; +import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; @@ -59,7 +61,7 @@ public static List getAllNetworkIp() { try { Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); if (netInterfaces == null) { - throw new RuntimeException("netInterfaces is null"); + throw new NetInterfacesCheckException("netInterfaces is null"); } InetAddress ip; while (netInterfaces.hasMoreElements()) { @@ -90,13 +92,13 @@ public static List getAllNetworkIp() { * * @return String */ - public static String getHostName() { + public static Optional getHostName() { InetAddress ia; try { ia = InetAddress.getLocalHost(); - return ia.getHostName(); + return Optional.ofNullable(ia.getHostName()); } catch (UnknownHostException e) { - return null; + return Optional.empty(); } } diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ReflectUtils.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ReflectUtils.java index d639eed239..2a6cb215eb 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ReflectUtils.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ReflectUtils.java @@ -194,7 +194,7 @@ public static Optional findMethod(Class clazz, String methodName, Cla if (method != null) { return Optional.of(method); } - method = setAccessible(clazz.getDeclaredMethod(methodName, paramsType)); + method = setObjectAccessible(clazz.getDeclaredMethod(methodName, paramsType)); METHOD_CACHE.put(methodKey, method); return Optional.of(method); } catch (NoSuchMethodException ex) { @@ -271,7 +271,7 @@ public static Optional> findConstructor(Class clazz, Class[ // 增加构造方法缓存 return CONSTRUCTOR_CACHE.computeIfAbsent(buildMethodKey(clazz, "", paramsTypes), key -> { try { - return Optional.of(setAccessible(clazz.getDeclaredConstructor(paramsTypes))); + return Optional.of(setObjectAccessible(clazz.getDeclaredConstructor(paramsTypes))); } catch (NoSuchMethodException e) { LOGGER.warning(String.format(Locale.ENGLISH, "Can not find constructor for class [%s] with params [%s]", clazz.getName(), Arrays.toString(paramsTypes))); @@ -314,7 +314,7 @@ public static boolean setFieldValue(Object target, String fieldName, Object valu return true; } catch (IllegalAccessException ex) { LOGGER.warning(String.format(Locale.ENGLISH, "Set value for field [%s] failed! %s", fieldName, - ex.getMessage())); + ex.getMessage())); return false; } } @@ -422,7 +422,7 @@ private static Field getField(Class clazz, String fieldName) { Field field = cache.get(fieldName); try { if (field == null) { - field = setAccessible(clazz.getDeclaredField(fieldName)); + field = setObjectAccessible(clazz.getDeclaredField(fieldName)); cache.putIfAbsent(fieldName, field); } } catch (IllegalArgumentException | NoSuchFieldException ex) { @@ -460,7 +460,7 @@ private static Optional getFieldFromCache(Class clazz, String fieldNam return Optional.empty(); } - private static T setAccessible(T object) { + private static T setObjectAccessible(T object) { AccessController.doPrivileged((PrivilegedAction) () -> { object.setAccessible(true); return object; diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/RsaUtil.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/RsaUtil.java index c12c386383..fad41d3e52 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/RsaUtil.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/RsaUtil.java @@ -72,7 +72,7 @@ public static Optional generateKey() { * 加密 * * @param publicKey 公钥 - * @param text 报文 + * @param text 报文 * @return 密文 */ public static Optional encrypt(String publicKey, String text) { @@ -93,7 +93,7 @@ public static Optional encrypt(String publicKey, String text) { * 解密 * * @param privateKey 私钥 - * @param text 报文 + * @param text 报文 * @return 明文 */ public static Optional decrypt(String privateKey, String text) { diff --git a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ThreadFactoryUtils.java b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ThreadFactoryUtils.java index 0915106e53..9ea3896262 100644 --- a/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ThreadFactoryUtils.java +++ b/sermant-agentcore/sermant-agentcore-core/src/main/java/com/huaweicloud/sermant/core/utils/ThreadFactoryUtils.java @@ -16,8 +16,13 @@ package com.huaweicloud.sermant.core.utils; +import com.huaweicloud.sermant.core.common.LoggerFactory; + +import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; /** * ThreadFactoryUtils @@ -26,6 +31,7 @@ * @since 2022-03-26 */ public class ThreadFactoryUtils implements ThreadFactory { + private static final Logger LOGGER = LoggerFactory.getLogger(); private static final AtomicInteger FACTORY_NUMBER = new AtomicInteger(0); @@ -70,6 +76,13 @@ private String prefix(String threadName, int factoryId) { public Thread newThread(Runnable job) { String newThreadName = createThreadName(); Thread thread = new Thread(job, newThreadName); + thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + LOGGER.log(Level.WARNING, "uncaughtException, thread is {0}, msg is {1}", new String[]{t.getName(), + e.getMessage()}); + } + }); if (isDaemon) { thread.setDaemon(true); } diff --git a/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java index 5639f081be..fb5463fdd0 100644 --- a/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java +++ b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/core/plugin/agent/entity/ExecuteContext.java @@ -341,6 +341,7 @@ public void setRawStaticFieldValue(String fieldName, Object value) * * @param fieldName 属性名 * @param value 属性值 + * @deprecated 已经过时 */ @Deprecated public void setExtStaticFieldValue(String fieldName, Object value) { @@ -355,6 +356,7 @@ public void setExtStaticFieldValue(String fieldName, Object value) { * * @param fieldName 属性名 * @return 属性值 + * @deprecated 已经过时 */ @Deprecated public Object getExtStaticFieldValue(String fieldName) { @@ -366,6 +368,7 @@ public Object getExtStaticFieldValue(String fieldName) { * * @param fieldName 属性名 * @param value 属性值 + * @deprecated 已经过时 */ @Deprecated public void setExtMemberFieldValue(String fieldName, Object value) { @@ -380,6 +383,7 @@ public void setExtMemberFieldValue(String fieldName, Object value) { * * @param fieldName 属性名 * @return 属性值 + * @deprecated 已经过时 */ @Deprecated public Object getExtMemberFieldValue(String fieldName) { diff --git a/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/RemoveSermantException.java b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/RemoveSermantException.java new file mode 100644 index 0000000000..4bd77b611f --- /dev/null +++ b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/RemoveSermantException.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2023 Huawei Technologies Co., Ltd. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.huaweicloud.sermant.god.common; + +/** + * 移除sermant异常 + * + * @author tangle + * @since 2023-11-03 + */ +public class RemoveSermantException extends RuntimeException { + private static final long serialVersionUID = -3051156765163094177L; + + /** + * 移除sermant异常 + * + * @param cause 抛出对象 + */ + public RemoveSermantException(Throwable cause) { + super(cause); + } +} diff --git a/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/SermantManager.java b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/SermantManager.java index 972b744c77..086ff46a40 100644 --- a/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/SermantManager.java +++ b/sermant-agentcore/sermant-agentcore-god/src/main/java/com/huaweicloud/sermant/god/common/SermantManager.java @@ -18,6 +18,8 @@ import java.io.IOException; import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -46,7 +48,13 @@ public static SermantClassLoader createSermant(String artifact, URL[] urls) { if (hasSermant(artifact)) { return SERMANT_MANAGE_MAP.get(artifact); } - SermantClassLoader sermantClassLoader = new SermantClassLoader(urls); + SermantClassLoader sermantClassLoader = + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public SermantClassLoader run() { + return new SermantClassLoader(urls); + } + }); SERMANT_MANAGE_MAP.put(artifact, sermantClassLoader); return sermantClassLoader; } @@ -65,14 +73,14 @@ public static SermantClassLoader getSermant(String artifact) { * 移除Sermant * * @param artifact 需要移除的Sermant的命名空间 - * @throws RuntimeException RuntimeException + * @throws RemoveSermantException RemoveSermantException */ public static void removeSermant(String artifact) { SermantClassLoader sermantClassLoader = SERMANT_MANAGE_MAP.get(artifact); try { sermantClassLoader.close(); } catch (IOException e) { - throw new RuntimeException(e); + throw new RemoveSermantException(e); } SERMANT_MANAGE_MAP.remove(artifact); } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadPropertiesStrategy.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadPropertiesStrategy.java index d33e0cc20b..275af65913 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadPropertiesStrategy.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadPropertiesStrategy.java @@ -19,8 +19,6 @@ import com.huaweicloud.sermant.core.common.CommonConstant; import com.huaweicloud.sermant.core.common.LoggerFactory; import com.huaweicloud.sermant.core.config.common.BaseConfig; -import com.huaweicloud.sermant.core.config.common.ConfigFieldKey; -import com.huaweicloud.sermant.core.config.common.ConfigTypeKey; import com.huaweicloud.sermant.core.config.strategy.LoadConfigStrategy; import com.huaweicloud.sermant.core.config.utils.ConfigFieldUtil; import com.huaweicloud.sermant.core.config.utils.ConfigKeyUtil; @@ -84,7 +82,7 @@ public boolean canLoad(File file) { *

要求配置文件必须存放在当前jar包的同级目录中 *

最终的配置信息将被{@code argsMap}覆盖,{@code argsMap}拥有最高优先级 * - * @param config 配置文件 + * @param config 配置文件 * @param bootArgsMap 启动时设定的参数 * @return 配置信息承载对象 */ @@ -96,14 +94,14 @@ public Properties getConfigHolder(File config, Map bootArgsMap) /** * 加载配置对象 - *

通过{@link ConfigTypeKey}和{@link ConfigFieldKey}注解定位到properties的配置信息 - *

如果{@link ConfigFieldKey}不存在,则直接使用配置对象的属性名拼接 + *

通过ConfigTypeKey和ConfigFieldKey注解定位到properties的配置信息 + *

如果ConfigFieldKey不存在,则直接使用配置对象的属性名拼接 *

设置配置对象属性值时,优先查找{@code setter}调用,不存在时尝试直接赋值 *

因此,要求配置对象的属性值需要拥有相应的{@code setter},或者要求改属性值是公有的 * * @param holder 配置信息主要承载对象 * @param config 配置对象 - * @param 配置对象泛型 + * @return 配置对象泛型 */ @Override public R loadConfig(Properties holder, R config) { @@ -133,6 +131,7 @@ private R loadConfig(Properties holder, Class cls, R c * 读取配置文件 * * @param config 配置文件对象 + * @return 配置内容 */ private Properties readConfig(File config) { final Properties properties = new Properties(); @@ -159,8 +158,8 @@ private Properties readConfig(File config) { * 获取配置信息内容 * * @param config 配置主要承载对象{@link Properties} - * @param key 配置键 - * @param field 属性 + * @param key 配置键 + * @param field 属性 * @return 配置信息 */ private Object getConfig(Properties config, String key, Field field) { @@ -172,7 +171,7 @@ private Object getConfig(Properties config, String key, Field field) { * 获取配置值,通过{@link ConfigValueUtil#fixValue}方法,修正形如"${}"的配置 * * @param config 配置 - * @param key 配置键 + * @param key 配置键 * @return 配置值 */ private String getConfigStr(Properties config, String key) { @@ -181,7 +180,7 @@ private String getConfigStr(Properties config, String key) { if (arg == null) { configVal = config.getProperty(key); if (configVal == null) { - configVal = readMapOrCollection(configVal, config, key); + configVal = readMapOrCollection(null, config, key); } } else { configVal = arg.toString(); @@ -196,13 +195,11 @@ public String getFixedValue(String key) { } /** - * 匹配Map/List/Set - * (1) 支持xxx.mapName.key1=value1配置Map - * (2) 支持xxx.xxx.listName[0]=elem1配置List或Set + * 匹配Map/List/Set (1) 支持xxx.mapName.key1=value1配置Map (2) 支持xxx.xxx.listName[0]=elem1配置List或Set * * @param configVal 配置值 - * @param config 配置 - * @param key 配置键 + * @param config 配置 + * @param key 配置键 * @return 配置值 */ public String readMapOrCollection(String configVal, Properties config, String key) { @@ -210,12 +207,12 @@ public String readMapOrCollection(String configVal, Properties config, String ke StringBuilder sb = new StringBuilder(); for (String propertyName : config.stringPropertyNames()) { if (propertyName.startsWith(key)) { - // xxx.xxx.listName[0]=elem1 方式匹配List和Set + // 匹配List和Set if (propertyName.matches("(.*)\\[[0-9]*]$")) { sb.append(config.getProperty(propertyName)) .append(CommonConstant.COMMA); } else { - // xxx.mapName.key1=value1 方式匹配Map + // 匹配Map sb.append(propertyName.replace(key + CommonConstant.DOT, "")) .append(CommonConstant.COLON) .append(config.getProperty(propertyName)) @@ -234,7 +231,7 @@ public String readMapOrCollection(String configVal, Properties config, String ke *

支持int、short、long、float、double、枚举、String和Object类型,以及他们构成的数组、List和Map * * @param configStr 配置值 - * @param field 属性字段 + * @param field 属性字段 * @return 转换后的类型 */ private Object transType(String configStr, Field field) { diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadYamlStrategy.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadYamlStrategy.java index 53acfeca75..0ec0eca170 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadYamlStrategy.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/config/LoadYamlStrategy.java @@ -75,6 +75,7 @@ public class LoadYamlStrategy implements LoadConfigStrategy { * Yaml对象 */ private final Yaml yaml; + /** * 启动参数 */ @@ -153,7 +154,8 @@ public R loadConfig(Map holder, R config) { * 修正键,如果属性被{@link ConfigFieldKey}修饰,则将{@link ConfigFieldKey#value()}转化为属性值 * * @param typeMap 类对应的配置信息 - * @param cls 类Class + * @param cls 类Class + * @return 类的字段map */ private Map fixEntry(Map typeMap, Class cls) { if (cls == Object.class || Map.class.isAssignableFrom(cls)) { @@ -197,8 +199,9 @@ private String formatConfigKey(String fieldKey, Class cls) { /** * 修正值中形如"${}"的部分 * - * @param configKey 配置键 - * @param typeMap 父Map + * @param field 类的字段名 + * @param configKey 配置键 + * @param typeMap 父Map * @param subTypeVal 当前值 * @return 修正后的值 */ @@ -231,7 +234,7 @@ public String getFixedValue(String key) { subTypeVal.getClass()); } } catch (ConstructorException exception) { - LOGGER.severe(String.format(Locale.ENGLISH,"Error occurs while parsing configKey: %s", configKey)); + LOGGER.severe(String.format(Locale.ENGLISH, "Error occurs while parsing configKey: %s", configKey)); } return fixedVal; diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/KieDynamicConfigService.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/KieDynamicConfigService.java index 1c34c12dbe..593c88a7f6 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/KieDynamicConfigService.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/KieDynamicConfigService.java @@ -28,7 +28,6 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.Optional; import java.util.logging.Logger; @@ -82,12 +81,13 @@ public boolean doAddConfigListener(String key, String group, DynamicConfigListen @Override public boolean addConfigListener(String key, String group, DynamicConfigListener listener, boolean ifNotify) { + String newGroup = group; if (!LabelGroupUtils.isLabelGroup(group)) { // 增加标签group判断, 对不规则的group进行适配处理 - group = LabelGroupUtils - .createLabelGroup(Collections.singletonMap(fixSeparator(group, true), fixSeparator(key, false))); + newGroup = LabelGroupUtils + .createLabelGroup(Collections.singletonMap(fixSeparator(group, true), fixSeparator(key, false))); } - return subscriberManager.addConfigListener(key, group, listener, ifNotify); + return subscriberManager.addConfigListener(key, newGroup, listener, ifNotify); } @Override @@ -99,7 +99,7 @@ public boolean doRemoveConfigListener(String key, String group) { @Override public Optional doGetConfig(String key, String group) { final KieResponse kieResponse = - subscriberManager.queryConfigurations(null, LabelGroupUtils.getLabelCondition(group)); + subscriberManager.queryConfigurations(null, LabelGroupUtils.getLabelCondition(group)); if (!isValidResponse(kieResponse)) { return Optional.empty(); } @@ -125,7 +125,7 @@ public boolean doRemoveConfig(String key, String group) { @Override public List doListKeysFromGroup(String group) { final KieResponse kieResponse = - subscriberManager.queryConfigurations(null, LabelGroupUtils.getLabelCondition(group)); + subscriberManager.queryConfigurations(null, LabelGroupUtils.getLabelCondition(group)); if (isValidResponse(kieResponse)) { final List data = kieResponse.getData(); final List keys = new ArrayList(data.size()); @@ -142,17 +142,16 @@ private boolean isValidResponse(KieResponse kieResponse) { } /** - * 更新监听器(删除||添加) - * 若第一次添加监听器,则会将数据通知给监听器 + * 更新监听器(删除||添加) 若第一次添加监听器,则会将数据通知给监听器 * - * @param group 分组, 针对KIE特别处理生成group方法{@link LabelGroupUtils#createLabelGroup(Map)} - * @param listener 对应改组的监听器 + * @param group 分组, 针对KIE特别处理生成group方法LabelGroupUtils#createLabelGroup(Map) + * @param listener 对应改组的监听器 * @param forSubscribe 是否为订阅 - * @param ifNotify 初次添加监听器,是否通知监听的数据 + * @param ifNotify 初次添加监听器,是否通知监听的数据 * @return 更新是否成功 */ private synchronized boolean updateGroupListener(String group, DynamicConfigListener listener, boolean forSubscribe, - boolean ifNotify) { + boolean ifNotify) { if (listener == null) { LOGGER.warning("Empty listener is not allowed. "); return false; @@ -172,19 +171,20 @@ private synchronized boolean updateGroupListener(String group, DynamicConfigList /** * 去除路径分隔符 * - * @param str key or group + * @param str key or group * @param isGroup 是否为组 * @return 修正值 */ private String fixSeparator(String str, boolean isGroup) { + String newStr = str; if (str == null) { if (isGroup) { // 默认分组 - str = CONFIG.getDefaultGroup(); + newStr = CONFIG.getDefaultGroup(); } else { throw new IllegalArgumentException("Key must not be empty!"); } } - return str.startsWith("/") ? str.substring(1) : str; + return newStr.startsWith("/") ? newStr.substring(1) : newStr; } } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/AbstractClient.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/AbstractClient.java index 941c7f28c2..1396741643 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/AbstractClient.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/AbstractClient.java @@ -31,8 +31,14 @@ public abstract class AbstractClient implements Client { */ private static final int DEFAULT_TIMEOUT_MS = 60000; + /** + * 客户端请求地址管理器 + */ protected final ClientUrlManager clientUrlManager; + /** + * http请求客户端 + */ protected HttpClient httpClient; /** diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/ClientUrlManager.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/ClientUrlManager.java index 906f35d6ce..db4b2e749b 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/ClientUrlManager.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/ClientUrlManager.java @@ -39,6 +39,7 @@ public class ClientUrlManager { private static final String KIE_PROTOCOL_SSL = "https://"; private final UrlSelector urlSelector = new UrlSelector(); + private List urls; /** @@ -60,12 +61,11 @@ public String getUrl() { } /** - * 解析url - * 默认多个url使用逗号隔开 + * 解析url 默认多个url使用逗号隔开 * * @param serverAddress 服务器地址字符串 */ - public void resolveUrls(String serverAddress) { + private void resolveUrls(String serverAddress) { if (serverAddress == null || serverAddress.trim().length() == 0) { return; } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/http/DefaultHttpClient.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/http/DefaultHttpClient.java index 74fe97f92b..540e0e6f74 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/http/DefaultHttpClient.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/http/DefaultHttpClient.java @@ -66,7 +66,7 @@ * @since 2021-11-17 */ public class DefaultHttpClient - implements com.huaweicloud.sermant.implement.service.dynamicconfig.kie.client.http.HttpClient { + implements com.huaweicloud.sermant.implement.service.dynamicconfig.kie.client.http.HttpClient { private static final Logger LOGGER = LoggerFactory.getLogger(); /** @@ -88,10 +88,10 @@ public class DefaultHttpClient */ public DefaultHttpClient(int timeout) { httpClient = HttpClientBuilder.create().setDefaultRequestConfig( - RequestConfig.custom().setConnectTimeout(timeout) - .setSocketTimeout(timeout) - .setConnectionRequestTimeout(timeout) - .build() + RequestConfig.custom().setConnectTimeout(timeout) + .setSocketTimeout(timeout) + .setConnectionRequestTimeout(timeout) + .build() ).setConnectionManager(buildConnectionManager()).build(); } @@ -102,9 +102,9 @@ public DefaultHttpClient(int timeout) { */ public DefaultHttpClient(RequestConfig requestConfig) { this.httpClient = HttpClientBuilder.create() - .setDefaultRequestConfig(requestConfig) - .setConnectionManager(buildConnectionManager()) - .build(); + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(buildConnectionManager()) + .build(); } /** @@ -120,7 +120,7 @@ private PoolingHttpClientConnectionManager buildConnectionManager() { // 如果需配置SSL 在此处注册https Registry connectionSocketFactoryRegistry = builder.build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( - connectionSocketFactoryRegistry); + connectionSocketFactoryRegistry); connectionManager.setMaxTotal(MAX_TOTAL); connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); return connectionManager; @@ -155,8 +155,9 @@ public HttpResult doGet(String url, RequestConfig requestConfig) { /** * get请求 * - * @param url 请求地址 + * @param url 请求地址 * @param headers 请求头 + * @param requestConfig 请求配置 * @return HttpResult */ @Override @@ -178,7 +179,7 @@ public HttpResult doPost(String url, Map params, RequestConfig r @Override public HttpResult doPost(String url, Map params, RequestConfig requestConfig, - Map headers) { + Map headers) { HttpPost httpPost = new HttpPost(url); beforeRequest(httpPost, requestConfig, headers); addParams(httpPost, params); @@ -264,12 +265,20 @@ private void addHeaders(HttpRequestBase base, Map headers) { /** * 添加默认的请求头 + * + * @param base http请求base */ private void addDefaultHeaders(HttpRequestBase base) { base.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8"); base.addHeader(HttpHeaders.USER_AGENT, "sermant/client"); } + /** + * SSL信任策略 + * + * @author zhouss + * @since 2021-11-17 + */ static class SslTrustStrategy implements TrustStrategy { @Override public boolean isTrusted(X509Certificate[] chain, String authType) { diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieClient.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieClient.java index 3e43690819..c959d565c7 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieClient.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieClient.java @@ -41,9 +41,9 @@ public class KieClient extends AbstractClient { */ private static final String ABSENT_REVISION = "0"; - private final ResultHandler defaultHandler = new ResultHandler.DefaultResultHandler(); + private static final String KIE_API_TEMPLATE = "/v1/%s/kie/kv?"; - private final String kieApiTemplate = "/v1/%s/kie/kv?"; + private final ResultHandler defaultHandler = new ResultHandler.DefaultResultHandler(); private String kieApi; @@ -51,7 +51,7 @@ public class KieClient extends AbstractClient { * kei客户端构造器 * * @param clientUrlManager kie url管理器 - * @param timeout 超时时间 + * @param timeout 超时时间 */ public KieClient(ClientUrlManager clientUrlManager, int timeout) { this(clientUrlManager, ConfigManager.getConfig(KieDynamicConfig.class).getProject(), timeout); @@ -61,8 +61,8 @@ public KieClient(ClientUrlManager clientUrlManager, int timeout) { * kei客户端构造器 * * @param clientUrlManager kie url管理器 - * @param project 命名空间 - * @param timeout 超时时间 + * @param project 命名空间 + * @param timeout 超时时间 */ public KieClient(ClientUrlManager clientUrlManager, String project, int timeout) { this(clientUrlManager, null, project, timeout); @@ -72,17 +72,22 @@ public KieClient(ClientUrlManager clientUrlManager, String project, int timeout) * kei客户端构造器 * * @param clientUrlManager kie url管理器 - * @param httpClient 指定请求器 - * @param project 命名空间 - * @param timeout 超时时间 + * @param httpClient 指定请求器 + * @param project 命名空间 + * @param timeout 超时时间 */ public KieClient(ClientUrlManager clientUrlManager, HttpClient httpClient, String project, int timeout) { super(clientUrlManager, httpClient, timeout); - kieApi = String.format(kieApiTemplate, project); + kieApi = String.format(KIE_API_TEMPLATE, project); } + /** + * 设置kieApi为命名空间 + * + * @param project 命名空间 + */ public void setProject(String project) { - this.kieApi = String.format(kieApiTemplate, project); + this.kieApi = String.format(KIE_API_TEMPLATE, project); } /** @@ -98,9 +103,9 @@ public KieResponse queryConfigurations(KieRequest request) { /** * 查询Kie配置 * - * @param request 请求体 + * @param request 请求体 * @param responseHandler http结果处理器 - * @param 转换后的目标类型 + * @param 转换后的目标类型 * @return 响应结果 */ public T queryConfigurations(KieRequest request, ResultHandler responseHandler) { @@ -109,8 +114,8 @@ public T queryConfigurations(KieRequest request, ResultHandler responseHa } final StringBuilder requestUrl = new StringBuilder().append(clientUrlManager.getUrl()).append(kieApi); requestUrl.append(formatNullString(request.getLabelCondition())) - .append("&revision=") - .append(formatNullString(request.getRevision())); + .append("&revision=") + .append(formatNullString(request.getRevision())); if (request.isAccurateMatchLabel()) { requestUrl.append("&match=exact"); } @@ -124,9 +129,10 @@ public T queryConfigurations(KieRequest request, ResultHandler responseHa /** * 发布配置 * - * @param key 请求键 - * @param labels 标签 + * @param key 请求键 + * @param labels 标签 * @param content 配置 + * @param enabled 配置的状态开关 * @return 是否发布成功 */ public boolean publishConfig(String key, Map labels, String content, boolean enabled) { @@ -142,7 +148,7 @@ public boolean publishConfig(String key, Map labels, String cont /** * 更新配置 * - * @param keyId key-id + * @param keyId key-id * @param content 更新内容 * @param enabled 是否开启 * @return 是否更新成功 @@ -157,7 +163,7 @@ public boolean doUpdateConfig(String keyId, String content, boolean enabled) { private String buildKeyIdUrl(String keyId) { return String.format(Locale.ENGLISH, "%s/%s", - clientUrlManager.getUrl() + kieApi.substring(0, kieApi.length() - 1), keyId); + clientUrlManager.getUrl() + kieApi.substring(0, kieApi.length() - 1), keyId); } /** diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieListenerWrapper.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieListenerWrapper.java index 8a999d0748..cb0b2d1643 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieListenerWrapper.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/KieListenerWrapper.java @@ -70,7 +70,7 @@ public KieListenerWrapper(String key, DynamicConfigListener dynamicConfigListene this.group = kieRequest.getLabelCondition(); this.kvDataHolder = kvDataHolder; this.kieRequest = kieRequest; - addKeyListener(key, dynamicConfigListener, ifNotify); + this.addKeyListener(key, dynamicConfigListener, ifNotify); } /** @@ -198,7 +198,7 @@ private void processInit(Map latestData, VersionListener version * @param dynamicConfigListener 监听器 * @param ifNotify 是否初始化通知 */ - public void addKeyListener(String key, DynamicConfigListener dynamicConfigListener, boolean ifNotify) { + public final void addKeyListener(String key, DynamicConfigListener dynamicConfigListener, boolean ifNotify) { VersionListenerWrapper versionListenerWrapper = keyListenerMap.get(key); if (versionListenerWrapper == null) { versionListenerWrapper = new VersionListenerWrapper(); diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/ResultHandler.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/ResultHandler.java index 63ae1d677f..57f8d310b9 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/ResultHandler.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/client/kie/ResultHandler.java @@ -28,6 +28,7 @@ /** * Kie结果处理器 * + * @param handle泛型 * @author zhouss * @since 2021-11-17 */ @@ -42,9 +43,13 @@ public interface ResultHandler { /** * 默认结果处理器 + * + * @author zhouss + * @since 2021-11-17 */ class DefaultResultHandler implements ResultHandler { private final boolean onlyEnabled; + public DefaultResultHandler() { onlyEnabled = true; } @@ -67,6 +72,7 @@ public KieResponse handle(HttpResult result) { // KIE如果响应状态码为304,则表示没有相关键变更 kieResponse.setChanged(false); } + // 过滤掉disabled的kv配置 final List data = kieResponse.getData(); if (data == null) { @@ -77,6 +83,7 @@ public KieResponse handle(HttpResult result) { kieResponse.setTotal(data.size()); return kieResponse; } + /** * 过滤未开启的kv * diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/KvDataHolder.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/KvDataHolder.java index f0f32c26f0..087e811293 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/KvDataHolder.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/KvDataHolder.java @@ -23,8 +23,7 @@ import java.util.Map; /** - * 监听键响应数据 - * 用于对比新旧数据并保留旧数据 + * 监听键响应数据 用于对比新旧数据并保留旧数据 * * @author zhouss * @since 2021-11-18 @@ -180,6 +179,11 @@ public void setAdded(Map added) { this.added = added; } + /** + * 通过操作不为空判断是否有行为变化 + * + * @return boolean + */ public boolean isChanged() { return !added.isEmpty() || !deleted.isEmpty() || !modified.isEmpty(); } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/SubscriberManager.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/SubscriberManager.java index cd3dfad2d7..bb5907a72f 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/SubscriberManager.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/dynamicconfig/kie/listener/SubscriberManager.java @@ -100,7 +100,7 @@ public class SubscriberManager { * map< 监听键, 监听该键的监听器列表 > 一个group,仅有一个KieListenerWrapper */ private final Map listenerMap = - new ConcurrentHashMap<>(); + new ConcurrentHashMap<>(); /** * kie客户端 @@ -116,18 +116,18 @@ public class SubscriberManager { * 订阅执行器 最大支持MAX_THREAD_SIZE个任务 由于是长连接请求,必然会占用线程,因此这里不考虑将任务存在队列中 */ private final ThreadPoolExecutor longRequestExecutor = new ThreadPoolExecutor(THREAD_SIZE, MAX_THREAD_SIZE, 0, - TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryUtils("kie-subscribe-long-task")); + TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryUtils("kie-subscribe-long-task")); /** * 快速返回的请求 */ - private ScheduledExecutorService scheduledExecutorService; + private volatile ScheduledExecutorService scheduledExecutorService; /** * 构造函数 * * @param serverAddress serverAddress - * @param timeout 超时时间 + * @param timeout 超时时间 */ public SubscriberManager(String serverAddress, int timeout) { kieClient = new KieClient(new ClientUrlManager(serverAddress), timeout); @@ -137,8 +137,8 @@ public SubscriberManager(String serverAddress, int timeout) { * SubscriberManager * * @param serverAddress serverAddress - * @param project project - * @param timeout 超时时间 + * @param project project + * @param timeout 超时时间 */ public SubscriberManager(String serverAddress, String project, int timeout) { kieClient = new KieClient(new ClientUrlManager(serverAddress), project, timeout); @@ -147,7 +147,7 @@ public SubscriberManager(String serverAddress, String project, int timeout) { /** * 添加组监听 * - * @param group 标签组 + * @param group 标签组 * @param listener 监听器 * @param ifNotify 是否在第一次添加时,将所有数据查询返回给调用者 * @return 是否添加成功 @@ -155,8 +155,9 @@ public SubscriberManager(String serverAddress, String project, int timeout) { public boolean addGroupListener(String group, DynamicConfigListener listener, boolean ifNotify) { try { return subscribe(KieConstants.DEFAULT_GROUP_KEY, - new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), listener, - ifNotify); + new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), + listener, + ifNotify); } catch (Exception ex) { LOGGER.warning(String.format(Locale.ENGLISH, "Add group listener failed, %s", ex.getMessage())); return false; @@ -166,8 +167,8 @@ public boolean addGroupListener(String group, DynamicConfigListener listener, bo /** * 添加单个key监听器 * - * @param key 键 - * @param group 标签组 + * @param key 键 + * @param group 标签组 * @param listener 监听器 * @param ifNotify 是否在第一次添加时,将所有数据查询返回给调用者 * @return 是否添加成功 @@ -175,8 +176,9 @@ public boolean addGroupListener(String group, DynamicConfigListener listener, bo public boolean addConfigListener(String key, String group, DynamicConfigListener listener, boolean ifNotify) { try { return subscribe(key, - new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), listener, - ifNotify); + new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), + listener, + ifNotify); } catch (Exception ex) { LOGGER.warning(String.format(Locale.ENGLISH, "Add group listener failed, %s", ex.getMessage())); return false; @@ -186,14 +188,15 @@ public boolean addConfigListener(String key, String group, DynamicConfigListener /** * 移除组监听 * - * @param group 标签组 + * @param group 标签组 * @param listener 监听器 * @return 是否添加成功 */ public boolean removeGroupListener(String group, DynamicConfigListener listener) { try { return unSubscribe(KieConstants.DEFAULT_GROUP_KEY, - new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), listener); + new KieRequest().setLabelCondition(LabelGroupUtils.getLabelCondition(group)).setWait(WAIT), + listener); } catch (Exception ex) { LOGGER.warning(String.format(Locale.ENGLISH, "Removed group listener failed, %s", ex.getMessage())); return false; @@ -203,8 +206,8 @@ public boolean removeGroupListener(String group, DynamicConfigListener listener) /** * 发布配置, 若配置已存在则转为更新配置 * - * @param key 配置键 - * @param group 分组 + * @param key 配置键 + * @param group 分组 * @param content 配置内容 * @return 是否发布成功 */ @@ -222,7 +225,7 @@ public boolean publishConfig(String key, String group, String content) { /** * 移除配置 * - * @param key 键名称 + * @param key 键名称 * @param group 分组 * @return 是否删除成功 */ @@ -234,7 +237,7 @@ public boolean removeConfig(String key, String group) { /** * 获取key_id * - * @param key 键 + * @param key 键 * @param group 组 * @return key_id, 若不存在则返回null */ @@ -274,14 +277,14 @@ private boolean isSameKey(KieConfigEntity entity, String targetKey, Map CLIENT_MAP = new HashMap<>(); + /** + * 获取netty客户端工厂单例 + * + * @return netty客户端工厂单例 + */ public static NettyClientFactory getInstance() { return FACTORY; } @@ -74,8 +79,8 @@ public synchronized NettyClient getNettyClient(String serverIp, int serverPort) * 关闭工厂,清空Client示例 */ public static void stop() { - for (String key : CLIENT_MAP.keySet()) { - CLIENT_MAP.get(key).stop(); + for (Map.Entry entry : CLIENT_MAP.entrySet()) { + entry.getValue().stop(); } CLIENT_MAP.clear(); } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/tracing/TracingServiceImpl.java b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/tracing/TracingServiceImpl.java index de52e53297..f033f14d9e 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/tracing/TracingServiceImpl.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/main/java/com/huaweicloud/sermant/implement/service/tracing/TracingServiceImpl.java @@ -85,7 +85,7 @@ public Optional getContext() { @Override public Optional onProviderSpanStart(TracingRequest tracingRequest, ExtractService extractService, - T carrier) { + T carrier) { if (!isTracing) { return Optional.empty(); } @@ -118,7 +118,7 @@ public Optional onNormalSpanStart(TracingRequest tracingRequest) { @Override public Optional onConsumerSpanStart(TracingRequest tracingRequest, InjectService injectService, - T carrier) { + T carrier) { if (!isTracing) { return Optional.empty(); } @@ -187,13 +187,14 @@ public Optional onSpanError(Throwable throwable) { * 通过SpanId来限制采样深度 * * @param tracingRequest 调用链路追踪生命周期时需要传入的参数 + * @return tracingRequest长度是否合法 */ private boolean filterSpanDepth(TracingRequest tracingRequest) { // 检查spanId长度 大于100忽略 String spanIdPrefix = tracingRequest.getSpanIdPrefix(); if (spanIdPrefix != null && spanIdPrefix.length() > MAX_SPAN_EVENT_DEPTH) { LOGGER.info(String.format(Locale.ROOT, "SpanId is too long, discard this span : [%s]", - JSON.toJSONString(tracingRequest, SerializerFeature.WriteMapNullValue))); + JSON.toJSONString(tracingRequest, SerializerFeature.WriteMapNullValue))); return false; } return true; @@ -201,7 +202,7 @@ private boolean filterSpanDepth(TracingRequest tracingRequest) { private void sendSpanEvent(SpanEvent spanEvent) { LOGGER.info(String.format(Locale.ROOT, "Add spanEvent to queue , TraceId : [%s] , SpanId [%s] . ", - spanEvent.getTraceId(), spanEvent.getSpanId())); + spanEvent.getTraceId(), spanEvent.getSpanId())); tracingSender.offerSpanEvent(spanEvent); } } diff --git a/sermant-agentcore/sermant-agentcore-implement/src/test/java/com/huaweicloud/sermant/implement/service/dynamicconfig/nacos/DynamicConfigSubscribeTest.java b/sermant-agentcore/sermant-agentcore-implement/src/test/java/com/huaweicloud/sermant/implement/service/dynamicconfig/nacos/DynamicConfigSubscribeTest.java index 87f47ba37e..1765726910 100644 --- a/sermant-agentcore/sermant-agentcore-implement/src/test/java/com/huaweicloud/sermant/implement/service/dynamicconfig/nacos/DynamicConfigSubscribeTest.java +++ b/sermant-agentcore/sermant-agentcore-implement/src/test/java/com/huaweicloud/sermant/implement/service/dynamicconfig/nacos/DynamicConfigSubscribeTest.java @@ -46,7 +46,7 @@ public void testDynamicConfigSubscribe() throws NoSuchFieldException, IllegalAcc try { // 测试订阅 TestListener testListener = new TestListener(); - dynamicConfigSubscribe = new DynamicConfigSubscribe("testServiceName", testListener, "testPluginName", + dynamicConfigSubscribe = new DynamicConfigSubscribe("testServiceName", testListener, "testSubscribeKey"); Assert.assertTrue(dynamicConfigSubscribe.subscribe()); Thread.sleep(SLEEP_TIME_MILLIS); diff --git a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/AgentLauncher.java b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/AgentLauncher.java index 321ec7913c..e0ca07a21e 100644 --- a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/AgentLauncher.java +++ b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/AgentLauncher.java @@ -21,6 +21,7 @@ import com.huaweicloud.sermant.premain.common.AgentArgsResolver; import com.huaweicloud.sermant.premain.common.BootArgsBuilder; import com.huaweicloud.sermant.premain.common.BootConstant; +import com.huaweicloud.sermant.premain.common.DirectoryCheckException; import com.huaweicloud.sermant.premain.common.PathDeclarer; import com.huaweicloud.sermant.premain.utils.LoggerUtils; import com.huaweicloud.sermant.premain.utils.StringUtils; @@ -159,11 +160,11 @@ private static void executeCommand(String artifact, String command) { private static void appendGodLibToBootStrapClassLoaderSearch(Instrumentation instrumentation) { final File bootstrapDir = new File(PathDeclarer.getGodLibPath(PathDeclarer.getAgentPath())); if (!bootstrapDir.exists() || !bootstrapDir.isDirectory()) { - throw new RuntimeException("God directory is not exist or is not directory."); + throw new DirectoryCheckException("God directory is not exist or is not directory."); } File[] jars = bootstrapDir.listFiles((dir, name) -> name.endsWith(".jar")); if (jars == null || jars.length == 0) { - throw new RuntimeException("God directory is empty"); + throw new DirectoryCheckException("God directory is empty"); } for (File jar : jars) { @@ -179,11 +180,11 @@ private static URL[] getCoreLibUrls(String agentPath) throws IOException { String realPath = StringUtils.isBlank(agentPath) ? PathDeclarer.getAgentPath() : agentPath; final File coreDir = new File(PathDeclarer.getCorePath(realPath)); if (!coreDir.exists() || !coreDir.isDirectory()) { - throw new RuntimeException("Core directory is not exist or is not directory."); + throw new DirectoryCheckException("Core directory is not exist or is not directory."); } final File[] jars = coreDir.listFiles((dir, name) -> name.endsWith(".jar")); if (jars == null || jars.length == 0) { - throw new RuntimeException("Core directory is empty."); + throw new DirectoryCheckException("Core directory is empty."); } List list = new ArrayList<>(); for (File jar : jars) { diff --git a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/common/DirectoryCheckException.java b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/common/DirectoryCheckException.java new file mode 100644 index 0000000000..94726c46b8 --- /dev/null +++ b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/common/DirectoryCheckException.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2023 Huawei Technologies Co., Ltd. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.huaweicloud.sermant.premain.common; + +/** + * 目录检查异常 + * + * @author tangle + * @since 2023-11-03 + */ +public class DirectoryCheckException extends RuntimeException { + private static final long serialVersionUID = 1623401059405718814L; + + /** + * 目录检查异常 + * + * @param message 异常信息 + */ + public DirectoryCheckException(String message) { + super(message); + } +} diff --git a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/utils/LoggerUtils.java b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/utils/LoggerUtils.java index 3313c67a0b..744eda70a0 100644 --- a/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/utils/LoggerUtils.java +++ b/sermant-agentcore/sermant-agentcore-premain/src/main/java/com/huaweicloud/sermant/premain/utils/LoggerUtils.java @@ -29,21 +29,13 @@ * @since 2023-07-20 */ public class LoggerUtils { - private static Logger logger; + private static final Logger LOGGER = initLogger(); private LoggerUtils() { } - /** - * 获取基础日志 - * - * @return Logger - */ - public static Logger getLogger() { - if (logger != null) { - return logger; - } - logger = Logger.getLogger("sermant.agent"); + private static Logger initLogger() { + Logger tmpLogger = Logger.getLogger("sermant.agent"); final ConsoleHandler handler = new ConsoleHandler(); final String lineSeparator = System.getProperty("line.separator"); handler.setFormatter(new Formatter() { @@ -53,8 +45,17 @@ public String format(LogRecord record) { return "[" + time + "] " + "[" + record.getLevel() + "] " + record.getMessage() + lineSeparator; } }); - logger.addHandler(handler); - logger.setUseParentHandlers(false); - return logger; + tmpLogger.addHandler(handler); + tmpLogger.setUseParentHandlers(false); + return tmpLogger; + } + + /** + * 获取基础日志 + * + * @return Logger + */ + public static Logger getLogger() { + return LOGGER; } } diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/conf/BackendConfig.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/conf/BackendConfig.java index 25ae84f8f7..8558eff8a6 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/conf/BackendConfig.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/conf/BackendConfig.java @@ -33,7 +33,6 @@ @Component @Configuration public class BackendConfig { - /** * 数据库类型 */ @@ -110,8 +109,8 @@ public int getEventExpire() { return eventExpire; } - public void setExpire(int expire) { - this.eventExpire = expire; + public void setEventExpire(int eventExpire) { + this.eventExpire = eventExpire; } public int getFieldExpire() { diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/handler/BaseHandler.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/handler/BaseHandler.java index 1153488daf..7623df1ab0 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/handler/BaseHandler.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/common/handler/BaseHandler.java @@ -17,6 +17,7 @@ package com.huaweicloud.sermant.backend.common.handler; import com.huaweicloud.sermant.backend.pojo.Message; +import com.huaweicloud.sermant.backend.pojo.Message.NettyMessage.MessageType; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; @@ -26,8 +27,7 @@ import org.slf4j.LoggerFactory; /** - * handler的基类 - * 不同数据类型选择处理方式,心跳触发等功能 + * handler的基类 不同数据类型选择处理方式,心跳触发等功能 * * @author lilai * @version 0.0.1 @@ -40,13 +40,10 @@ public abstract class BaseHandler extends SimpleChannelInboundHandler webHookClients = eventPushHandler.getWebHookClients(); for (WebHookClient webHookClient : webHookClients) { WebHookConfig config = webHookClient.getConfig(); diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/controller/HeartBeatInfoController.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/controller/HeartBeatInfoController.java index 38f791e58a..8fd463b5f7 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/controller/HeartBeatInfoController.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/controller/HeartBeatInfoController.java @@ -42,6 +42,11 @@ public class HeartBeatInfoController { private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatInfoController.class); + /** + * 返回插件信息 + * + * @return 插件信息 + */ @GetMapping("/getPluginsInfo") public String getPluginsInfo() { return JSONObject.toJSONString(getHeartbeatMessageCache()); diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/memory/MemoryClientImpl.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/memory/MemoryClientImpl.java index d078e52318..7e40857e17 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/memory/MemoryClientImpl.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/memory/MemoryClientImpl.java @@ -47,11 +47,17 @@ @Component public class MemoryClientImpl implements EventDao { private ExpiringMap eventMap; + private ExpiringMap agentInstanceMap; + private ExpiringMap eventTimeKeyMap; + private ExpiringMap> sessionMap; + private ExpiringMap emergency; + private ExpiringMap important; + private ExpiringMap normal; /** @@ -61,7 +67,7 @@ public class MemoryClientImpl implements EventDao { */ public MemoryClientImpl(BackendConfig backendConfig) { this.eventMap = ExpiringMap.builder().expiration( - backendConfig.getEventExpire(), TimeUnit.DAYS) + backendConfig.getEventExpire(), TimeUnit.DAYS) .expirationPolicy(ExpirationPolicy.CREATED).build(); this.agentInstanceMap = ExpiringMap.builder() .expiration(backendConfig.getEventExpire(), TimeUnit.DAYS) @@ -163,7 +169,9 @@ public QueryResultEventInfoEntity getDoNotifyEvent(Event event) { */ public List getQueryEventKey(long startTime, long endTime, String pattern) { List> queryResultByTime = eventTimeKeyMap.entrySet().stream().filter( - s -> s.getValue() >= startTime && s.getValue() <= endTime && s.getKey().matches(pattern)) + ent -> ent.getValue() >= startTime + && ent.getValue() <= endTime + && ent.getKey().matches(pattern)) .collect(Collectors.toList()); return queryResultByTime.stream().sorted(Map.Entry.comparingByValue()) .map(Map.Entry::getKey).collect(Collectors.toList()); diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/redis/EventDaoForRedis.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/redis/EventDaoForRedis.java index 3a024a369c..9b1e3c0c49 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/redis/EventDaoForRedis.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/dao/redis/EventDaoForRedis.java @@ -39,7 +39,6 @@ * @since 2023-03-02 */ public class EventDaoForRedis implements EventDao { - private static final Logger LOGGER = LoggerFactory.getLogger(EventDaoForRedis.class); private EventDao jedis; @@ -93,6 +92,7 @@ public List queryEvent(EventsRequestEntity eventsReq /** * 获取某一页数据 * + * @param sessionId 会话ID * @param page 页码 * @return 查询数据 */ @@ -104,6 +104,7 @@ public List queryEventPage(String sessionId, int pag /** * 获取查询数据类型数量 * + * @param eventsRequestEntity 事件请求体 * @return 查询结果数量 */ @Override diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/entity/event/DingDingMessageType.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/entity/event/DingDingMessageType.java index 50a669237e..9ed1974566 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/entity/event/DingDingMessageType.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/entity/event/DingDingMessageType.java @@ -27,7 +27,7 @@ public enum DingDingMessageType { /** * 文本 */ - Text("text"), + TEXT("text"), /** * 富文本 diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/handler/EventPushHandler.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/handler/EventPushHandler.java index 43a853fc8c..6459fb6333 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/handler/EventPushHandler.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/handler/EventPushHandler.java @@ -60,13 +60,13 @@ public class EventPushHandler { * 构造函数 */ public EventPushHandler() { - init(); + this.init(); } /** * 初始化webhook */ - public void init() { + private void init() { ServiceLoader loader = ServiceLoader.load(WebHookClient.class); for (WebHookClient webHookClient : loader) { webHookClients.add(webHookClient); diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/EventServer.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/EventServer.java index 767182f788..57dfcf5ae1 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/EventServer.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/EventServer.java @@ -17,6 +17,7 @@ package com.huaweicloud.sermant.backend.server; import com.huaweicloud.sermant.backend.common.conf.BackendConfig; +import com.huaweicloud.sermant.backend.dao.DatabaseType; import com.huaweicloud.sermant.backend.dao.EventDao; import com.huaweicloud.sermant.backend.dao.memory.MemoryClientImpl; import com.huaweicloud.sermant.backend.dao.redis.EventDaoForRedis; @@ -32,6 +33,7 @@ import org.springframework.stereotype.Component; import java.util.List; +import java.util.Objects; import javax.annotation.PostConstruct; @@ -43,12 +45,13 @@ */ @Component public class EventServer { - private static final Logger LOGGER = LoggerFactory.getLogger(EventServer.class); + private static EventServer eventServer; @Autowired private BackendConfig backendConfig; + private EventDao daoService; private EventServer() { @@ -60,13 +63,10 @@ private EventServer() { @PostConstruct public void init() { eventServer = this; - switch (backendConfig.getDatabase()) { - case REDIS: - eventServer.daoService = new EventDaoForRedis(backendConfig); - break; - default: - eventServer.daoService = new MemoryClientImpl(backendConfig); - break; + if (Objects.requireNonNull(backendConfig.getDatabase()) == DatabaseType.REDIS) { + eventServer.daoService = new EventDaoForRedis(backendConfig); + } else { + eventServer.daoService = new MemoryClientImpl(backendConfig); } } diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/ServerHandler.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/ServerHandler.java index 98bfc2ea1d..fe1dffc271 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/ServerHandler.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/server/ServerHandler.java @@ -70,12 +70,6 @@ public class ServerHandler extends BaseHandler { @Autowired private EventServer eventServer; - /** - * ServerHandler - */ - public ServerHandler() { - } - /** * 初始化事件推送服务 */ @@ -165,6 +159,8 @@ private void writeInstanceMeta(HeartbeatMessage heartbeatMessage) { /** * 配置服务可见性数据有效时间 + * + * @param instanceId 实例ID */ private void setServiceValidityPeriod(String instanceId) { ServerInfo serverInfo = new ServerInfo(); diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/DbUtils.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/DbUtils.java index f265c10cda..db0fc9fd2c 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/DbUtils.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/DbUtils.java @@ -49,7 +49,6 @@ * @since 2023-03-02 */ public class DbUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(DbUtils.class); private static final int EVENT_LEVEL_INDEX = 3; @@ -175,7 +174,7 @@ public static String getListPattern(List strings) { * @return 过滤结果 */ public static List filterQueryResult(BackendConfig backendConfig, - List queryResultByTime, String pattern) { + List queryResultByTime, String pattern) { List fanList = new ArrayList<>(); if (queryResultByTime.size() <= 0) { return fanList; @@ -206,9 +205,9 @@ public static List filterQueryResult(BackendConfig backendConfig, @Override public List call() throws Exception { List newList = new ArrayList<>(); - for (Tuple a : finalCutList) { - if (a.getElement().matches(pattern)) { - newList.add(a); + for (Tuple tuple : finalCutList) { + if (tuple.getElement().matches(pattern)) { + newList.add(tuple); } } return newList; diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/GzipUtils.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/GzipUtils.java index 5d7a0a459d..e5e9128363 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/GzipUtils.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/util/GzipUtils.java @@ -50,25 +50,17 @@ private GzipUtils() { * @return 压缩完成的数据 */ public static byte[] compress(byte[] data) { - ByteArrayInputStream bais = new ByteArrayInputStream(data); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - // 压缩 - compress(bais, baos); - byte[] output = baos.toByteArray(); - try { + try (ByteArrayInputStream bais = new ByteArrayInputStream(data); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + // 压缩 + compress(bais, baos); + byte[] output = baos.toByteArray(); baos.flush(); + return output; } catch (IOException e) { - LOGGER.error("Exception occurs when compress. Exception info: {}", e); - } finally { - try { - baos.close(); - bais.close(); - } catch (IOException e) { - LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e); - } + LOGGER.error("Exception occurs when compress or close IOStream. Exception info: {}", e.getMessage()); + return new byte[0]; } - return output; } /** @@ -89,14 +81,14 @@ public static void compress(InputStream is, OutputStream os) { gos.finish(); gos.flush(); } catch (IOException e) { - LOGGER.error("Exception occurs when compress. Exception info: {}", e); + LOGGER.error("Exception occurs when compress. Exception info: {}", e.getMessage()); } finally { try { if (gos != null) { gos.close(); } } catch (IOException e) { - LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e); + LOGGER.error("Exception occurs when close IOStream, Exception info: {}", e.getMessage()); } } } @@ -113,20 +105,20 @@ public static byte[] decompress(byte[] data) { // 解压缩 decompress(bais, baos); - data = baos.toByteArray(); + byte[] newData = baos.toByteArray(); try { baos.flush(); } catch (IOException e) { - LOGGER.error("Exception occurs when decompress. Exception info: {}", e); + LOGGER.error("Exception occurs when decompress. Exception info: {}", e.getMessage()); } finally { try { baos.close(); bais.close(); } catch (IOException e) { - LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e); + LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e.getMessage()); } } - return data; + return newData; } /** @@ -145,14 +137,14 @@ public static void decompress(InputStream is, OutputStream os) { os.write(data, 0, count); } } catch (IOException e) { - LOGGER.error("Exception occurs when decompress. Exception info: {}", e); + LOGGER.error("Exception occurs when decompress. Exception info: {}", e.getMessage()); } finally { try { if (gis != null) { gis.close(); } } catch (IOException e) { - LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e); + LOGGER.error("Exception occurs when close IOStream. Exception info: {}", e.getMessage()); } } } diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/dingding/DingDingHookConfig.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/dingding/DingDingHookConfig.java index f3a3e1254c..071f14102c 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/dingding/DingDingHookConfig.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/dingding/DingDingHookConfig.java @@ -26,12 +26,16 @@ * @since 2023-03-02 */ public class DingDingHookConfig extends WebhookConfigImpl { - private static final WebHookConfig CONFIG = new WebhookConfigImpl(); private DingDingHookConfig() { } + /** + * 获取webhook配置单例 + * + * @return webhook配置单例 + */ public static WebHookConfig getInstance() { return CONFIG; } diff --git a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/feishu/FeiShuHookClient.java b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/feishu/FeiShuHookClient.java index 2bd994b472..084419e8ef 100644 --- a/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/feishu/FeiShuHookClient.java +++ b/sermant-backend/src/main/java/com/huaweicloud/sermant/backend/webhook/feishu/FeiShuHookClient.java @@ -48,7 +48,6 @@ * @since 2023-03-02 */ public class FeiShuHookClient implements WebHookClient { - private static final Logger LOGGER = LoggerFactory.getLogger(FeiShuHookClient.class); private final RestTemplate restTemplate = new RestTemplate(); @@ -69,11 +68,10 @@ public FeiShuHookClient() { * webhook推送事件 * * @param events 事件信息 - * @return + * @return 唤醒feishu的webhook结果 */ @Override public boolean doNotify(List events) { - FeiShuEntity feiShuEntity = new FeiShuEntity(); feiShuEntity.setMsgType(FeiShuMessageType.POST.getType()); feiShuEntity.setContent(new HashMap() { @@ -126,7 +124,6 @@ public HashMap getNotifyContent(List content.add(getContent("logLineNumber:" + logInfo.getLogLineNumber())); content.add(getContent("logThreadId" + logInfo.getLogThreadId())); content.add(getContent("throwable:" + logInfo.getLogThrowable())); - } else { EventInfo eventInfo = (EventInfo) event.getInfo(); content.add(getContent("name:" + eventInfo.getName()));