diff --git a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceContext.java b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceContext.java index a87161b7fda6..19bbd74a66a0 100644 --- a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceContext.java +++ b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceContext.java @@ -20,6 +20,7 @@ import com.navercorp.pinpoint.bootstrap.plugin.jdbc.JdbcContext; import com.navercorp.pinpoint.common.annotations.InterfaceAudience; import com.navercorp.pinpoint.common.annotations.InterfaceStability; +import com.navercorp.pinpoint.common.id.AgentId; /** * @author emeroad @@ -73,7 +74,7 @@ public interface TraceContext { // ActiveThreadCounter getActiveThreadCounter(); - String getAgentId(); + AgentId getAgentId(); String getApplicationName(); diff --git a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceId.java b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceId.java index 18eb7b143c12..3fbcfa5566e9 100644 --- a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceId.java +++ b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/context/TraceId.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.bootstrap.context; +import com.navercorp.pinpoint.common.id.AgentId; + /** * @author emeroad */ @@ -27,7 +29,7 @@ public interface TraceId { String getTransactionId(); - String getAgentId(); + AgentId getAgentId(); long getAgentStartTime(); diff --git a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java index c6bc5902fafd..fa757b576abb 100644 --- a/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java +++ b/agent-module/bootstraps/bootstrap-core/src/main/java/com/navercorp/pinpoint/bootstrap/resolver/condition/MainClassCondition.java @@ -23,6 +23,7 @@ import com.navercorp.pinpoint.common.util.SystemPropertyKey; import java.io.IOException; +import java.util.Objects; import java.util.jar.JarFile; /** @@ -49,7 +50,7 @@ public MainClassCondition(SimpleProperty property) { throw new IllegalArgumentException("properties should not be null"); } this.applicationMainClassName = getMainClassName(property); - if (this.applicationMainClassName == NOT_FOUND) { + if (Objects.equals(this.applicationMainClassName, NOT_FOUND)) { logger.info("Main class could not be deduced, please set 'profiler.applicationservertype' in pinpoint.config."); logger.info("If you're running on 1.6.0_24 or prior version of Java, consider upgrading to 1.6.0_25+."); } @@ -84,7 +85,7 @@ public boolean check(String condition) { */ @Override public String getValue() { - if (this.applicationMainClassName == NOT_FOUND) { + if (Objects.equals(this.applicationMainClassName, NOT_FOUND)) { return ""; } return this.applicationMainClassName; diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolver.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolver.java index 4f0635f9549f..1dc4fe682bb3 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolver.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolver.java @@ -16,29 +16,29 @@ package com.navercorp.pinpoint.bootstrap; -import com.navercorp.pinpoint.common.util.AgentUuidUtils; +import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.ServiceId; import com.navercorp.pinpoint.common.util.StringUtils; import java.util.List; import java.util.Objects; -import java.util.UUID; /** * @author Woonduk Kang(emeroad) */ public class AgentIdResolver { public static final String APPLICATION_NAME = "applicationName"; - public static final String AGENT_ID = "agentId"; + public static final String SERVICE_NAME = "serviceName"; public static final String AGENT_NAME = "agentName"; public static final String SYSTEM_PROPERTY_PREFIX = "pinpoint."; public static final String APPLICATION_NAME_SYSTEM_PROPERTY = SYSTEM_PROPERTY_PREFIX + "applicationName"; - public static final String AGENT_ID_SYSTEM_PROPERTY = SYSTEM_PROPERTY_PREFIX + "agentId"; + public static final String SERVICE_NAME_SYSTEM_PROPERTY = SYSTEM_PROPERTY_PREFIX + "serviceName"; public static final String AGENT_NAME_SYSTEM_PROPERTY = SYSTEM_PROPERTY_PREFIX + "agentName"; public static final String ENV_PROPERTY_PREFIX = "PINPOINT_"; public static final String APPLICATION_NAME_ENV_PROPERTY = ENV_PROPERTY_PREFIX + "APPLICATION_NAME"; - public static final String AGENT_ID_ENV_PROPERTY = ENV_PROPERTY_PREFIX + "AGENT_ID"; + public static final String SERVICE_NAME_ENV_PROPERTY = ENV_PROPERTY_PREFIX + "SERVICE_NAME"; public static final String AGENT_NAME_ENV_PROPERTY = ENV_PROPERTY_PREFIX + "AGENT_NAME"; private final BootLogger logger = BootLogger.getLogger(this.getClass()); @@ -46,51 +46,33 @@ public class AgentIdResolver { private final List agentPropertyList; private final IdValidator idValidator = new IdValidator(); + private final IdValidator applicationNameValidator = new IdValidator(PinpointConstants.APPLICATION_NAME_MAX_LEN); + private final IdValidator serviceNameValidator = new IdValidator(PinpointConstants.SERVICE_NAME_MAX_LEN); public AgentIdResolver(List agentPropertyList) { this.agentPropertyList = Objects.requireNonNull(agentPropertyList, "agentPropertyList"); } public AgentIds resolve() { - String agentId = getAgentId(); - if (StringUtils.isEmpty(agentId)) { - logger.info("Failed to resolve AgentId(-Dpinpoint.agentId)"); - agentId = newRandomAgentId(); - logger.info("Auto generate AgentId='" + agentId + "'"); - } - final String applicationName = getApplicationName(); if (StringUtils.isEmpty(applicationName)) { logger.warn("Failed to resolve ApplicationName(-Dpinpoint.applicationName)"); return null; } + String serviceName = getServiceName(); + if (StringUtils.isEmpty(serviceName)) { + logger.info("Failed to resolve ServiceName(-Dpinpoint.serviceName)"); + serviceName = ServiceId.DEFAULT_SERVICE_NAME; + logger.info("Using default serviceName='" + serviceName + "'"); + } + final String agentName = getAgentName(); if (StringUtils.isEmpty(agentName)) { logger.info("No AgentName(-Dpinpoint.agentName) provided, it's optional!"); } - return new AgentIds(agentId, agentName, applicationName); - } - - private String newRandomAgentId() { - UUID agentUUID = UUID.randomUUID(); - return AgentUuidUtils.encode(agentUUID); - } - - private String getAgentId() { - String source = null; - for (AgentProperties agentProperty : agentPropertyList) { - final String agentId = agentProperty.getAgentId(); - if (StringUtils.isEmpty(agentId)) { - continue; - } - if (idValidator.validateAgentId(agentProperty.getType(), agentId)) { - logger.info(agentProperty.getType() + " " + agentProperty.getAgentIdKey() + "=" + agentId); - source = agentId; - } - } - return source; + return new AgentIds(agentName, applicationName, serviceName); } private String getAgentName() { @@ -112,7 +94,7 @@ private String getApplicationName() { if (StringUtils.isEmpty(applicationName)) { continue; } - if (idValidator.validateApplicationName(agentProperty.getType(), applicationName)) { + if (applicationNameValidator.validateApplicationName(agentProperty.getType(), applicationName)) { logger.info(agentProperty.getType() + " " + agentProperty.getApplicationNameKey() + "=" + applicationName); source = applicationName; } @@ -120,4 +102,19 @@ private String getApplicationName() { return source; } + private String getServiceName() { + String source = null; + for (AgentProperties agentProperty : agentPropertyList) { + final String serviceName = agentProperty.getServiceName(); + if (StringUtils.isEmpty(serviceName)) { + continue; + } + if (serviceNameValidator.validateServiceName(agentProperty.getType(), serviceName)) { + logger.info(agentProperty.getType() + " " + agentProperty.getServiceNameKey() + "=" + serviceName); + source = serviceName; + } + } + return source; + } + } diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverBuilder.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverBuilder.java index 7e0cc6c09aab..f09e1a43cccc 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverBuilder.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverBuilder.java @@ -32,9 +32,9 @@ public void addSystemProperties(Properties system) { Objects.requireNonNull(system, "system"); AgentProperties systemProperties = new AgentProperties(AgentIdSourceType.SYSTEM, system, - AgentIdResolver.AGENT_ID_SYSTEM_PROPERTY, AgentIdResolver.AGENT_NAME_SYSTEM_PROPERTY, - AgentIdResolver.APPLICATION_NAME_SYSTEM_PROPERTY); + AgentIdResolver.APPLICATION_NAME_SYSTEM_PROPERTY, + AgentIdResolver.SERVICE_NAME_SYSTEM_PROPERTY); this.agentProperties.add(systemProperties); } @@ -42,9 +42,9 @@ public void addEnvProperties(Map env) { Objects.requireNonNull(env, "env"); AgentProperties envProperties = new AgentProperties(AgentIdSourceType.SYSTEM_ENV, env, - AgentIdResolver.AGENT_ID_ENV_PROPERTY, AgentIdResolver.AGENT_NAME_ENV_PROPERTY, - AgentIdResolver.APPLICATION_NAME_ENV_PROPERTY); + AgentIdResolver.APPLICATION_NAME_ENV_PROPERTY, + AgentIdResolver.SERVICE_NAME_ENV_PROPERTY); this.agentProperties.add(envProperties); } @@ -52,9 +52,9 @@ public void addAgentArgument(Map agentArguments) { Objects.requireNonNull(agentArguments, "agentArguments"); AgentProperties agentArgument = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, agentArguments, - AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, - AgentIdResolver.APPLICATION_NAME); + AgentIdResolver.APPLICATION_NAME, + AgentIdResolver.SERVICE_NAME); this.agentProperties.add(agentArgument); } diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIds.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIds.java index 032dbe46302f..8c860e6d03f4 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIds.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentIds.java @@ -22,19 +22,14 @@ * @author Woonduk Kang(emeroad) */ public class AgentIds { - private final String agentId; private final String agentName; private final String applicationName; + private final String serviceName; - public AgentIds(String agentId, String agentName, String applicationName) { - this.agentId = Objects.requireNonNull(agentId, "agentId"); + public AgentIds(String agentName, String applicationName, String serviceName) { this.agentName = agentName; this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); - } - - - public String getAgentId() { - return agentId; + this.serviceName = Objects.requireNonNull(serviceName, "serviceName"); } public String getAgentName() { @@ -44,4 +39,9 @@ public String getAgentName() { public String getApplicationName() { return applicationName; } + + public String getServiceName() { + return serviceName; + } + } diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentOption.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentOption.java index ed78c955c538..a70280da1903 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentOption.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentOption.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.bootstrap; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import java.lang.instrument.Instrumentation; import java.util.List; @@ -28,12 +29,14 @@ public interface AgentOption { Instrumentation getInstrumentation(); - String getAgentId(); + AgentId getAgentId(); String getAgentName(); String getApplicationName(); + String getServiceName(); + boolean isContainer(); ProfilerConfig getProfilerConfig(); diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentProperties.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentProperties.java index 5ea2fa8ea2d2..51ab1dd33145 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentProperties.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/AgentProperties.java @@ -26,20 +26,20 @@ public class AgentProperties { private final AgentIdSourceType type; private final Properties properties; - private final String agentIdKey; private final String agentNameKey; private final String applicationNameKey; + private final String serviceNameKey; - public AgentProperties(AgentIdSourceType type, Properties properties, String agentIdKey, String agentNameKey, String applicationNameKey) { + public AgentProperties(AgentIdSourceType type, Properties properties, String agentNameKey, String applicationNameKey, String serviceNameKey) { this.type = Objects.requireNonNull(type, "type"); this.properties = Objects.requireNonNull(properties, "properties"); - this.agentIdKey = Objects.requireNonNull(agentIdKey, "agentIdKey"); this.agentNameKey = Objects.requireNonNull(agentNameKey, "agentNameKey"); this.applicationNameKey = Objects.requireNonNull(applicationNameKey, "applicationNameKey"); + this.serviceNameKey = Objects.requireNonNull(serviceNameKey, "serviceNameKey"); } - public AgentProperties(AgentIdSourceType type, Map properties, String agentIdKey, String agentNameKey, String applicationNameKey) { - this(type, toProperties(properties), agentIdKey, agentNameKey, applicationNameKey); + public AgentProperties(AgentIdSourceType type, Map properties, String agentNameKey, String applicationNameKey, String serviceNameKey) { + this(type, toProperties(properties), agentNameKey, applicationNameKey, serviceNameKey); } private static Properties toProperties(Map properties) { @@ -54,18 +54,10 @@ public AgentIdSourceType getType() { return type; } - public String getAgentId() { - return trim(this.properties.getProperty(agentIdKey)); - } - public String getAgentName() { return trim(this.properties.getProperty(agentNameKey)); } - public String getAgentIdKey() { - return agentIdKey; - } - public String getAgentNameKey() { return agentNameKey; } @@ -78,6 +70,14 @@ public String getApplicationNameKey() { return applicationNameKey; } + public String getServiceName() { + return trim(this.properties.getProperty(serviceNameKey)); + } + + public String getServiceNameKey() { + return serviceNameKey; + } + private String trim(String string) { if (string == null) { return null; @@ -87,13 +87,11 @@ private String trim(String string) { @Override public String toString() { - final StringBuilder sb = new StringBuilder("AgentProperties{"); - sb.append("type=").append(type); - sb.append(", properties=").append(properties); - sb.append(", agentIdKey='").append(agentIdKey).append('\''); - sb.append(", agentNameKey='").append(agentNameKey).append('\''); - sb.append(", applicationNameKey='").append(applicationNameKey).append('\''); - sb.append('}'); - return sb.toString(); + return "AgentProperties{" + "type=" + type + + ", properties=" + properties + + ", agentNameKey='" + agentNameKey + '\'' + + ", applicationNameKey='" + applicationNameKey + '\'' + + ", serviceNameKey='" + serviceNameKey + '\'' + + '}'; } } diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/DefaultAgentOption.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/DefaultAgentOption.java index 033cf698adb7..ad63aa26716c 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/DefaultAgentOption.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/DefaultAgentOption.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.bootstrap; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import java.lang.instrument.Instrumentation; import java.util.List; @@ -29,9 +30,10 @@ public class DefaultAgentOption implements AgentOption { private final Instrumentation instrumentation; - private final String agentId; + private final AgentId agentId; private final String agentName; private final String applicationName; + private final String serviceName; private final boolean isContainer; private final ProfilerConfig profilerConfig; @@ -39,12 +41,13 @@ public class DefaultAgentOption implements AgentOption { private final List bootstrapJarPaths; public DefaultAgentOption(final Instrumentation instrumentation, - String agentId, String agentName, String applicationName, final boolean isContainer, + AgentId agentId, String agentName, String applicationName, String serviceName, final boolean isContainer, final ProfilerConfig profilerConfig, final List pluginJars, final List bootstrapJarPaths) { this.instrumentation = Objects.requireNonNull(instrumentation, "instrumentation"); this.agentId = Objects.requireNonNull(agentId, "agentId"); this.agentName = Objects.requireNonNull(agentName, "agentName"); this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); + this.serviceName = Objects.requireNonNull(serviceName, "serviceName"); this.isContainer = isContainer; this.profilerConfig = Objects.requireNonNull(profilerConfig, "profilerConfig"); this.pluginJars = Objects.requireNonNull(pluginJars, "pluginJars"); @@ -57,7 +60,7 @@ public Instrumentation getInstrumentation() { } @Override - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -71,6 +74,11 @@ public String getApplicationName() { return applicationName; } + @Override + public String getServiceName() { + return serviceName; + } + @Override public boolean isContainer() { return isContainer; @@ -93,16 +101,15 @@ public ProfilerConfig getProfilerConfig() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("DefaultAgentOption{"); - sb.append("instrumentation=").append(instrumentation); - sb.append(", agentId='").append(agentId).append('\''); - sb.append(", agentName='").append(agentName).append('\''); - sb.append(", applicationName='").append(applicationName).append('\''); - sb.append(", isContainer=").append(isContainer); - sb.append(", profilerConfig=").append(profilerConfig); - sb.append(", pluginJars=").append(pluginJars); - sb.append(", bootstrapJarPaths=").append(bootstrapJarPaths); - sb.append('}'); - return sb.toString(); + return "DefaultAgentOption{" + "instrumentation=" + instrumentation + + ", agentId='" + agentId + '\'' + + ", agentName='" + agentName + '\'' + + ", applicationName='" + applicationName + '\'' + + ", serviceName='" + serviceName + '\'' + + ", isContainer=" + isContainer + + ", profilerConfig=" + profilerConfig + + ", pluginJars=" + pluginJars + + ", bootstrapJarPaths=" + bootstrapJarPaths + + '}'; } } diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/IdValidator.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/IdValidator.java index db50a2202508..b694d4265aa6 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/IdValidator.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/IdValidator.java @@ -55,6 +55,11 @@ public boolean validateApplicationName(AgentIdSourceType type, String applicatio return validate0(type + " applicationName", applicationName); } + public boolean validateServiceName(AgentIdSourceType type, String serviceName) { + Objects.requireNonNull(serviceName, "serviceName"); + return validate0(type + " serviceName", serviceName); + } + public boolean validateAgentName(AgentIdSourceType type, String agentName) { if (StringUtils.isEmpty(agentName)) { return false; diff --git a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java index 26ff685d4844..b4b0aade0bb5 100644 --- a/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java +++ b/agent-module/bootstraps/bootstrap/src/main/java/com/navercorp/pinpoint/bootstrap/PinpointStarter.java @@ -27,6 +27,7 @@ import com.navercorp.pinpoint.bootstrap.config.PropertyLoaderFactory; import com.navercorp.pinpoint.common.Version; import com.navercorp.pinpoint.common.banner.PinpointBanner; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.OsEnvSimpleProperty; import com.navercorp.pinpoint.common.util.PropertySnapshot; import com.navercorp.pinpoint.common.util.SimpleProperty; @@ -59,7 +60,7 @@ class PinpointStarter { public static final String PLUGIN_TEST_AGENT = "PLUGIN_TEST"; public static final String PLUGIN_TEST_BOOT_CLASS = "com.navercorp.pinpoint.profiler.test.PluginTestAgent"; - private SimpleProperty systemProperty = SystemProperty.INSTANCE; + private final SimpleProperty systemProperty = SystemProperty.INSTANCE; private final Map agentArgs; private final AgentType agentType; @@ -97,16 +98,18 @@ boolean start() { return false; } - final String agentId = agentIds.getAgentId(); - if (agentId == null) { - logger.warn("agentId is null"); - return false; - } + final AgentId agentId = AgentId.random(); + final String applicationName = agentIds.getApplicationName(); if (applicationName == null) { logger.warn("applicationName is null"); return false; } + final String serviceName = agentIds.getServiceName(); + if (serviceName == null) { + logger.warn("serviceName is null"); + return false; + } final ContainerResolver containerResolver = new ContainerResolver(); final boolean isContainer = containerResolver.isContainer(); @@ -121,7 +124,6 @@ boolean start() { } // set the path of log file as a system property - saveAgentIdForLog(agentIds); saveLogFilePath(agentDirectory.getAgentLogFilePath()); savePinpointVersion(); @@ -142,7 +144,7 @@ boolean start() { final List pluginJars = agentDirectory.getPlugins(); final String agentName = agentIds.getAgentName(); - AgentOption option = createAgentOption(agentId, agentName, applicationName, isContainer, + AgentOption option = createAgentOption(agentId, agentName, applicationName, serviceName, isContainer, profilerConfig, instrumentation, pluginJars, @@ -248,14 +250,16 @@ private String getAgentType() { } - private AgentOption createAgentOption(String agentId, String agentName, String applicationName, boolean isContainer, + private AgentOption createAgentOption(AgentId agentId, String agentName, String applicationName, String serviceName, + boolean isContainer, ProfilerConfig profilerConfig, Instrumentation instrumentation, List pluginJars, List bootstrapJarPaths) { List pluginJarStrPath = toPathList(pluginJars); List bootstrapJarPathStrPath = toPathList(bootstrapJarPaths); - return new DefaultAgentOption(instrumentation, agentId, agentName, applicationName, isContainer, profilerConfig, pluginJarStrPath, bootstrapJarPathStrPath); + return new DefaultAgentOption(instrumentation, agentId, agentName, applicationName, serviceName, + isContainer, profilerConfig, pluginJarStrPath, bootstrapJarPathStrPath); } private List toPathList(List paths) { @@ -266,15 +270,6 @@ private List toPathList(List paths) { return list; } - // for test - void setSystemProperty(SimpleProperty systemProperty) { - this.systemProperty = systemProperty; - } - - private void saveAgentIdForLog(AgentIds agentIds) { - systemProperty.setProperty(AgentIdResolver.AGENT_ID_SYSTEM_PROPERTY, agentIds.getAgentId()); - } - private void saveLogFilePath(Path agentLogFilePath) { logger.info("logPath:" + agentLogFilePath); systemProperty.setProperty(ProductInfo.NAME + ".log", agentLogFilePath.toString()); diff --git a/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentBootLoaderTest.java b/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentBootLoaderTest.java index 33256aac0f86..b2dcb84d02fe 100644 --- a/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentBootLoaderTest.java +++ b/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentBootLoaderTest.java @@ -18,6 +18,7 @@ import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.CodeSourceUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -50,7 +51,7 @@ private void boot(String agentName) { ClassLoader classLoader = AgentBootLoaderTest.class.getClassLoader(); AgentBootLoader agentBootLoader = new AgentBootLoader("com.navercorp.pinpoint.bootstrap.DummyAgent", classLoader); Instrumentation instrumentation = mock(Instrumentation.class); - AgentOption option = new DefaultAgentOption(instrumentation, "testCaseAgent", agentName, "testCaseAppName", false, + AgentOption option = new DefaultAgentOption(instrumentation, AgentId.of("testCaseAgent"), agentName, "testCaseAppName", "testCaseServiceName", false, new DefaultProfilerConfig(), Collections.emptyList(), Collections.emptyList()); Agent boot = agentBootLoader.boot(option); boot.start(); diff --git a/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverTest.java b/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverTest.java index 5b35d2d2c9db..693bb37b73e7 100644 --- a/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverTest.java +++ b/agent-module/bootstraps/bootstrap/src/test/java/com/navercorp/pinpoint/bootstrap/AgentIdResolverTest.java @@ -1,95 +1,87 @@ package com.navercorp.pinpoint.bootstrap; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; +import java.util.Collections; import java.util.Properties; +import static org.assertj.core.api.Assertions.assertThat; + public class AgentIdResolverTest { @Test public void resolve() { Properties properties = new Properties(); - properties.setProperty(AgentIdResolver.AGENT_ID, "agentId"); properties.setProperty(AgentIdResolver.AGENT_NAME, "agentName"); properties.setProperty(AgentIdResolver.APPLICATION_NAME, "appName"); - AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); - AgentIdResolver resolver = new AgentIdResolver(Arrays.asList(ap)); + AgentIdResolver resolver = new AgentIdResolver(Collections.singletonList(ap)); AgentIds resolve = resolver.resolve(); - Assertions.assertEquals("agentId", resolve.getAgentId()); - Assertions.assertEquals("agentName", resolve.getAgentName()); - Assertions.assertEquals("appName", resolve.getApplicationName()); + assertThat(resolve.getAgentName()).isEqualTo("agentName"); + assertThat(resolve.getApplicationName()).isEqualTo("appName"); } @Test public void resolve_optional_agent_name() { Properties properties = new Properties(); - properties.setProperty(AgentIdResolver.AGENT_ID, "agentId"); properties.setProperty(AgentIdResolver.APPLICATION_NAME, "appName"); - AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); - AgentIdResolver resolver = new AgentIdResolver(Arrays.asList(ap)); + AgentIdResolver resolver = new AgentIdResolver(Collections.singletonList(ap)); AgentIds resolve = resolver.resolve(); - Assertions.assertEquals("agentId", resolve.getAgentId()); - Assertions.assertEquals("appName", resolve.getApplicationName()); - Assertions.assertEquals("", resolve.getAgentName()); + assertThat(resolve.getApplicationName()).isEqualTo("appName"); + assertThat(resolve.getAgentName()).isEmpty(); } @Test public void resolve_fail() { Properties properties = new Properties(); - properties.setProperty(AgentIdResolver.AGENT_ID, "agentId"); - AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); - AgentIdResolver resolver = new AgentIdResolver(Arrays.asList(ap)); + AgentIdResolver resolver = new AgentIdResolver(Collections.singletonList(ap)); AgentIds resolve = resolver.resolve(); - Assertions.assertNull(resolve); + assertThat(resolve).isNull(); } @Test public void resolve_multi_source() { Properties properties1 = new Properties(); - properties1.setProperty(AgentIdResolver.AGENT_ID, "agentId1"); properties1.setProperty(AgentIdResolver.AGENT_NAME, "agentName1"); - AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties1, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties1, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); Properties properties2 = new Properties(); properties2.setProperty(AgentIdResolver.APPLICATION_NAME, "appName2"); - AgentProperties ap2 = new AgentProperties(AgentIdSourceType.SYSTEM, properties2, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap2 = new AgentProperties(AgentIdSourceType.SYSTEM, properties2, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); AgentIdResolver resolver = new AgentIdResolver(Arrays.asList(ap, ap2)); AgentIds resolve = resolver.resolve(); - Assertions.assertEquals("agentId1", resolve.getAgentId()); - Assertions.assertEquals("appName2", resolve.getApplicationName()); - Assertions.assertEquals("agentName1", resolve.getAgentName()); + assertThat(resolve.getApplicationName()).isEqualTo("appName2"); + assertThat(resolve.getAgentName()).isEqualTo("agentName1"); } @Test public void resolve_multi_source_2() { Properties properties1 = new Properties(); - properties1.setProperty(AgentIdResolver.AGENT_ID, "agentId1"); properties1.setProperty(AgentIdResolver.AGENT_NAME, "agentName1"); - AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties1, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap = new AgentProperties(AgentIdSourceType.AGENT_ARGUMENT, properties1, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); Properties properties2 = new Properties(); - properties2.setProperty(AgentIdResolver.AGENT_ID, "agentId2"); properties2.setProperty(AgentIdResolver.AGENT_NAME, "agentName2"); properties2.setProperty(AgentIdResolver.APPLICATION_NAME, "appName2"); - AgentProperties ap2 = new AgentProperties(AgentIdSourceType.SYSTEM, properties2, AgentIdResolver.AGENT_ID, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME); + AgentProperties ap2 = new AgentProperties(AgentIdSourceType.SYSTEM, properties2, AgentIdResolver.AGENT_NAME, AgentIdResolver.APPLICATION_NAME, AgentIdResolver.SERVICE_NAME); AgentIdResolver resolver = new AgentIdResolver(Arrays.asList(ap, ap2)); AgentIds resolve = resolver.resolve(); - Assertions.assertEquals("agentId2", resolve.getAgentId()); - Assertions.assertEquals("appName2", resolve.getApplicationName()); - Assertions.assertEquals("agentName2", resolve.getAgentName()); + assertThat(resolve.getApplicationName()).isEqualTo("appName2"); + assertThat(resolve.getAgentName()).isEqualTo("agentName2"); } } \ No newline at end of file diff --git a/agent-module/plugins/jboss/src/test/java/com/navercorp/pinpoint/plugin/jboss/InvokeMethodInterceptorTest.java b/agent-module/plugins/jboss/src/test/java/com/navercorp/pinpoint/plugin/jboss/InvokeMethodInterceptorTest.java index a85e6f7a2733..064bedbe2586 100644 --- a/agent-module/plugins/jboss/src/test/java/com/navercorp/pinpoint/plugin/jboss/InvokeMethodInterceptorTest.java +++ b/agent-module/plugins/jboss/src/test/java/com/navercorp/pinpoint/plugin/jboss/InvokeMethodInterceptorTest.java @@ -25,6 +25,7 @@ import com.navercorp.pinpoint.bootstrap.plugin.RequestRecorderFactory; import com.navercorp.pinpoint.bootstrap.plugin.proxy.DisableRequestRecorder; import com.navercorp.pinpoint.bootstrap.plugin.request.RequestAdaptor; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.plugin.jboss.interceptor.StandardHostValveInvokeInterceptor; import com.navercorp.pinpoint.profiler.context.DefaultMethodDescriptor; import com.navercorp.pinpoint.profiler.context.id.DefaultTraceId; @@ -203,7 +204,7 @@ public void testValidHeaderExists() { when(request.getRequestURI()).thenReturn("/hellotest.nhn"); when(request.getRemoteAddr()).thenReturn("10.0.0.1"); - TraceId traceId = new DefaultTraceId("agentTest", System.currentTimeMillis(), 1); + TraceId traceId = new DefaultTraceId(AgentId.of("agentTest"), System.currentTimeMillis(), 1); when(request.getHeader(Header.HTTP_TRACE_ID.toString())).thenReturn(traceId.getTransactionId()); when(request.getHeader(Header.HTTP_PARENT_SPAN_ID.toString())).thenReturn("PARENTSPANID"); when(request.getHeader(Header.HTTP_SPAN_ID.toString())).thenReturn("SPANID"); diff --git a/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextFactory.java b/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextFactory.java index 25f835fd00a4..fa0c226a7e25 100644 --- a/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextFactory.java +++ b/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextFactory.java @@ -21,6 +21,7 @@ import com.navercorp.pinpoint.bootstrap.DefaultAgentOption; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfigLoader; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext; import com.navercorp.pinpoint.profiler.context.module.ModuleFactory; import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder; @@ -64,11 +65,12 @@ public DefaultApplicationContext build(ProfilerConfig config) { public DefaultApplicationContext build(ProfilerConfig config, ModuleFactory moduleFactory) { Instrumentation instrumentation = new DummyInstrumentation(); - String mockAgentId = "mockAgentId"; + AgentId mockAgentId = AgentId.of("mockAgentId"); String mockAgentName = "mockAgentName"; String mockApplicationName = "mockApplicationName"; + String mockServiceName = "mockServiceName"; - AgentOption agentOption = new DefaultAgentOption(instrumentation, mockAgentId, mockAgentName, mockApplicationName, false, + AgentOption agentOption = new DefaultAgentOption(instrumentation, mockAgentId, mockAgentName, mockApplicationName, mockServiceName, false, config, Collections.emptyList(), Collections.emptyList()); return new DefaultApplicationContext(agentOption, moduleFactory); } @@ -79,8 +81,7 @@ private ModuleFactory newModuleFactory() { InterceptorRegistryBinder binder = new TestInterceptorRegistryBinder(); Module interceptorRegistryModule = InterceptorRegistryModule.wrap(binder); - ModuleFactory moduleFactory = new OverrideModuleFactory(pluginModule, interceptorRegistryModule); - return moduleFactory; + return new OverrideModuleFactory(pluginModule, interceptorRegistryModule); } } diff --git a/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/TestAgentInformation.java b/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/TestAgentInformation.java index 978b503c45b4..2cbe4a9fd835 100644 --- a/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/TestAgentInformation.java +++ b/agent-module/profiler-test/src/main/java/com/navercorp/pinpoint/profiler/test/TestAgentInformation.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.test; import com.navercorp.pinpoint.common.Version; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.JvmUtils; import com.navercorp.pinpoint.common.util.SystemPropertyKey; @@ -27,9 +28,10 @@ */ public class TestAgentInformation extends DefaultAgentInformation { - private static final String AGENT_ID = "test-agent"; + private static final AgentId AGENT_ID = AgentId.of("test-agent"); private static final String AGENT_NAME = "test-agent-name"; private static final String APPLICATION_NAME = "TEST_APPLICATION"; + private static final String SERVICE_NAME = "TEST_SERVICE"; private static final boolean IS_CONTAINER = false; private static final int PID = 10; private static final String MACHINE_NAME = "test-machine"; @@ -39,6 +41,6 @@ public class TestAgentInformation extends DefaultAgentInformation { private static final String AGENT_VERSION = Version.VERSION; public TestAgentInformation() { - super(AGENT_ID, AGENT_NAME, APPLICATION_NAME, IS_CONTAINER, System.currentTimeMillis(), PID, MACHINE_NAME, HOST_IP, SERVICE_TYPE, JVM_VERSION, AGENT_VERSION); + super(AGENT_ID, AGENT_NAME, APPLICATION_NAME, SERVICE_NAME, IS_CONTAINER, System.currentTimeMillis(), PID, MACHINE_NAME, HOST_IP, SERVICE_TYPE, JVM_VERSION, AGENT_VERSION); } } diff --git a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextModuleTest.java b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextModuleTest.java index e394847a3bb0..1c8cfe560c2e 100644 --- a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextModuleTest.java +++ b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/MockApplicationContextModuleTest.java @@ -23,6 +23,7 @@ import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.Profiles; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.AgentInfoSender; import com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext; import com.navercorp.pinpoint.profiler.context.module.ModuleFactory; @@ -36,6 +37,7 @@ import java.net.URL; import java.util.Collections; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -49,11 +51,12 @@ public void test() { ProfilerConfig profilerConfig = spy(new DefaultProfilerConfig()); when(profilerConfig.getStaticResourceCleanup()).thenReturn(true); URL resource = getClass().getResource("/"); + assertThat(resource).isNotNull(); when(profilerConfig.readString(Profiles.LOG_CONFIG_LOCATION_KEY, null)).thenReturn(resource.getPath()); Instrumentation instrumentation = Mockito.mock(Instrumentation.class); AgentOption agentOption = new DefaultAgentOption(instrumentation, - "mockAgentId", "mockAgentName", "mockApplicationName", false, + AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", false, profilerConfig, Collections.emptyList(), Collections.emptyList()); PluginTestAgent pluginTestAgent = new PluginTestAgent(agentOption); @@ -71,7 +74,7 @@ public void testMockApplicationContext() { Instrumentation instrumentation = Mockito.mock(Instrumentation.class); AgentOption agentOption = new DefaultAgentOption(instrumentation, - "mockAgentId", "mockAgentName", "mockApplicationName", false, + AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", false, profilerConfig, Collections.emptyList(), Collections.emptyList()); Module pluginModule = new PluginApplicationContextModule(); @@ -87,7 +90,7 @@ public void testMockApplicationContext() { AgentInfoSender instance2 = injector.getInstance(AgentInfoSender.class); Assertions.assertSame(instance1, instance2); - ClassFileTransformer instance4 = injector.getInstance(ClassFileTransformer.class); + injector.getInstance(ClassFileTransformer.class); applicationContext.close(); } diff --git a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/OrderedSpanRecorderTest.java b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/OrderedSpanRecorderTest.java index dcf820b6c9fb..3b5ac9218a2f 100644 --- a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/OrderedSpanRecorderTest.java +++ b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/OrderedSpanRecorderTest.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.test; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.DefaultAsyncSpanChunk; import com.navercorp.pinpoint.profiler.context.DefaultLocalAsyncId; import com.navercorp.pinpoint.profiler.context.DefaultSpanChunk; @@ -54,7 +55,7 @@ public class OrderedSpanRecorderTest { private final OrderedSpanRecorder recorder = new OrderedSpanRecorder(); - private final String agentId = "agentId"; + private final AgentId agentId = AgentId.of("agentId"); @AfterEach public void tearDown() { diff --git a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/monitor/AgentStatMonitorTest.java b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/monitor/AgentStatMonitorTest.java index 4eb3914dadc3..49551e4e1c55 100644 --- a/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/monitor/AgentStatMonitorTest.java +++ b/agent-module/profiler-test/src/test/java/com/navercorp/pinpoint/profiler/test/monitor/AgentStatMonitorTest.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.test.monitor; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.DataSender; import com.navercorp.pinpoint.profiler.context.monitor.config.MonitorConfig; import com.navercorp.pinpoint.profiler.monitor.AgentStatMonitor; @@ -82,7 +83,7 @@ public void testAgentStatMonitor() throws InterruptedException { Mockito.when(mockProfilerConfig.getProfileJvmStatBatchSendCount()).thenReturn(numCollectionsPerBatch); // When - AgentStatMonitor monitor = new DefaultAgentStatMonitor(this.dataSender, "agentId", System.currentTimeMillis(), + AgentStatMonitor monitor = new DefaultAgentStatMonitor(this.dataSender, AgentId.of("agentId"), System.currentTimeMillis(), agentStatCollector, null, null, mockProfilerConfig); monitor.start(); Thread.sleep(totalTestDurationMs); diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java index e5bf26a75703..5eac22377406 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/AgentInformation.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.profiler; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; /** @@ -23,12 +24,14 @@ */ public interface AgentInformation { - String getAgentId(); + AgentId getAgentId(); String getAgentName(); String getApplicationName(); + String getServiceName(); + boolean isContainer(); long getStartTime(); diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgentInformation.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgentInformation.java index 83ee586bb9b0..ae07b806f1fd 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgentInformation.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/DefaultAgentInformation.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.profiler; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import java.util.Objects; @@ -26,9 +27,10 @@ * @author hyungil.jeong */ public class DefaultAgentInformation implements AgentInformation { - private final String agentId; + private final AgentId agentId; private final String agentName; private final String applicationName; + private final String serviceName; private final boolean isContainer; private final long startTime; private final int pid; @@ -39,9 +41,10 @@ public class DefaultAgentInformation implements AgentInformation { private final String agentVersion; public DefaultAgentInformation( - String agentId, + AgentId agentId, String agentName, String applicationName, + String serviceName, boolean isContainer, long startTime, int pid, @@ -53,6 +56,7 @@ public DefaultAgentInformation( this.agentId = Objects.requireNonNull(agentId, "agentId"); this.agentName = Objects.requireNonNull(agentName, "agentName"); this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); + this.serviceName = Objects.requireNonNull(serviceName, "serviceName"); this.isContainer = isContainer; this.startTime = startTime; this.pid = pid; @@ -64,7 +68,7 @@ public DefaultAgentInformation( } @Override - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -78,6 +82,11 @@ public String getApplicationName() { return applicationName; } + @Override + public String getServiceName() { + return serviceName; + } + @Override public boolean isContainer() { return isContainer; @@ -120,19 +129,18 @@ public String getAgentVersion() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("{"); - sb.append("agentId='").append(agentId).append('\''); - sb.append(", agentName='").append(agentName).append('\''); - sb.append(", applicationName='").append(applicationName).append('\''); - sb.append(", isContainer=").append(isContainer); - sb.append(", startTime=").append(startTime); - sb.append(", pid=").append(pid); - sb.append(", machineName='").append(machineName).append('\''); - sb.append(", hostIp='").append(hostIp).append('\''); - sb.append(", serverType=").append(serverType); - sb.append(", jvmVersion='").append(jvmVersion).append('\''); - sb.append(", agentVersion='").append(agentVersion).append('\''); - sb.append('}'); - return sb.toString(); + return "{" + "agentId='" + agentId + '\'' + + ", agentName='" + agentName + '\'' + + ", applicationName='" + applicationName + '\'' + + ", serviceName='" + serviceName + '\'' + + ", isContainer=" + isContainer + + ", startTime=" + startTime + + ", pid=" + pid + + ", machineName='" + machineName + '\'' + + ", hostIp='" + hostIp + '\'' + + ", serverType=" + serverType + + ", jvmVersion='" + jvmVersion + '\'' + + ", agentVersion='" + agentVersion + '\'' + + '}'; } } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContext.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContext.java index 5aebc48168e4..9b1aa48681fb 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContext.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContext.java @@ -25,6 +25,7 @@ import com.navercorp.pinpoint.bootstrap.context.TraceId; import com.navercorp.pinpoint.bootstrap.plugin.jdbc.JdbcContext; import com.navercorp.pinpoint.common.annotations.InterfaceAudience; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.AgentInformation; import com.navercorp.pinpoint.profiler.context.id.TraceIdFactory; import com.navercorp.pinpoint.profiler.metadata.ApiMetaDataService; @@ -188,7 +189,7 @@ private Trace closeUnsampledTrace(Trace trace) { } @Override - public String getAgentId() { + public AgentId getAgentId() { return this.agentInformation.getAgentId(); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverter.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverter.java index c5cb490fbd53..a29248d05e24 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverter.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverter.java @@ -18,7 +18,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.common.annotations.VisibleForTesting; -import com.navercorp.pinpoint.common.profiler.logging.ThrottledLogger; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.MessageConverter; import com.navercorp.pinpoint.grpc.trace.PSpan; import com.navercorp.pinpoint.grpc.trace.PSpanChunk; @@ -27,8 +27,6 @@ import com.navercorp.pinpoint.profiler.context.SpanType; import com.navercorp.pinpoint.profiler.context.compress.SpanProcessor; import com.navercorp.pinpoint.profiler.context.grpc.mapper.SpanMessageMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import java.util.Objects; @@ -39,10 +37,7 @@ */ public class GrpcSpanMessageConverter implements MessageConverter { - private final Logger logger = LogManager.getLogger(this.getClass()); - private final ThrottledLogger throttledLogger = ThrottledLogger.getLogger(this.logger, 100); - - private final String agentId; + private final AgentId agentId; private final short applicationServiceType; private final SpanProcessor spanProcessor; @@ -51,7 +46,7 @@ public class GrpcSpanMessageConverter implements MessageConverter spanProcessor, SpanMessageMapper spanMessageMapper) { this.agentId = Objects.requireNonNull(agentId, "agentId"); diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterProvider.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterProvider.java index d05aad2c16e7..87bf0805ec0a 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterProvider.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterProvider.java @@ -19,15 +19,15 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.protobuf.GeneratedMessageV3; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.MessageConverter; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.trace.PSpan; import com.navercorp.pinpoint.grpc.trace.PSpanChunk; import com.navercorp.pinpoint.profiler.context.SpanType; import com.navercorp.pinpoint.profiler.context.compress.SpanProcessor; -import com.navercorp.pinpoint.profiler.context.grpc.config.SpanUriGetter; import com.navercorp.pinpoint.profiler.context.grpc.mapper.SpanMessageMapper; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.ApplicationServerType; import java.util.Objects; @@ -37,21 +37,18 @@ */ public class GrpcSpanMessageConverterProvider implements Provider> { - private final String agentId; + private final AgentId agentId; private final short applicationServiceTypeCode; private final SpanProcessor spanPostProcessor; - private final SpanUriGetter spanUriGetter; private final SpanMessageMapper mapper; @Inject - public GrpcSpanMessageConverterProvider(@AgentId String agentId, @ApplicationServerType ServiceType applicationServiceType, + public GrpcSpanMessageConverterProvider(@AgentIdHolder AgentId agentId, @ApplicationServerType ServiceType applicationServiceType, SpanProcessor spanPostProcessor, - SpanUriGetter spanUriGetter, SpanMessageMapper spanMessageMapper) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.applicationServiceTypeCode = applicationServiceType.getCode(); this.spanPostProcessor = Objects.requireNonNull(spanPostProcessor, "spanPostProcessor"); - this.spanUriGetter = Objects.requireNonNull(spanUriGetter, "spanUriGetter"); this.mapper = Objects.requireNonNull(spanMessageMapper, "spanMessageMapper"); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/mapper/TraceIdMapStructUtils.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/mapper/TraceIdMapStructUtils.java index 52b80b0bd2e6..b8043d9fd11c 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/mapper/TraceIdMapStructUtils.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/grpc/mapper/TraceIdMapStructUtils.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.profiler.context.grpc.mapper; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.grpc.trace.PTransactionId; import org.mapstruct.Qualifier; @@ -37,7 +38,7 @@ public class TraceIdMapStructUtils { @ToTransactionId public static PTransactionId newTransactionId(TraceId traceId) { final PTransactionId.Builder builder = PTransactionId.newBuilder(); - builder.setAgentId(traceId.getAgentId()); + builder.setAgentId(AgentId.unwrap(traceId.getAgentId())); builder.setAgentStartTime(traceId.getAgentStartTime()); builder.setSequence(traceId.getTransactionSequence()); return builder.build(); diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceId.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceId.java index 2f26f00ddcaa..120b3497105e 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceId.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceId.java @@ -18,6 +18,7 @@ import com.navercorp.pinpoint.bootstrap.context.SpanId; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import java.util.Objects; @@ -27,7 +28,7 @@ */ public class DefaultTraceId implements TraceId { - private final String agentId; + private final AgentId agentId; private final long agentStartTime; private final long transactionSequence; @@ -35,15 +36,16 @@ public class DefaultTraceId implements TraceId { private final long spanId; private final short flags; - public DefaultTraceId(String agentId, long agentStartTime, long transactionId) { + public DefaultTraceId(AgentId agentId, long agentStartTime, long transactionId) { this(agentId, agentStartTime, transactionId, SpanId.NULL, SpanId.newSpanId(), (short) 0); } + @Override public TraceId getNextTraceId() { return new DefaultTraceId(this.agentId, this.agentStartTime, transactionSequence, spanId, SpanId.nextSpanID(spanId, parentSpanId), flags); } - public DefaultTraceId(String agentId, long agentStartTime, long transactionId, long parentSpanId, long spanId, short flags) { + public DefaultTraceId(AgentId agentId, long agentStartTime, long transactionId, long parentSpanId, long spanId, short flags) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.agentStartTime = agentStartTime; this.transactionSequence = transactionId; @@ -53,51 +55,57 @@ public DefaultTraceId(String agentId, long agentStartTime, long transactionId, l this.flags = flags; } + @Override public String getTransactionId() { return TransactionIdUtils.formatString(agentId, agentStartTime, transactionSequence); } - public String getAgentId() { + @Override + public AgentId getAgentId() { return agentId; } + @Override public long getAgentStartTime() { return agentStartTime; } + @Override public long getTransactionSequence() { return transactionSequence; } + @Override public long getParentSpanId() { return parentSpanId; } + @Override public long getSpanId() { return spanId; } + @Override public short getFlags() { return flags; } + @Override public boolean isRoot() { return this.parentSpanId == SpanId.NULL; } @Override public String toString() { - final StringBuilder sb = new StringBuilder("DefaultTraceId{"); - sb.append("agentId='").append(agentId).append('\''); - sb.append(", agentStartTime=").append(agentStartTime); - sb.append(", transactionSequence=").append(transactionSequence); - sb.append(", parentSpanId=").append(parentSpanId); - sb.append(", spanId=").append(spanId); - sb.append(", flags=").append(flags); - sb.append('}'); - return sb.toString(); + return "DefaultTraceId{" + "agentId='" + agentId + '\'' + + ", agentStartTime=" + agentStartTime + + ", transactionSequence=" + transactionSequence + + ", parentSpanId=" + parentSpanId + + ", spanId=" + spanId + + ", flags=" + flags + + '}'; } } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceIdFactory.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceIdFactory.java index 0e2f6c32c489..ad4396c8e0e8 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceIdFactory.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceIdFactory.java @@ -18,9 +18,10 @@ import com.google.inject.Inject; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.AgentStartTime; import java.util.Objects; @@ -30,11 +31,11 @@ */ public class DefaultTraceIdFactory implements TraceIdFactory { - private final String agentId; + private final AgentId agentId; private final long agentStartTime; @Inject - public DefaultTraceIdFactory(@AgentId String agentId, @AgentStartTime long agentStartTime) { + public DefaultTraceIdFactory(@AgentIdHolder AgentId agentId, @AgentStartTime long agentStartTime) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.agentStartTime = agentStartTime; diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceRootFactory.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceRootFactory.java index b55875f4cddf..063d4db904a1 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceRootFactory.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/DefaultTraceRootFactory.java @@ -18,7 +18,8 @@ import com.google.inject.Inject; import com.navercorp.pinpoint.bootstrap.context.TraceId; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import java.util.Objects; @@ -27,11 +28,11 @@ */ public class DefaultTraceRootFactory implements TraceRootFactory { - private final String agentId; + private final AgentId agentId; private final TraceIdFactory traceIdFactory; @Inject - public DefaultTraceRootFactory(@AgentId String agentId, TraceIdFactory traceIdFactory) { + public DefaultTraceRootFactory(@AgentIdHolder AgentId agentId, TraceIdFactory traceIdFactory) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.traceIdFactory = Objects.requireNonNull(traceIdFactory, "traceIdFactory"); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootImpl.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootImpl.java index 322fa560db6b..1fa7782fd032 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootImpl.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootImpl.java @@ -1,5 +1,7 @@ package com.navercorp.pinpoint.profiler.context.id; +import com.navercorp.pinpoint.common.id.AgentId; + import java.util.Objects; /** @@ -7,7 +9,7 @@ */ public class LocalTraceRootImpl implements LocalTraceRoot { - protected final String agentId; + protected final AgentId agentId; protected final long localTransactionId; protected final long traceStartTime; @@ -15,13 +17,13 @@ public class LocalTraceRootImpl implements LocalTraceRoot { protected final Shared shared = new DefaultShared(); - LocalTraceRootImpl(String agentId, long traceStartTime, long localTransactionId) { + LocalTraceRootImpl(AgentId agentId, long traceStartTime, long localTransactionId) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.traceStartTime = traceStartTime; this.localTransactionId = localTransactionId; } - public String getAgentId() { + public AgentId getAgentId() { return agentId; } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/RemoteTraceRootImpl.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/RemoteTraceRootImpl.java index aac3050cf35d..8eb94f7e40d5 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/RemoteTraceRootImpl.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/RemoteTraceRootImpl.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.context.id; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import java.util.Objects; @@ -27,7 +28,7 @@ public class RemoteTraceRootImpl extends LocalTraceRootImpl implements TraceRoot private final TraceId traceId; - RemoteTraceRootImpl(TraceId traceId, String agentId, long traceStartTime, long localTransactionId) { + RemoteTraceRootImpl(TraceId traceId, AgentId agentId, long traceStartTime, long localTransactionId) { super(agentId, traceStartTime, localTransactionId); this.traceId = Objects.requireNonNull(traceId, "traceId"); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/TraceRoot.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/TraceRoot.java index 0e39754f0164..38a8e35e24c4 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/TraceRoot.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/id/TraceRoot.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.context.id; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import java.util.Objects; @@ -36,11 +37,11 @@ public interface TraceRoot extends LocalTraceRoot { @Override Shared getShared(); - static TraceRoot remote(TraceId traceId, String agentId, long traceStartTime, long localTransactionId) { + static TraceRoot remote(TraceId traceId, AgentId agentId, long traceStartTime, long localTransactionId) { return new RemoteTraceRootImpl(traceId, agentId, traceStartTime, localTransactionId); } - static LocalTraceRoot local(String agentId, long traceStartTime, long localTransactionId) { + static LocalTraceRoot local(AgentId agentId, long traceStartTime, long localTransactionId) { Objects.requireNonNull(agentId, "agentId"); return new LocalTraceRootImpl(agentId, traceStartTime, localTransactionId); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentIdHolder.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentIdHolder.java new file mode 100644 index 000000000000..6dfdc46e8933 --- /dev/null +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentIdHolder.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.profiler.context.module; + +import com.google.inject.BindingAnnotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author Woonduk Kang(emeroad) + */ +@BindingAnnotation +@Target(PARAMETER) +@Retention(RUNTIME) +public @interface AgentIdHolder { +} diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentId.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/ServiceName.java similarity index 96% rename from agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentId.java rename to agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/ServiceName.java index e8fdc396ab7c..9b0c8257a070 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/AgentId.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/ServiceName.java @@ -30,5 +30,5 @@ @BindingAnnotation @Target(PARAMETER) @Retention(RUNTIME) -public @interface AgentId { +public @interface ServiceName { } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/config/ConfigModule.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/config/ConfigModule.java index 7a26c275cc84..1aa46593a012 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/config/ConfigModule.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/module/config/ConfigModule.java @@ -22,11 +22,12 @@ import com.navercorp.pinpoint.bootstrap.AgentOption; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.TransportModule; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.profiler.context.TraceDataFormatVersion; import com.navercorp.pinpoint.profiler.context.config.ContextConfig; import com.navercorp.pinpoint.profiler.context.config.DefaultContextConfig; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.AgentName; import com.navercorp.pinpoint.profiler.context.module.AgentStartTime; import com.navercorp.pinpoint.profiler.context.module.ApplicationName; @@ -35,6 +36,7 @@ import com.navercorp.pinpoint.profiler.context.module.Container; import com.navercorp.pinpoint.profiler.context.module.PluginJarPaths; import com.navercorp.pinpoint.profiler.context.module.PluginJars; +import com.navercorp.pinpoint.profiler.context.module.ServiceName; import com.navercorp.pinpoint.profiler.context.monitor.config.DefaultMonitorConfig; import com.navercorp.pinpoint.profiler.context.monitor.config.MonitorConfig; import com.navercorp.pinpoint.profiler.context.provider.AgentStartTimeProvider; @@ -130,7 +132,13 @@ protected void configure() { bindBootstrapCoreInformation(); - bindAgentInformation(agentOption.getAgentId(), agentOption.getAgentName(), agentOption.getApplicationName(), agentOption.isContainer()); + bindAgentInformation( + agentOption.getAgentId(), + agentOption.getAgentName(), + agentOption.getApplicationName(), + agentOption.getServiceName(), + agentOption.isContainer() + ); bindShutdownHook(contextConfig); } @@ -154,11 +162,11 @@ private void bindConstants(ContextConfig contextConfig) { bindConstant().annotatedWith(DeadlockMonitorInterval.class).to(contextConfig.getDeadlockMonitorInterval()); } - private void bindAgentInformation(String agentId, String agentName, String applicationName, boolean isContainer) { - - bind(String.class).annotatedWith(AgentId.class).toInstance(agentId); + private void bindAgentInformation(AgentId agentId, String agentName, String applicationName, String serviceName, boolean isContainer) { + bind(AgentId.class).annotatedWith(AgentIdHolder.class).toInstance(agentId); bind(String.class).annotatedWith(AgentName.class).toInstance(agentName); bind(String.class).annotatedWith(ApplicationName.class).toInstance(applicationName); + bind(String.class).annotatedWith(ServiceName.class).toInstance(serviceName); bind(Boolean.class).annotatedWith(Container.class).toInstance(isContainer); bind(Long.class).annotatedWith(AgentStartTime.class).toProvider(AgentStartTimeProvider.class).in(Scopes.SINGLETON); bind(ServiceType.class).annotatedWith(ConfiguredApplicationType.class).toProvider(ConfiguredApplicationTypeProvider.class).in(Scopes.SINGLETON); diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/AgentInformationProvider.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/AgentInformationProvider.java index c0e539626b8e..6e13868c8ac2 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/AgentInformationProvider.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/AgentInformationProvider.java @@ -19,19 +19,22 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.navercorp.pinpoint.bootstrap.util.NetworkUtils; +import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.Version; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.IdValidateUtils; import com.navercorp.pinpoint.common.util.JvmUtils; import com.navercorp.pinpoint.common.util.SystemPropertyKey; import com.navercorp.pinpoint.profiler.AgentInformation; import com.navercorp.pinpoint.profiler.DefaultAgentInformation; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.AgentName; import com.navercorp.pinpoint.profiler.context.module.AgentStartTime; import com.navercorp.pinpoint.profiler.context.module.ApplicationName; import com.navercorp.pinpoint.profiler.context.module.ApplicationServerType; import com.navercorp.pinpoint.profiler.context.module.Container; +import com.navercorp.pinpoint.profiler.context.module.ServiceName; import com.navercorp.pinpoint.profiler.util.RuntimeMXBeanUtils; import java.util.Objects; @@ -41,21 +44,30 @@ */ public class AgentInformationProvider implements Provider { - private final String agentId; + private final AgentId agentId; private final String agentName; private final String applicationName; + private final String serviceName; private final boolean isContainer; private final long agentStartTime; private final ServiceType serverType; @Inject - public AgentInformationProvider(@AgentId String agentId, @AgentName String agentName, @ApplicationName String applicationName, - @Container boolean isContainer, @AgentStartTime long agentStartTime, @ApplicationServerType ServiceType serverType) { + public AgentInformationProvider( + @AgentIdHolder AgentId agentId, + @AgentName String agentName, + @ApplicationName String applicationName, + @ServiceName String serviceName, + @Container boolean isContainer, + @AgentStartTime long agentStartTime, + @ApplicationServerType ServiceType serverType + ) { Objects.requireNonNull(agentId, "agentId"); Objects.requireNonNull(applicationName, "applicationName"); - this.agentId = checkId("agentId", agentId); - this.applicationName = checkId("applicationName", applicationName); + this.agentId = checkId("agentId", agentId, PinpointConstants.AGENT_ID_MAX_LEN); + this.applicationName = checkId("applicationName", applicationName, PinpointConstants.APPLICATION_NAME_MAX_LEN); + this.serviceName = checkId("serviceName", serviceName, PinpointConstants.SERVICE_NAME_MAX_LEN); this.agentName = agentName; this.isContainer = isContainer; this.agentStartTime = agentStartTime; @@ -68,19 +80,24 @@ public AgentInformation get() { } public AgentInformation createAgentInformation() { - final String machineName = NetworkUtils.getHostName(); final String hostIp = NetworkUtils.getRepresentationHostIp(); final int pid = RuntimeMXBeanUtils.getPid(); final String jvmVersion = JvmUtils.getSystemProperty(SystemPropertyKey.JAVA_VERSION); - return new DefaultAgentInformation(agentId, agentName, applicationName, isContainer, agentStartTime, pid, machineName, hostIp, serverType, jvmVersion, Version.VERSION); + return new DefaultAgentInformation(agentId, agentName, applicationName, serviceName, + isContainer, agentStartTime, pid, machineName, hostIp, serverType, jvmVersion, Version.VERSION); } - private String checkId(String keyName,String id) { - if (!IdValidateUtils.validateId(id)) { + private String checkId(String keyName, String id, int maxLen) { + if (!IdValidateUtils.validateId(id, maxLen)) { throw new IllegalArgumentException("invalid " + keyName + "=" + id); } return id; } + + private AgentId checkId(String keyName, AgentId id, int maxLen) { + return AgentId.of(checkId(keyName, AgentId.unwrap(id), maxLen)); + } + } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/grpc/AgentHeaderFactoryProvider.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/grpc/AgentHeaderFactoryProvider.java index da5ae6c104df..752a7825de15 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/grpc/AgentHeaderFactoryProvider.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/context/provider/grpc/AgentHeaderFactoryProvider.java @@ -37,6 +37,13 @@ public AgentHeaderFactoryProvider(AgentInformation agentInformation) { @Override public HeaderFactory get() { - return new AgentHeaderFactory(agentInformation.getAgentId(), agentInformation.getAgentName(), agentInformation.getApplicationName(), agentInformation.getServerType().getCode(), agentInformation.getStartTime()); + return new AgentHeaderFactory( + agentInformation.getAgentId(), + agentInformation.getAgentName(), + agentInformation.getApplicationName(), + agentInformation.getServiceName(), + agentInformation.getServerType().getCode(), + agentInformation.getStartTime() + ); } } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CollectJob.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CollectJob.java index 489dd46412f3..ee5a7eb0032a 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CollectJob.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/CollectJob.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.profiler.monitor; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.DataSender; import com.navercorp.pinpoint.profiler.monitor.collector.AgentStatMetricCollector; import com.navercorp.pinpoint.profiler.monitor.metric.AgentStatMetricSnapshot; @@ -36,7 +37,7 @@ public class CollectJob implements Runnable { private final Logger logger = LogManager.getLogger(this.getClass()); private final DataSender dataSender; - private final String agentId; + private final AgentId agentId; private final long agentStartTimestamp; private final AgentStatMetricCollector agentStatCollector; private final int numCollectionsPerBatch; @@ -47,9 +48,9 @@ public class CollectJob implements Runnable { private List agentStats; public CollectJob(DataSender dataSender, - String agentId, long agentStartTimestamp, - AgentStatMetricCollector agentStatCollector, - int numCollectionsPerBatch) { + AgentId agentId, long agentStartTimestamp, + AgentStatMetricCollector agentStatCollector, + int numCollectionsPerBatch) { this.dataSender = Objects.requireNonNull(dataSender, "dataSender"); this.agentId = agentId; this.agentStartTimestamp = agentStartTimestamp; @@ -83,7 +84,7 @@ private void sendAgentStats() { // TODO multi thread issue. // If we reuse TAgentStat, there could be concurrency issue because data sender runs in a different thread. final AgentStatMetricSnapshotBatch agentStatBatch = new AgentStatMetricSnapshotBatch(); - agentStatBatch.setAgentId(agentId); + agentStatBatch.setAgentId(AgentId.unwrap(agentId)); agentStatBatch.setStartTimestamp(agentStartTimestamp); agentStatBatch.setAgentStats(this.agentStats); // If we reuse agentStats list, there could be concurrency issue because data sender runs in a different diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/DefaultAgentStatMonitor.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/DefaultAgentStatMonitor.java index 3bfc93451d48..33aaf3ef5fce 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/DefaultAgentStatMonitor.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/DefaultAgentStatMonitor.java @@ -18,10 +18,11 @@ import com.google.inject.Inject; import com.google.inject.name.Named; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.concurrent.PinpointThreadFactory; import com.navercorp.pinpoint.common.profiler.message.DataSender; import com.navercorp.pinpoint.common.profiler.message.EmptyDataSender; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.AgentStartTime; import com.navercorp.pinpoint.profiler.context.module.StatDataSender; import com.navercorp.pinpoint.profiler.context.monitor.config.DefaultMonitorConfig; @@ -64,7 +65,7 @@ public class DefaultAgentStatMonitor implements AgentStatMonitor { @Inject public DefaultAgentStatMonitor(@StatDataSender DataSender dataSender, - @AgentId String agentId, + @AgentIdHolder AgentId agentId, @AgentStartTime long agentStartTimestamp, @Named("AgentStatCollector") AgentStatMetricCollector agentStatCollector, CustomMetricRegistryService customMetricRegistryService, @@ -114,7 +115,7 @@ public DefaultAgentStatMonitor(@StatDataSender DataSender dataSender // prevent deadlock for JDK6 // Single thread execution is more safe than multi thread execution. // eg) executor.scheduleAtFixedRate(collectJob, 0(initialDelay is zero), this.collectionIntervalMs, TimeUnit.MILLISECONDS); - private void preLoadClass(String agentId, long agentStartTimestamp, AgentStatMetricCollector agentStatCollector) { + private void preLoadClass(AgentId agentId, long agentStartTimestamp, AgentStatMetricCollector agentStatCollector) { logger.debug("pre-load class start"); CollectJob collectJob = new CollectJob(EmptyDataSender.instance(), agentId, agentStartTimestamp, agentStatCollector, 1); @@ -137,7 +138,9 @@ public void stop() { executor.shutdown(); try { - executor.awaitTermination(3000, TimeUnit.MILLISECONDS); + if (!executor.awaitTermination(3000, TimeUnit.MILLISECONDS)) { + logger.warn("AgentStat monitor shutdown forcefully"); + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } diff --git a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/collector/AgentStatCollector.java b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/collector/AgentStatCollector.java index a668f365bd2a..6628894abd65 100644 --- a/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/collector/AgentStatCollector.java +++ b/agent-module/profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/collector/AgentStatCollector.java @@ -17,8 +17,9 @@ package com.navercorp.pinpoint.profiler.monitor.collector; import com.google.inject.Inject; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.active.ActiveTraceHistogram; -import com.navercorp.pinpoint.profiler.context.module.AgentId; +import com.navercorp.pinpoint.profiler.context.module.AgentIdHolder; import com.navercorp.pinpoint.profiler.context.module.AgentStartTime; import com.navercorp.pinpoint.profiler.monitor.metric.AgentStatMetricSnapshot; import com.navercorp.pinpoint.profiler.monitor.metric.JvmGcMetricSnapshot; @@ -39,7 +40,7 @@ */ public class AgentStatCollector implements AgentStatMetricCollector { - private final String agentId; + private final AgentId agentId; private final long agentStartTimestamp; private final AgentStatMetricCollector jvmGcMetricCollector; private final AgentStatMetricCollector cpuLoadMetricCollector; @@ -55,7 +56,7 @@ public class AgentStatCollector implements AgentStatMetricCollector jvmGcMetricCollector, AgentStatMetricCollector cpuLoadMetricCollector, @@ -86,7 +87,7 @@ public AgentStatCollector( @Override public AgentStatMetricSnapshot collect() { AgentStatMetricSnapshot agentStat = new AgentStatMetricSnapshot(); - agentStat.setAgentId(agentId); + agentStat.setAgentId(AgentId.unwrap(agentId)); agentStat.setStartTimestamp(agentStartTimestamp); agentStat.setGc(jvmGcMetricCollector.collect()); agentStat.setCpuLoad(cpuLoadMetricCollector.collect()); @@ -105,21 +106,19 @@ public AgentStatMetricSnapshot collect() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("AgentStatCollector{"); - sb.append("agentId='").append(agentId).append('\''); - sb.append(", agentStartTimestamp=").append(agentStartTimestamp); - sb.append(", jvmGcMetricCollector=").append(jvmGcMetricCollector); - sb.append(", cpuLoadMetricCollector=").append(cpuLoadMetricCollector); - sb.append(", transactionMetricCollector=").append(transactionMetricCollector); - sb.append(", activeTraceMetricCollector=").append(activeTraceMetricCollector); - sb.append(", dataSourceMetricCollector=").append(dataSourceMetricCollector); - sb.append(", responseTimeMetricCollector=").append(responseTimeMetricCollector); - sb.append(", deadlockMetricCollector=").append(deadlockMetricCollector); - sb.append(", fileDescriptorMetricCollector=").append(fileDescriptorMetricCollector); - sb.append(", bufferMetricCollector=").append(bufferMetricCollector); - sb.append(", totalThreadMetricCollector=").append(totalThreadMetricCollector); - sb.append(", loadedClassMetricCollector=").append(loadedClassMetricCollector); - sb.append('}'); - return sb.toString(); + return "AgentStatCollector{" + "agentId='" + agentId + '\'' + + ", agentStartTimestamp=" + agentStartTimestamp + + ", jvmGcMetricCollector=" + jvmGcMetricCollector + + ", cpuLoadMetricCollector=" + cpuLoadMetricCollector + + ", transactionMetricCollector=" + transactionMetricCollector + + ", activeTraceMetricCollector=" + activeTraceMetricCollector + + ", dataSourceMetricCollector=" + dataSourceMetricCollector + + ", responseTimeMetricCollector=" + responseTimeMetricCollector + + ", deadlockMetricCollector=" + deadlockMetricCollector + + ", fileDescriptorMetricCollector=" + fileDescriptorMetricCollector + + ", bufferMetricCollector=" + bufferMetricCollector + + ", totalThreadMetricCollector=" + totalThreadMetricCollector + + ", loadedClassMetricCollector=" + loadedClassMetricCollector + + '}'; } } \ No newline at end of file diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContextTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContextTest.java index 0af10b51c80a..103300483748 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContextTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/DefaultTraceContextTest.java @@ -21,6 +21,7 @@ import com.navercorp.pinpoint.bootstrap.context.Trace; import com.navercorp.pinpoint.bootstrap.context.TraceContext; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import com.navercorp.pinpoint.profiler.context.id.DefaultTraceId; @@ -66,7 +67,7 @@ public void tearDown() throws Exception { @Test public void parseTest() { - String agent = "test"; + AgentId agent = AgentId.of("test"); long agentStartTime = System.currentTimeMillis(); long agentTransactionCount = 10; TraceId traceId = new DefaultTraceId(agent, agentStartTime, agentTransactionCount); @@ -141,7 +142,7 @@ public void transactionCountTest() { final long expectedSampledContinuationCount = 5L; for (int i = 0; i < expectedSampledContinuationCount; i++) { - traceContext.continueTraceObject(new DefaultTraceId("agentId", 0L, i)); + traceContext.continueTraceObject(new DefaultTraceId(AgentId.of("agentId"), 0L, i)); traceContext.removeTraceObject(); } diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/MockApplicationContextFactory.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/MockApplicationContextFactory.java index 21d9802375cd..5323c2fe901f 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/MockApplicationContextFactory.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/MockApplicationContextFactory.java @@ -19,6 +19,7 @@ import com.navercorp.pinpoint.bootstrap.AgentOption; import com.navercorp.pinpoint.bootstrap.DefaultAgentOption; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext; import com.navercorp.pinpoint.profiler.context.module.ModuleFactory; import org.mockito.Mockito; @@ -37,10 +38,11 @@ public MockApplicationContextFactory() { public DefaultApplicationContext build(ProfilerConfig config, ModuleFactory moduleFactory) { Instrumentation instrumentation = Mockito.mock(Instrumentation.class); - String mockAgentId = "mockAgentId"; + AgentId mockAgentId = AgentId.of("mockAgentId"); String mockAgentName = "mockAgentName"; String mockApplicationName = "mockApplicationName"; - AgentOption agentOption = new DefaultAgentOption(instrumentation, mockAgentId, mockAgentName, mockApplicationName, false, + String mockServiceName = "mockServiceName"; + AgentOption agentOption = new DefaultAgentOption(instrumentation, mockAgentId, mockAgentName, mockApplicationName, mockServiceName, false, config, Collections.emptyList(), Collections.emptyList()); return new DefaultApplicationContext(agentOption, moduleFactory); } diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TestAgentInformation.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TestAgentInformation.java index 672ce9ab59b0..c57e861d6ddf 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TestAgentInformation.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TestAgentInformation.java @@ -18,6 +18,7 @@ package com.navercorp.pinpoint.profiler.context; import com.navercorp.pinpoint.common.Version; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.JvmUtils; import com.navercorp.pinpoint.common.util.SystemPropertyKey; @@ -29,9 +30,10 @@ */ public class TestAgentInformation extends DefaultAgentInformation { - private static final String AGENT_ID = "test-agent"; + private static final AgentId AGENT_ID = AgentId.of("test-agent"); private static final String AGENT_NAME = "test-agent-name"; private static final String APPLICATION_NAME = "TEST_APPLICATION"; + private static final String SERVICE_NAME = "TEST_SERVICE"; private static final boolean IS_CONTAINER = false; private static final int PID = 10; private static final String MACHINE_NAME = "test-machine"; @@ -41,6 +43,6 @@ public class TestAgentInformation extends DefaultAgentInformation { private static final String AGENT_VERSION = Version.VERSION; public TestAgentInformation() { - super(AGENT_ID, AGENT_NAME, APPLICATION_NAME, IS_CONTAINER, System.currentTimeMillis(), PID, MACHINE_NAME, HOST_IP, SERVICE_TYPE, JVM_VERSION, AGENT_VERSION); + super(AGENT_ID, AGENT_NAME, APPLICATION_NAME, SERVICE_NAME, IS_CONTAINER, System.currentTimeMillis(), PID, MACHINE_NAME, HOST_IP, SERVICE_TYPE, JVM_VERSION, AGENT_VERSION); } } diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TraceTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TraceTest.java index 1cf5c63c8a8e..20813a40f4ba 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TraceTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/TraceTest.java @@ -19,6 +19,7 @@ import com.navercorp.pinpoint.bootstrap.context.SpanRecorder; import com.navercorp.pinpoint.bootstrap.context.Trace; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.errorhandler.BypassErrorHandler; import com.navercorp.pinpoint.profiler.context.errorhandler.IgnoreErrorHandler; import com.navercorp.pinpoint.profiler.context.exception.ExceptionRecorder; @@ -51,7 +52,7 @@ public class TraceTest { private final Logger logger = LogManager.getLogger(this.getClass()); - private final String agentId = "agent"; + private final AgentId agentId = AgentId.of("agent"); private final long agentStartTime = System.currentTimeMillis(); private final long traceStartTime = agentStartTime + 100; diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/active/ActiveTraceRepositoryTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/active/ActiveTraceRepositoryTest.java index 4b180b5edab6..5701a6011181 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/active/ActiveTraceRepositoryTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/active/ActiveTraceRepositoryTest.java @@ -25,6 +25,7 @@ import com.navercorp.pinpoint.bootstrap.context.Trace; import com.navercorp.pinpoint.bootstrap.context.TraceContext; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.MockTraceContextFactory; import com.navercorp.pinpoint.profiler.context.id.DefaultTraceId; import com.navercorp.pinpoint.profiler.context.id.DefaultTransactionCounter; @@ -175,7 +176,7 @@ private ListenableFuture executeSampledContinuedTrace(Listenin @Override public TraceThreadTuple call() throws Exception { try { - TraceId agentId1 = new DefaultTraceId("agentId", 0L, id); + TraceId agentId1 = new DefaultTraceId(AgentId.of("agentId"), 0L, id); Trace agentId = traceContext.continueTraceObject(agentId1); return new TraceThreadTuple(agentId, Thread.currentThread().getId()); } finally { diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/compress/GrpcSpanProcessorV2Test.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/compress/GrpcSpanProcessorV2Test.java index 329c0badf59b..57a9e9b6440a 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/compress/GrpcSpanProcessorV2Test.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/compress/GrpcSpanProcessorV2Test.java @@ -17,12 +17,12 @@ package com.navercorp.pinpoint.profiler.context.compress; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.grpc.trace.PSpan; import com.navercorp.pinpoint.grpc.trace.PSpanChunk; import com.navercorp.pinpoint.grpc.trace.PSpanEvent; import com.navercorp.pinpoint.profiler.context.Span; import com.navercorp.pinpoint.profiler.context.SpanEvent; -import com.navercorp.pinpoint.profiler.context.grpc.GrpcSpanMessageConverter; import com.navercorp.pinpoint.profiler.context.grpc.config.SpanAutoUriGetter; import com.navercorp.pinpoint.profiler.context.grpc.mapper.AnnotationValueMapper; import com.navercorp.pinpoint.profiler.context.grpc.mapper.AnnotationValueMapperImpl; @@ -40,11 +40,9 @@ */ public class GrpcSpanProcessorV2Test { - private SpanProcessor spanProcessorProtoV2 = new GrpcSpanProcessorV2(); - - private AnnotationValueMapper annotationValueMapper = new AnnotationValueMapperImpl(); - private SpanMessageMapper mapper = new SpanMessageMapperImpl(annotationValueMapper, new SpanAutoUriGetter()); - private GrpcSpanMessageConverter converter = new GrpcSpanMessageConverter("agentId", (short) 1, spanProcessorProtoV2, mapper); + private final SpanProcessor spanProcessorProtoV2 = new GrpcSpanProcessorV2(); + private final AnnotationValueMapper annotationValueMapper = new AnnotationValueMapperImpl(); + private final SpanMessageMapper mapper = new SpanMessageMapperImpl(annotationValueMapper, new SpanAutoUriGetter()); @Test public void preProcess() { @@ -66,8 +64,8 @@ public void preProcess() { } private Span newSpan() { - TraceId traceId = new DefaultTraceId("agent", 1, 0); - TraceRoot traceRoot = TraceRoot.remote(traceId, "agent", 0, 3); + TraceId traceId = new DefaultTraceId(AgentId.of("agent"), 1, 0); + TraceRoot traceRoot = TraceRoot.remote(traceId, AgentId.of("agent"), 0, 3); return new Span(traceRoot); } diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/graph/DependencyGraph.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/graph/DependencyGraph.java index c68e5f03b1ab..b058f843478c 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/graph/DependencyGraph.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/graph/DependencyGraph.java @@ -25,6 +25,7 @@ import com.navercorp.pinpoint.bootstrap.DefaultAgentOption; import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.CodeSourceUtils; import com.navercorp.pinpoint.profiler.context.module.DefaultApplicationContext; import com.navercorp.pinpoint.profiler.context.module.InterceptorRegistryModule; @@ -83,7 +84,7 @@ private DefaultApplicationContext newApplicationContext() { Instrumentation instrumentation = mock(Instrumentation.class); AgentOption agentOption = new DefaultAgentOption(instrumentation, - "mockAgentId", "mockAgentName", "mockApplicationName", false, + AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", false, profilerConfig, Collections.emptyList(), Collections.emptyList()); InterceptorRegistryBinder interceptorRegistryBinder = new TestInterceptorRegistryBinder(); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcExceptionMetaDataConverterTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcExceptionMetaDataConverterTest.java index 3db6bc515499..fe3529d4287e 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcExceptionMetaDataConverterTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcExceptionMetaDataConverterTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.profiler.context.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.grpc.trace.PException; import com.navercorp.pinpoint.grpc.trace.PExceptionMetaData; import com.navercorp.pinpoint.grpc.trace.PStackTraceElement; @@ -36,7 +37,7 @@ class GrpcExceptionMetaDataConverterTest { private static TraceRoot newTraceRoot() { TraceRoot traceRoot = mock(TraceRoot.class); - final String agentId = "agent"; + final AgentId agentId = AgentId.of("agent"); final long agentStartTime = System.currentTimeMillis(); when(traceRoot.getTraceId()).thenReturn(new DefaultTraceId(agentId, agentStartTime, 0)); when(traceRoot.getTraceStartTime()).thenReturn(agentStartTime + 100); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterTest.java index fecd43b4468d..c2cf56feec08 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/grpc/GrpcSpanMessageConverterTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.profiler.context.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.IntStringValue; import com.navercorp.pinpoint.grpc.trace.PSpan; import com.navercorp.pinpoint.grpc.trace.PSpanChunk; @@ -42,7 +43,7 @@ class GrpcSpanMessageConverterTest { private static final Random random = new Random(); - private static final String agentId = "agent"; + private static final AgentId agentId = AgentId.of("agent"); private static final String parentAgentId = "agent-parent"; private static final short applicationServiceType = 0; private final SpanProcessor spanProcessorProtoV2 = new GrpcSpanProcessorV2(); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootTest.java index bdb1d085682a..03e05ddff1c8 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/id/LocalTraceRootTest.java @@ -3,6 +3,7 @@ import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder; import com.navercorp.pinpoint.bootstrap.context.SpanRecorder; import com.navercorp.pinpoint.bootstrap.context.Trace; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.CloseListener; import com.navercorp.pinpoint.profiler.context.DisableChildTrace; import com.navercorp.pinpoint.profiler.context.DisableTrace; @@ -12,9 +13,12 @@ import static org.mockito.Mockito.mock; public class LocalTraceRootTest { + + private static final AgentId AGENT_ID = AgentId.of("testAgent"); + @Test public void testGetScope() { - LocalTraceRoot traceRoot = TraceRoot.local("testAgent", 2, 1); + LocalTraceRoot traceRoot = TraceRoot.local(AGENT_ID, 2, 1); Trace trace = newTrace(traceRoot); Trace childTrace = newChildTrace(traceRoot); Assertions.assertNull(trace.addScope("empty")); @@ -23,7 +27,7 @@ public void testGetScope() { @Test public void testAddScope() { - LocalTraceRoot traceRoot = TraceRoot.local("testAgent", 2, 1); + LocalTraceRoot traceRoot = TraceRoot.local(AGENT_ID, 2, 1); Trace trace = newTrace(traceRoot); Trace childTrace = newChildTrace(traceRoot); @@ -35,7 +39,7 @@ public void testAddScope() { @Test public void testSampled() { - LocalTraceRoot traceRoot = TraceRoot.local("testAgent", 2, 1); + LocalTraceRoot traceRoot = TraceRoot.local(AGENT_ID, 2, 1); Trace trace = newTrace(traceRoot); Trace childTrace = newChildTrace(traceRoot); @@ -45,7 +49,7 @@ public void testSampled() { @Test public void testSpanRecorder() { - LocalTraceRoot traceRoot = TraceRoot.local("testAgent", 2, 1); + LocalTraceRoot traceRoot = TraceRoot.local(AGENT_ID, 2, 1); Trace trace = newTrace(traceRoot); Trace childTrace = newChildTrace(traceRoot); SpanRecorder spanRecorder = trace.getSpanRecorder(); @@ -57,7 +61,7 @@ public void testSpanRecorder() { @Test public void testCurrentSpanEventRecorder() { - LocalTraceRoot traceRoot = TraceRoot.local("testAgent", 2, 1); + LocalTraceRoot traceRoot = TraceRoot.local(AGENT_ID, 2, 1); Trace trace = newTrace(traceRoot); Trace childTrace = newChildTrace(traceRoot); SpanEventRecorder spanEventRecorder = trace.currentSpanEventRecorder(); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/module/DefaultApplicationContextTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/module/DefaultApplicationContextTest.java index bf0ab6d93dea..bb756fb9f8be 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/module/DefaultApplicationContextTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/module/DefaultApplicationContextTest.java @@ -26,6 +26,7 @@ import com.navercorp.pinpoint.bootstrap.DefaultAgentOption; import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.AgentInfoSender; import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder; import com.navercorp.pinpoint.profiler.util.TestInterceptorRegistryBinder; @@ -89,7 +90,7 @@ private DefaultApplicationContext newApplicationContext() { // when(profilerConfig.getTransportModule()).thenReturn("GRPC"); Instrumentation instrumentation = mock(Instrumentation.class); - AgentOption agentOption = new DefaultAgentOption(instrumentation, "mockAgentId", "mockAgentName", "mockApplicationName", false, + AgentOption agentOption = new DefaultAgentOption(instrumentation, AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", false, profilerConfig, Collections.emptyList(), Collections.emptyList()); InterceptorRegistryBinder interceptorRegistryBinder = new TestInterceptorRegistryBinder(); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageTest.java index e5b6704dded6..ef8087d0a2ea 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/context/storage/BufferedStorageTest.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.profiler.context.storage; import com.navercorp.pinpoint.bootstrap.context.TraceId; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.profiler.context.DefaultSpanChunkFactory; import com.navercorp.pinpoint.profiler.context.Span; import com.navercorp.pinpoint.profiler.context.SpanChunkFactory; @@ -30,7 +31,7 @@ public class BufferedStorageTest { - private final String agentId = "agentId"; + private final AgentId agentId = AgentId.of("agentId"); private final long agentStartTime = System.currentTimeMillis(); private final CountingDataSender countingDataSender = new CountingDataSender(); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java index 5d559a6a9ad1..3a697a5494f1 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/monitor/CollectJobTest.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.profiler.monitor; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.DataSender; import com.navercorp.pinpoint.profiler.monitor.collector.AgentStatMetricCollector; import com.navercorp.pinpoint.profiler.monitor.metric.AgentStatMetricSnapshot; @@ -39,7 +40,7 @@ public void run() throws Exception { DataSender dataSender = mock(DataSender.class); - CollectJob job = new CollectJob(dataSender, "agent", 0, agentStatMetricCollector, 1); + CollectJob job = new CollectJob(dataSender, AgentId.of("agent"), 0, agentStatMetricCollector, 1); job.run(); Mockito.verify(dataSender).send(any(AgentStatMetricSnapshotBatch.class)); diff --git a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/grpc/AgentGrpcDataSenderTestMain.java b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/grpc/AgentGrpcDataSenderTestMain.java index 7d37c71b2532..840dbc0be752 100644 --- a/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/grpc/AgentGrpcDataSenderTestMain.java +++ b/agent-module/profiler/src/test/java/com/navercorp/pinpoint/profiler/sender/grpc/AgentGrpcDataSenderTestMain.java @@ -18,6 +18,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.bootstrap.context.ServerMetaData; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.message.MessageConverter; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.AgentHeaderFactory; @@ -46,9 +47,10 @@ import java.util.concurrent.TimeUnit; public class AgentGrpcDataSenderTestMain { - private static final String AGENT_ID = "mockAgentId"; + private static final AgentId AGENT_ID = AgentId.of("mockAgentId"); private static final String AGENT_NAME = "mockAgentName"; private static final String APPLICATION_NAME = "mockApplicationName"; + private static final String SERVICE_NAME = "mockServiceName"; private static final long START_TIME = System.currentTimeMillis(); private static final int SERVICE_TYPE = ServiceType.UNDEFINED.getCode(); private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); @@ -58,7 +60,7 @@ public class AgentGrpcDataSenderTestMain { public void request() throws Exception { MetaDataMapper mapper = new MetaDataMapperImpl(); MessageConverter messageConverter = new GrpcMetadataMessageConverter(mapper); - HeaderFactory headerFactory = new AgentHeaderFactory(AGENT_ID, AGENT_NAME, APPLICATION_NAME, SERVICE_TYPE, START_TIME); + HeaderFactory headerFactory = new AgentHeaderFactory(AGENT_ID, AGENT_NAME, APPLICATION_NAME, SERVICE_NAME, SERVICE_TYPE, START_TIME); DnsExecutorServiceProvider dnsExecutorServiceProvider = new DnsExecutorServiceProvider(); GrpcNameResolverProvider grpcNameResolverProvider = new GrpcNameResolverProvider(dnsExecutorServiceProvider); @@ -82,7 +84,7 @@ public void request() throws Exception { } private AgentInfo newAgentInfo() { - AgentInformation agentInformation = new DefaultAgentInformation(AGENT_ID, AGENT_NAME, APPLICATION_NAME, true, START_TIME, 99, "", "", ServiceType.TEST_STAND_ALONE, "1.0", "1.0"); + AgentInformation agentInformation = new DefaultAgentInformation(AGENT_ID, AGENT_NAME, APPLICATION_NAME, SERVICE_NAME, true, START_TIME, 99, "", "", ServiceType.TEST_STAND_ALONE, "1.0", "1.0"); JvmInformation jvmInformation = new JvmInformation("1.0", JvmGcType.G1); ServerMetaData serverInfo = new DefaultServerMetaData("serverInfo", Collections.emptyList(), Collections.emptyMap(), Collections.emptyList()); return new AgentInfo(agentInformation, serverInfo, jvmInformation); diff --git a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplate.java b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplate.java index 0c1e5e2ae53b..90c7668e558b 100644 --- a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplate.java +++ b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplate.java @@ -48,7 +48,7 @@ public AlarmMailTemplate(AlarmCheckerInterface checker, String pinpointUrl, Stri public String createSubject() { RuleInterface rule = checker.getRule(); - return String.format("[PINPOINT-%s] %s Alarm for %s Service. #%d", batchEnv, rule.getCheckerName(), rule.getApplicationId(), sequenceCount); + return String.format("[PINPOINT-%s] %s Alarm for %s Service. #%d", batchEnv, rule.getCheckerName(), rule.getApplicationName(), sequenceCount); } public String getTime() { @@ -67,21 +67,18 @@ public String getTime() { public String createBody() { RuleInterface rule = checker.getRule(); - return newBody(createSubject(), rule.getCheckerName(), rule.getApplicationId(), rule.getServiceType(), getTime()); + return newBody(createSubject(), rule.getCheckerName(), rule.getApplicationName(), rule.getServiceType(), getTime()); } private String newBody(String subject, String rule, String applicationId, String serviceType, String currentTime) { - StringBuilder body = new StringBuilder(); - body.append("").append(subject).append(""); - body.append(LINE_FEED); - body.append(LINE_FEED); - body.append(String.format("Rule : %s", rule)); - body.append(LINE_FEED); - body.append(checker.getEmailMessage(pinpointUrl, applicationId, serviceType, currentTime)); - body.append(String.format(LINK_FORMAT, pinpointUrl)); - body.append(LINE_FEED); - body.append(String.format(SCATTER_CHART_LINK_FORMAT, pinpointUrl, applicationId, serviceType, currentTime, applicationId)); - - return body.toString(); + return "" + subject + "" + + LINE_FEED + + LINE_FEED + + String.format("Rule : %s", rule) + + LINE_FEED + + checker.getEmailMessage(pinpointUrl, applicationId, serviceType, currentTime) + + String.format(LINK_FORMAT, pinpointUrl) + + LINE_FEED + + String.format(SCATTER_CHART_LINK_FORMAT, pinpointUrl, applicationId, serviceType, currentTime, applicationId); } } diff --git a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayload.java b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayload.java index b3a35941b911..664884a0b573 100644 --- a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayload.java +++ b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayload.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.navercorp.pinpoint.batch.alarm.checker.AlarmCheckerInterface; -import com.navercorp.pinpoint.batch.alarm.checker.PinotAlarmCheckerInterface; /** * @author Jongjin.Bae @@ -28,7 +27,7 @@ public class WebhookPayload { private final String pinpointUrl; private final String batchEnv; - private final String applicationId; + private final String applicationName; private final String serviceType; private final String checkerName; private final String checkerType; @@ -43,7 +42,7 @@ public WebhookPayload(String pinpointUrl, String batchEnv, AlarmCheckerInterface this.pinpointUrl = pinpointUrl; this.batchEnv = batchEnv; - this.applicationId = checker.getRule().getApplicationId(); + this.applicationName = checker.getRule().getApplicationName(); this.serviceType = checker.getRule().getServiceType(); this.checkerName = checker.getRule().getCheckerName(); this.checkerType = checker.getCheckerType(); @@ -63,8 +62,8 @@ public String getBatchEnv() { return batchEnv; } - public String getApplicationId() { - return applicationId; + public String getApplicationName() { + return applicationName; } public String getServiceType() { @@ -108,7 +107,7 @@ public String toString() { return "WebhookPayload{" + "pinpointUrl='" + pinpointUrl + '\'' + ", batchEnv='" + batchEnv + '\'' + - ", applicationId='" + applicationId + '\'' + + ", applicationName='" + applicationName + '\'' + ", serviceType='" + serviceType + '\'' + ", checkerName='" + checkerName + '\'' + ", checkerType='" + checkerType + '\'' + diff --git a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayloadSerializer.java b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayloadSerializer.java index c30b3af8747f..0ffcda8cd09a 100644 --- a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayloadSerializer.java +++ b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/sender/payload/WebhookPayloadSerializer.java @@ -29,30 +29,30 @@ public class WebhookPayloadSerializer extends JsonSerializer { @Override - public void serialize(WebhookPayload webhookPayload, JsonGenerator jgen, SerializerProvider serializers) throws IOException { - jgen.writeStartObject(); + public void serialize(WebhookPayload webhookPayload, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); - jgen.writeStringField("pinpointUrl", webhookPayload.getPinpointUrl()); - jgen.writeStringField("batchEnv", webhookPayload.getBatchEnv()); - jgen.writeStringField("applicationId", webhookPayload.getApplicationId()); - jgen.writeStringField("serviceType", webhookPayload.getServiceType()); - jgen.writeObjectField("userGroup", webhookPayload.getUserGroup()); + gen.writeStringField("pinpointUrl", webhookPayload.getPinpointUrl()); + gen.writeStringField("batchEnv", webhookPayload.getBatchEnv()); + gen.writeStringField("applicationId", webhookPayload.getApplicationName()); + gen.writeStringField("serviceType", webhookPayload.getServiceType()); + gen.writeObjectField("userGroup", webhookPayload.getUserGroup()); - writeChecker(webhookPayload, jgen); + writeChecker(webhookPayload, gen); - jgen.writeStringField("unit", webhookPayload.getUnit()); + gen.writeStringField("unit", webhookPayload.getUnit()); Number threshold = webhookPayload.getThreshold(); if (threshold instanceof Integer integer) { - jgen.writeNumberField("threshold", integer); + gen.writeNumberField("threshold", integer); } else if (threshold instanceof BigDecimal bigDecimal){ - jgen.writeNumberField("threshold", bigDecimal); + gen.writeNumberField("threshold", bigDecimal); } else { throw new IOException("threshold type should be either Integer or BigDecimal"); } - jgen.writeStringField("notes", webhookPayload.getNotes()); - jgen.writeNumberField("sequenceCount", webhookPayload.getSequenceCount()); + gen.writeStringField("notes", webhookPayload.getNotes()); + gen.writeNumberField("sequenceCount", webhookPayload.getSequenceCount()); - jgen.writeEndObject(); + gen.writeEndObject(); } private void writeChecker(WebhookPayload webhookPayload, JsonGenerator jgen) throws IOException { diff --git a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/web/vo/RuleInterface.java b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/web/vo/RuleInterface.java index 8d4a87f1d1c2..e803d5565370 100644 --- a/batch-alarmsender/src/main/java/com/navercorp/pinpoint/web/vo/RuleInterface.java +++ b/batch-alarmsender/src/main/java/com/navercorp/pinpoint/web/vo/RuleInterface.java @@ -2,7 +2,7 @@ public interface RuleInterface { String getCheckerName(); - String getApplicationId(); + String getApplicationName(); String getServiceType(); Number getThreshold(); String getNotes(); diff --git a/batch-alarmsender/src/test/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplateTest.java b/batch-alarmsender/src/test/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplateTest.java index 7f512e51bd69..65e41e58675d 100644 --- a/batch-alarmsender/src/test/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplateTest.java +++ b/batch-alarmsender/src/test/java/com/navercorp/pinpoint/batch/alarm/sender/AlarmMailTemplateTest.java @@ -42,7 +42,7 @@ class AlarmMailTemplateTest { @Test public void newBodyTest() { when(rule.getCheckerName()).thenReturn("checkerName"); - when(rule.getApplicationId()).thenReturn("applicaitonId"); + when(rule.getApplicationName()).thenReturn("applicationName"); when(rule.getServiceType()).thenReturn("TOMCAT"); when(checker.getRule()).thenReturn(rule); when(checker.getEmailMessage(anyString(), anyString(), anyString(), anyString())).thenReturn("ERROR RATE is 25 % (Threshold: 10 %)
"); diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessor.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessor.java index 4d2ef3f77800..12608fcbfeb7 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessor.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessor.java @@ -20,14 +20,16 @@ import com.navercorp.pinpoint.batch.alarm.checker.AlarmChecker; import com.navercorp.pinpoint.batch.alarm.collector.DataCollector; import com.navercorp.pinpoint.batch.alarm.vo.AppAlarmChecker; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.web.alarm.CheckerCategory; import com.navercorp.pinpoint.web.alarm.DataCollectorCategory; import com.navercorp.pinpoint.web.alarm.vo.Rule; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AgentInfoService; import com.navercorp.pinpoint.web.service.AlarmService; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import jakarta.annotation.Nonnull; import org.springframework.batch.item.ItemProcessor; @@ -51,7 +53,7 @@ public class AlarmProcessor implements ItemProcessor> getAlarmCheckers(Application application) { - List rules = alarmService.selectRuleByApplicationId(application.getName()); + List rules = alarmService.selectRuleByApplicationId(application.name()); long now = System.currentTimeMillis(); Supplier> agentIds = getAgentIdsSupplier(application, now); @@ -102,13 +104,13 @@ private List> getAlarmCheckers(Application application) { private Supplier> getAgentIdsSupplier(Application application, long now) { Range range = Range.between(now - activeDuration, now); - return Suppliers.memoize(() -> fetchActiveAgents(application.getName(), range)); + return Suppliers.memoize(() -> fetchActiveAgents(application.id(), range)); } - private List fetchActiveAgents(String applicationId, Range activeRange) { - return applicationIndexDao.selectAgentIds(applicationId) + private List fetchActiveAgents(ApplicationId applicationId, Range activeRange) { + return this.applicationService.getAgents(applicationId) .stream() - .filter(id -> agentInfoService.isActiveAgent(id, activeRange)) + .filter(id -> agentInfoService.isActiveAgent(AgentId.of(id), activeRange)) .toList(); } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmReader.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmReader.java index 990fcba5b56a..eb1002b62e08 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmReader.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/AlarmReader.java @@ -16,15 +16,15 @@ package com.navercorp.pinpoint.batch.alarm; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AlarmService; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; +import jakarta.annotation.Nonnull; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.item.ItemReader; -import jakarta.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -36,13 +36,13 @@ */ public class AlarmReader implements ItemReader, StepExecutionListener { - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; private final AlarmService alarmService; private Queue applicationQueue; - public AlarmReader(ApplicationIndexDao applicationIndexDao, AlarmService alarmService) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + public AlarmReader(ApplicationService applicationService, AlarmService alarmService) { + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.alarmService = Objects.requireNonNull(alarmService, "alarmService"); } @@ -56,12 +56,12 @@ public void beforeStep(@Nonnull StepExecution stepExecution) { } private List fetchApplications() { - List applications = applicationIndexDao.selectAllApplicationNames(); + List applications = this.applicationService.getApplications(); List validApplicationIds = alarmService.selectApplicationId(); List validApplications = new ArrayList<>(applications.size()); for (Application application: applications) { - if (validApplicationIds.contains(application.getName())) { + if (validApplicationIds.contains(application.name())) { validApplications.add(application); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/AlarmChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/AlarmChecker.java index fce56abf9b3b..f12ac693b28d 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/AlarmChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/AlarmChecker.java @@ -85,12 +85,12 @@ public String getUnit() { public void check() { dataCollector.collect(); detected = decideResult(getDetectedValue()); - logger.info("{} result is {} for application ({}). value is {}. (threshold : {}).", this.getClass().getSimpleName(), detected, rule.getApplicationId(), getDetectedValue(), rule.getThreshold()); + logger.info("{} result is {} for application ({}). value is {}. (threshold : {}).", this.getClass().getSimpleName(), detected, rule.getApplicationName(), getDetectedValue(), rule.getThreshold()); } public List getSmsMessage() { List messages = new ArrayList<>(); - messages.add(String.format("[PINPOINT Alarm - %s] %s is %s%s (Threshold : %s%s)", rule.getApplicationId(), rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit)); + messages.add(String.format("[PINPOINT Alarm - %s] %s is %s%s (Threshold : %s%s)", rule.getApplicationName(), rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit)); return messages; } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorCountToCalleeChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorCountToCalleeChecker.java index 86c9ca95dad4..76bbffde5997 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorCountToCalleeChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorCountToCalleeChecker.java @@ -37,7 +37,8 @@ protected Long getDetectedValue() { @Override public String getEmailMessage(String pinpointUrl, String applicationId, String serviceType, String currentTime) { - return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationId(), rule.getNotes()); + return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", + rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationName(), rule.getNotes()); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorRateToCalleeChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorRateToCalleeChecker.java index f69363ab04e2..88df10275dd8 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorRateToCalleeChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/ErrorRateToCalleeChecker.java @@ -38,7 +38,8 @@ protected Long getDetectedValue() { @Override public String getEmailMessage(String pinpointUrl, String applicationId, String serviceType, String currentTime) { - return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationId(), rule.getNotes()); + return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", + rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationName(), rule.getNotes()); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowCountToCalleeChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowCountToCalleeChecker.java index 33c1701ca06a..bf7eeadc355c 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowCountToCalleeChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowCountToCalleeChecker.java @@ -37,7 +37,8 @@ protected Long getDetectedValue() { @Override public String getEmailMessage(String pinpointUrl, String applicationId, String serviceType, String currentTime) { - return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationId(), rule.getNotes()); + return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", + rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationName(), rule.getNotes()); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowRateToCalleeChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowRateToCalleeChecker.java index b5961258a101..4f3bbf0a4575 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowRateToCalleeChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/checker/SlowRateToCalleeChecker.java @@ -32,13 +32,14 @@ public SlowRateToCalleeChecker(DataCollector dataCollector, Rule rule) { @Override protected Long getDetectedValue() { - String calleName = rule.getNotes(); - return ((MapStatisticsCallerDataCollector)dataCollector).getCountRate(calleName, DataCategory.SLOW_RATE); + String calleeName = rule.getNotes(); + return ((MapStatisticsCallerDataCollector)dataCollector).getCountRate(calleeName, DataCategory.SLOW_RATE); } @Override public String getEmailMessage(String pinpointUrl, String applicationId, String serviceType, String currentTime) { - return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationId(), rule.getNotes()); + return String.format("%s value is %s%s during the past 5 mins.(Threshold : %s%s) %s For From '%s' To '%s'.
", + rule.getCheckerName(), getDetectedValue(), unit, rule.getThreshold(), unit, rule.getCheckerName(), rule.getApplicationName(), rule.getNotes()); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/MapStatisticsCallerDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/MapStatisticsCallerDataCollector.java index f4654bea2198..2563e92a746e 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/MapStatisticsCallerDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/MapStatisticsCallerDataCollector.java @@ -62,15 +62,15 @@ public void collect() { LinkCallDataMap linkCallDataMap = linkData.getLinkCallDataMap(); for (LinkCallData linkCallData : linkCallDataMap.getLinkDataList()) { - calleeStatMap.put(linkCallData.getTarget().getName(), linkCallData); + calleeStatMap.put(linkCallData.getTarget().name(), linkCallData); } } init.set(true); } - public long getCount(String calleName, DataCategory dataCategory) { - final LinkCallData linkCallData = calleeStatMap.get(calleName); + public long getCount(String calleeName, DataCategory dataCategory) { + final LinkCallData linkCallData = calleeStatMap.get(calleeName); if (linkCallData == null) { return 0; } @@ -102,8 +102,8 @@ public long getCount(String calleName, DataCategory dataCategory) { } - public long getCountRate(String calleName, DataCategory dataCategory) { - final LinkCallData linkCallData = calleeStatMap.get(calleName); + public long getCountRate(String calleeName, DataCategory dataCategory) { + final LinkCallData linkCallData = calleeStatMap.get(calleeName); if (linkCallData == null) { return 0; } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/ResponseTimeDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/ResponseTimeDataCollector.java index a3a22f6c09ba..16f860ea1467 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/ResponseTimeDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/ResponseTimeDataCollector.java @@ -36,7 +36,7 @@ public class ResponseTimeDataCollector extends DataCollector { private final MapResponseDao responseDao; private final long timeSlotEndTime; private final long slotInterval; - private final AtomicBoolean init =new AtomicBoolean(false); // need to consider a race condition when checkers start simultaneously. + private final AtomicBoolean init = new AtomicBoolean(false); // need to consider a race condition when checkers start simultaneously. private long fastCount = 0; private long normalCount = 0; diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/DataSourceDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/DataSourceDataCollector.java index 2e63f85d2116..5dc82c48b893 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/DataSourceDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/DataSourceDataCollector.java @@ -84,7 +84,7 @@ public void collect() { for (TagInformation tagInformation : tagInformationList) { CompletableFuture> futureAgent = alarmDao - .selectAvgGroupByField(application.getName(), agentId, METRIC_NAME, fieldList, tagInformation.tags(), range); + .selectAvgGroupByField(application.name(), agentId, METRIC_NAME, fieldList, tagInformation.tags(), range); queryResults.add(new QueryResult<>(futureAgent, tagInformation)); } } @@ -123,11 +123,11 @@ public void collect() { agentDataSourceConnectionUsageRateMap.add(tagInformation.agentId(), dataSourceAlarmVO); } } catch (RuntimeException e) { - logger.error("Fail to get agent datasource data. applicationName : {}", application.getName(), e); + logger.error("Fail to get agent datasource data. applicationName : {}", application.name(), e); } catch (ExecutionException e) { - logger.error("Fail to get agent datasource data with ExecutionException. applicationName : {}", application.getName(), e); + logger.error("Fail to get agent datasource data with ExecutionException. applicationName : {}", application.name(), e); } catch (InterruptedException e) { - logger.error("Fail to get agent datasource data with InterruptedException. applicationName : {}", application.getName(), e); + logger.error("Fail to get agent datasource data with InterruptedException. applicationName : {}", application.name(), e); } } @@ -141,7 +141,7 @@ private Map> getAgentTagInformation(Range range) th for (Tag jdbcUrlTag : jdbcUrlList) { List tagList = List.of(jdbcUrlTag); - CompletableFuture> futureTagInformation = alarmDao.getTagInfoContainedSpecificTag(application.getName(), agentId, METRIC_NAME, FIELD_ACTIVE_CONNECTION, tagList, range); + CompletableFuture> futureTagInformation = alarmDao.getTagInfoContainedSpecificTag(application.name(), agentId, METRIC_NAME, FIELD_ACTIVE_CONNECTION, tagList, range); queryResults.add(new QueryResult<>(futureTagInformation, agentId)); } } @@ -163,7 +163,7 @@ private Map> getAgentTagInformation(Range range) th errorCount++; if (errorCount > 2) { - logger.error("Fail to get agent tag information. applicationName : {}, agentId : {}", application.getName(), agentId, e); + logger.error("Fail to get agent tag information. applicationName : {}, agentId : {}", application.name(), agentId, e); throw e; } } @@ -176,7 +176,7 @@ private Map> distinctJdbUrlForAgent(Range range) throws Execut List> queryResults = new ArrayList<>(); for (String agentId : agentIds) { - CompletableFuture> future = alarmDao.selectTagInfo(application.getName(), agentId, METRIC_NAME, FIELD_ACTIVE_CONNECTION, range); + CompletableFuture> future = alarmDao.selectTagInfo(application.name(), agentId, METRIC_NAME, FIELD_ACTIVE_CONNECTION, range); queryResults.add(new QueryResult<>(future, agentId)); } @@ -201,7 +201,7 @@ private Map> distinctJdbUrlForAgent(Range range) throws Execut } catch (Exception e) { errorCount++; if (errorCount > 2) { - logger.error("Fail to get agent jdbcUrl. applicationName : {}, agentId : {}", application.getName(), agentId, e); + logger.error("Fail to get agent jdbcUrl. applicationName : {}, agentId : {}", application.name(), agentId, e); throw e; } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/FileDescriptorDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/FileDescriptorDataCollector.java index 98e988e90d9d..f12a25d26c03 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/FileDescriptorDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/FileDescriptorDataCollector.java @@ -54,7 +54,7 @@ public FileDescriptorDataCollector(DataCollectorCategory dataCollectorCategory, @Override public void collect() { Range range = Range.between(timeSlotEndTime - slotInterval, timeSlotEndTime); - List agentUsageList = alarmDao.selectAvg(application.getName(), METRIC_NAME, FIELD_NAME, range); + List agentUsageList = alarmDao.selectAvg(application.name(), METRIC_NAME, FIELD_NAME, range); for (AgentUsage agentUsage : agentUsageList) { agentFileDescriptorCount.put(agentUsage.getAgentId(), agentUsage.getValue().longValue()); diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/HeapDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/HeapDataCollector.java index 10bcee115875..faeb1b649c33 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/HeapDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/HeapDataCollector.java @@ -57,7 +57,7 @@ public HeapDataCollector(DataCollectorCategory dataCollectorCategory, AlarmDao a @Override public void collect() { Range range = Range.between(timeSlotEndTime - slotInterval, timeSlotEndTime); - List agentFieldUsageList = alarmDao.selectSumGroupByField(application.getName(), METRIC_NAME, fieldList, range); + List agentFieldUsageList = alarmDao.selectSumGroupByField(application.name(), METRIC_NAME, fieldList, range); Map agentHeapUsageMap = new HashMap<>(); for(AgentFieldUsage agentFieldUsage : agentFieldUsageList) { diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/JvmCpuDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/JvmCpuDataCollector.java index 5ad6a7089a41..365830949221 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/JvmCpuDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/JvmCpuDataCollector.java @@ -56,7 +56,7 @@ public JvmCpuDataCollector(DataCollectorCategory dataCollectorCategory, AlarmDao @Override public void collect() { Range range = Range.between(timeSlotEndTime - slotInterval, timeSlotEndTime); - List agentUsageCountList = alarmDao.selectSumCount(application.getName(), METRIC_NAME, FIELD_NAME, range); + List agentUsageCountList = alarmDao.selectSumCount(application.name(), METRIC_NAME, FIELD_NAME, range); for (AgentUsageCount agentUsageCount : agentUsageCountList) { long jvmCpuUsagePercent = calculatePercent(agentUsageCount.getValue().longValue(), 100L * agentUsageCount.getCountValue().longValue()); diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/SystemCpuDataCollector.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/SystemCpuDataCollector.java index a4924e06a404..56d5fc8deef2 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/SystemCpuDataCollector.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/collector/pinot/SystemCpuDataCollector.java @@ -54,7 +54,7 @@ public SystemCpuDataCollector(DataCollectorCategory dataCollectorCategory, Alarm @Override public void collect() { Range range = Range.between(timeSlotEndTime - slotInterval, timeSlotEndTime); - List agentUsageCountList = alarmDao.selectSumCount(application.getName(), METRIC_NAME, FIELD_NAME, range); + List agentUsageCountList = alarmDao.selectSumCount(application.name(), METRIC_NAME, FIELD_NAME, range); for (AgentUsageCount agentUsageCount : agentUsageCountList) { long jvmCpuUsagePercent = calculatePercent(agentUsageCount.getValue().longValue(), 100L * agentUsageCount.getCountValue().longValue()); diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/AppAlarmChecker.java b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/AppAlarmChecker.java index f7a3b310bd3f..f4c7e47c5d93 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/AppAlarmChecker.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/alarm/vo/AppAlarmChecker.java @@ -30,7 +30,7 @@ public class AppAlarmChecker { public AppAlarmChecker(List> children) { this.children = haveSameApplication(children); - this.applicationId = this.children.get(0).getRule().getApplicationId(); + this.applicationId = this.children.get(0).getRule().getApplicationName(); } private List> haveSameApplication(List> children) { @@ -38,10 +38,10 @@ private List> haveSameApplication(List> children throw new IllegalArgumentException("children should not be empty"); } - final String applicationName = children.get(0).getRule().getApplicationId(); + final String applicationName = children.get(0).getRule().getApplicationName(); for (AlarmChecker child : children) { - if (!applicationName.equals(child.getRule().getApplicationId())) { - throw new IllegalArgumentException("All children should have the same application: " + applicationName + " != " + child.getRule().getApplicationId()); + if (!applicationName.equals(child.getRule().getApplicationName())) { + throw new IllegalArgumentException("All children should have the same application: " + applicationName + " != " + child.getRule().getApplicationName()); } } return children; diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountProcessor.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountProcessor.java index 947450029b33..390d6c63d778 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountProcessor.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountProcessor.java @@ -16,34 +16,36 @@ package com.navercorp.pinpoint.batch.job; import com.navercorp.pinpoint.batch.common.BatchProperties; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AgentInfoService; +import com.navercorp.pinpoint.web.service.ApplicationService; +import jakarta.annotation.Nonnull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.batch.item.ItemProcessor; -import jakarta.annotation.Nonnull; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * @author youngjin.kim2 */ -public class AgentCountProcessor implements ItemProcessor { +public class AgentCountProcessor implements ItemProcessor { private final Logger logger = LogManager.getLogger(this.getClass()); - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; private final AgentInfoService agentInfoService; private final long duration; public AgentCountProcessor( - ApplicationIndexDao applicationIndexDao, + ApplicationService applicationService, AgentInfoService agentInfoService, BatchProperties batchProperties ) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.agentInfoService = Objects.requireNonNull(agentInfoService, "agentInfoService"); long durationDays = batchProperties.getCleanupInactiveAgentsDurationDays(); @@ -51,16 +53,17 @@ public AgentCountProcessor( } @Override - public Integer process(@Nonnull String applicationName) { - long localCount = applicationIndexDao.selectAgentIds(applicationName) + public Integer process(@Nonnull ApplicationId applicationId) { + long localCount = applicationService.getAgents(applicationId) .stream() + .map(AgentId::of) .filter(this::isActive) .count(); - logger.info("Application {} has {} agents", applicationName, localCount); + logger.info("Application {} has {} agents", applicationId, localCount); return Math.toIntExact(localCount); } - private boolean isActive(String agentId) { + private boolean isActive(AgentId agentId) { long now = System.currentTimeMillis(); Range range = Range.between(now - duration, now); return agentInfoService.isActiveAgent(agentId, range); diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountReader.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountReader.java index 807a2a1a920d..a9c8caf21ce3 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountReader.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentCountReader.java @@ -16,7 +16,8 @@ package com.navercorp.pinpoint.batch.job; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import jakarta.annotation.Nonnull; import org.springframework.batch.core.ExitStatus; @@ -32,21 +33,21 @@ /** * @author youngjin.kim2 */ -public class AgentCountReader implements ItemReader, StepExecutionListener { +public class AgentCountReader implements ItemReader, StepExecutionListener { - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; - private Queue applicationNameQueue; + private Queue applicationNameQueue; - public AgentCountReader(ApplicationIndexDao applicationIndexDao) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + public AgentCountReader(ApplicationService applicationService) { + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); } @Override public void beforeStep(@Nonnull StepExecution stepExecution) { - List applicationNames = applicationIndexDao.selectAllApplicationNames() + List applicationNames = applicationService.getApplications() .stream() - .map(Application::getName) + .map(Application::id) .toList(); this.applicationNameQueue = new ConcurrentLinkedQueue<>(applicationNames); } @@ -57,7 +58,7 @@ public ExitStatus afterStep(@Nonnull StepExecution stepExecution) { } @Override - public String read() { + public ApplicationId read() { return applicationNameQueue.poll(); } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentRemover.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentRemover.java index a425a3d40d48..eef35cab5431 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentRemover.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/AgentRemover.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.batch.job; import com.navercorp.pinpoint.batch.service.BatchAgentService; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.cluster.ClusterKey; import jakarta.annotation.Nonnull; import org.apache.logging.log4j.LogManager; @@ -25,6 +26,7 @@ import org.springframework.batch.item.ItemWriter; import java.util.Objects; +import java.util.UUID; /** * @author youngjin.kim2 @@ -44,7 +46,8 @@ public void write(@Nonnull Chunk serAgentKeys) throws Exceptio for (String serKey: serAgentKeys) { logger.info("Removing agent: {}", serKey); ClusterKey key = ClusterKey.parse(serKey); - this.agentService.remove(key.getApplicationName(), key.getAgentId()); + UUID applicationIdValue = UUID.fromString(key.getApplicationName()); + this.agentService.remove(ApplicationId.of(applicationIdValue), key.getAgentId()); } } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationCleaningProcessor.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationCleaningProcessor.java index 4b62a869a6b8..c0c9a6c76013 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationCleaningProcessor.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationCleaningProcessor.java @@ -19,6 +19,8 @@ import com.navercorp.pinpoint.batch.service.BatchAgentService; import com.navercorp.pinpoint.batch.service.BatchApplicationService; import com.navercorp.pinpoint.batch.vo.CleanTarget; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.cluster.ClusterKey; import com.navercorp.pinpoint.common.server.util.time.Range; import jakarta.annotation.Nonnull; @@ -34,61 +36,61 @@ /** * @author youngjin.kim2 */ -public class ApplicationCleaningProcessor implements ItemProcessor> { +public class ApplicationCleaningProcessor implements ItemProcessor> { private static final Logger logger = LogManager.getLogger(ApplicationCleaningProcessor.class); private final BatchAgentService agentService; - private final BatchApplicationService applicationService; + private final BatchApplicationService batchApplicationService; private final Duration emptyDurationThreshold; public ApplicationCleaningProcessor( BatchAgentService agentService, - BatchApplicationService applicationService, + BatchApplicationService batchApplicationService, Duration emptyDurationThreshold ) { this.agentService = Objects.requireNonNull(agentService, "agentService"); - this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); + this.batchApplicationService = Objects.requireNonNull(batchApplicationService, "batchApplicationService"); this.emptyDurationThreshold = Objects.requireNonNull(emptyDurationThreshold, "emptyDurationThreshold"); } @Override - public List process(@Nonnull String applicationName) throws Exception { - logger.info("Processing application: {}", applicationName); + public List process(@Nonnull ApplicationId applicationId) throws Exception { + logger.info("Processing application: {}", applicationId); Range range = getRange(); - List agentIds = getAgents(applicationName); + List agentIds = getAgents(applicationId); List targets = new ArrayList<>(agentIds.size() + 1); - for (String agentId: agentIds) { + for (AgentId agentId: agentIds) { if (isAgentTarget(agentId, range)) { - String agentKey = ClusterKey.compose(applicationName, agentId, -1); + String agentKey = ClusterKey.compose(applicationId.toString(), AgentId.unwrap(agentId), -1); targets.add(new CleanTarget(CleanTarget.TYPE_AGENT, agentKey)); } } - if (targets.size() == agentIds.size() && isApplicationTarget(applicationName)) { - targets.add(new CleanTarget(CleanTarget.TYPE_APPLICATION, applicationName)); + if (targets.size() == agentIds.size() && isApplicationTarget(applicationId)) { + targets.add(new CleanTarget(CleanTarget.TYPE_APPLICATION, applicationId.toString())); } if (targets.isEmpty()) { return null; } - logger.info("Cleaning application {}: {}", applicationName, targets); + logger.info("Cleaning application {}: {}", applicationId, targets); return targets; } - private boolean isApplicationTarget(String applicationName) { - return !this.applicationService.isActive(applicationName, this.emptyDurationThreshold); + private boolean isApplicationTarget(ApplicationId applicationId) { + return !this.batchApplicationService.isActive(applicationId, this.emptyDurationThreshold); } - private boolean isAgentTarget(String agentId, Range range) { + private boolean isAgentTarget(AgentId agentId, Range range) { return !this.agentService.isActive(agentId, range); } - private List getAgents(String applicationName) { - return this.agentService.getIds(applicationName); + private List getAgents(ApplicationId applicationId) { + return this.agentService.getIds(applicationId); } private Range getRange() { diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationReader.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationReader.java index adc3a04a5c9c..3c7f1a46bb44 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationReader.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationReader.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.batch.job; import com.navercorp.pinpoint.batch.service.BatchApplicationService; +import com.navercorp.pinpoint.common.id.ApplicationId; import jakarta.annotation.Nonnull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -31,14 +32,14 @@ /** * @author youngjin.kim2 */ -public class ApplicationReader implements ItemStreamReader { +public class ApplicationReader implements ItemStreamReader { private static final Logger logger = LogManager.getLogger(ApplicationReader.class); private static final String CURRENT_INDEX = "current.index"; private final BatchApplicationService applicationService; - private List applicationNames; + private List applicationIds; private final AtomicInteger currentIndexAtom = new AtomicInteger(0); @@ -47,11 +48,11 @@ public ApplicationReader(BatchApplicationService applicationService) { } @Override - public String read() { + public ApplicationId read() { int currentIndex = currentIndexAtom.getAndIncrement(); - if (currentIndex < applicationNames.size()) { - logger.info("Reading application: {} / {}", currentIndex, applicationNames.size()); - return applicationNames.get(currentIndex); + if (currentIndex < applicationIds.size()) { + logger.info("Reading application: {} / {}", currentIndex, applicationIds.size()); + return applicationIds.get(currentIndex); } else { return null; } @@ -60,8 +61,8 @@ public String read() { @Override public void open(@Nonnull ExecutionContext executionContext) throws ItemStreamException { logger.info("Opened application reader"); - this.applicationNames = getAllApplications(); - logger.info("Application reader has {} applications", applicationNames.size()); + this.applicationIds = getAllApplications(); + logger.info("Application reader has {} applications", applicationIds.size()); if (executionContext.containsKey(CURRENT_INDEX)) { int loadedIndex = executionContext.getInt(CURRENT_INDEX); this.currentIndexAtom.set(loadedIndex); @@ -82,7 +83,7 @@ public void close() throws ItemStreamException { logger.info("Closing application reader"); } - private List getAllApplications() { + private List getAllApplications() { return this.applicationService.getAll() .stream() .sorted() diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationRemover.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationRemover.java index c27e967b04d8..9d545a42aefe 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationRemover.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/ApplicationRemover.java @@ -17,12 +17,14 @@ package com.navercorp.pinpoint.batch.job; import com.navercorp.pinpoint.batch.service.BatchApplicationService; +import com.navercorp.pinpoint.common.id.ApplicationId; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import java.util.Objects; +import java.util.UUID; /** * @author youngjin.kim2 @@ -38,11 +40,12 @@ public ApplicationRemover(BatchApplicationService applicationService) { } @Override - public void write(Chunk applicationNames) throws Exception { - for (String applicationName : applicationNames) { - logger.info("Removing application: {}", applicationName); - this.applicationService.remove(applicationName); - logger.info("Removed application: {}", applicationName); + public void write(Chunk applicationIds) throws Exception { + for (String applicationIdStr : applicationIds) { + ApplicationId applicationId = ApplicationId.of(UUID.fromString(applicationIdStr)); + logger.info("Removing application: {}", applicationId); + this.applicationService.remove(applicationId); + logger.info("Removed application: {}", applicationId); } } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/job/CleanupInactiveAgentsTasklet.java b/batch/src/main/java/com/navercorp/pinpoint/batch/job/CleanupInactiveAgentsTasklet.java index 339ca8aa69f9..d7005b894b64 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/job/CleanupInactiveAgentsTasklet.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/job/CleanupInactiveAgentsTasklet.java @@ -17,8 +17,9 @@ package com.navercorp.pinpoint.batch.job; import com.navercorp.pinpoint.batch.common.BatchProperties; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.web.service.AdminService; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import jakarta.annotation.Nonnull; import org.apache.logging.log4j.LogManager; @@ -50,9 +51,9 @@ public class CleanupInactiveAgentsTasklet implements Tasklet, StepExecutionListe private final AdminService adminService; - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; - private Queue applicationNameQueue; + private Queue applicationIdsQueue; private int progress; private int total; private int inactiveCount; @@ -60,26 +61,26 @@ public class CleanupInactiveAgentsTasklet implements Tasklet, StepExecutionListe public CleanupInactiveAgentsTasklet( BatchProperties batchProperties, AdminService adminService, - ApplicationIndexDao applicationIndexDao + ApplicationService applicationService ) { Objects.requireNonNull(batchProperties, "batchProperties"); this.durationDays = batchProperties.getCleanupInactiveAgentsDurationDays(); this.adminService = Objects.requireNonNull(adminService, "adminService"); - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); } @Override public void beforeStep(@Nonnull StepExecution stepExecution) { - List applicationNames = this.applicationIndexDao.selectAllApplicationNames() + List applicationIds = this.applicationService.getApplications() .stream() - .map(Application::getName) + .map(Application::id) .distinct() .collect(Collectors.toList()); - Collections.shuffle(applicationNames); + Collections.shuffle(applicationIds); - this.applicationNameQueue = new ArrayDeque<>(applicationNames); + this.applicationIdsQueue = new ArrayDeque<>(applicationIds); this.progress = 0; - this.total = applicationNames.size(); + this.total = applicationIds.size(); this.inactiveCount = 0; } @@ -94,16 +95,16 @@ public RepeatStatus execute( @Nonnull StepContribution contribution, @Nonnull ChunkContext chunkContext ) throws Exception { - String applicationName = this.applicationNameQueue.poll(); - if (applicationName == null) { + ApplicationId applicationId = this.applicationIdsQueue.poll(); + if (applicationId == null) { return RepeatStatus.FINISHED; } try { - logger.info("Cleaning application {} ({}/{})", applicationName, ++progress, total); - inactiveCount += adminService.removeInactiveAgentInApplication(applicationName, durationDays); + logger.info("Cleaning application {} ({}/{})", applicationId, ++progress, total); + inactiveCount += adminService.removeInactiveAgentInApplication(applicationId, durationDays); } catch (Exception e) { - logger.warn("Failed to clean application {}. message: {}", applicationName, e.getMessage(), e); + logger.warn("Failed to clean application {}. message: {}", applicationId, e.getMessage(), e); } return RepeatStatus.CONTINUABLE; diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/service/AlarmServiceImpl.java b/batch/src/main/java/com/navercorp/pinpoint/batch/service/AlarmServiceImpl.java index 3fcdc70b9df8..49e63986b8ea 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/service/AlarmServiceImpl.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/service/AlarmServiceImpl.java @@ -64,7 +64,7 @@ public void updateBeforeCheckerResult(CheckerResult beforeCheckerResult, AlarmCh beforeCheckerResult.increseCount(); alarmDao.insertCheckerResult(beforeCheckerResult); } else { - alarmDao.insertCheckerResult(new CheckerResult(checker.getRule().getRuleId(), checker.getRule().getApplicationId(), checker.getRule().getCheckerName(), false, 0, 1)); + alarmDao.insertCheckerResult(new CheckerResult(checker.getRule().getRuleId(), checker.getRule().getApplicationName(), checker.getRule().getCheckerName(), false, 0, 1)); } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentService.java b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentService.java index a3f447ef1a48..cbcf21377a90 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentService.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentService.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.batch.service; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; import java.util.List; @@ -25,10 +27,10 @@ */ public interface BatchAgentService { - List getIds(String applicationName); + List getIds(ApplicationId applicationId); - boolean isActive(String agentId, Range range); + boolean isActive(AgentId agentId, Range range); - void remove(String applicationName, String agentId); + void remove(ApplicationId applicationId, String agentId); } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentServiceImpl.java b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentServiceImpl.java index 617c56ce9f14..956ca42a1586 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentServiceImpl.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchAgentServiceImpl.java @@ -16,9 +16,11 @@ package com.navercorp.pinpoint.batch.service; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AgentInfoService; +import com.navercorp.pinpoint.web.service.ApplicationService; import java.util.List; import java.util.Objects; @@ -28,29 +30,32 @@ */ public class BatchAgentServiceImpl implements BatchAgentService { - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; private final AgentInfoService agentInfoService; public BatchAgentServiceImpl( - ApplicationIndexDao applicationIndexDao, + ApplicationService applicationService, AgentInfoService agentInfoService ) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.agentInfoService = Objects.requireNonNull(agentInfoService, "agentInfoService"); } @Override - public List getIds(String applicationName) { - return this.applicationIndexDao.selectAgentIds(applicationName); + public List getIds(ApplicationId applicationId) { + return this.applicationService.getAgents(applicationId) + .stream() + .map(AgentId::of) + .toList(); } @Override - public boolean isActive(String agentId, Range range) { + public boolean isActive(AgentId agentId, Range range) { return this.agentInfoService.isActiveAgent(agentId, range); } @Override - public void remove(String applicationName, String agentId) { - this.applicationIndexDao.deleteAgentId(applicationName, agentId); + public void remove(ApplicationId applicationId, String agentId) { + this.applicationService.deleteAgent(applicationId, agentId); } } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationService.java b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationService.java index 49d9db155e38..43fa97f81932 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationService.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationService.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.batch.service; +import com.navercorp.pinpoint.common.id.ApplicationId; + import java.time.Duration; import java.util.List; @@ -24,10 +26,10 @@ */ public interface BatchApplicationService { - List getAll(); + List getAll(); - boolean isActive(String applicationName, Duration duration); + boolean isActive(ApplicationId applicationId, Duration duration); - void remove(String applicationName); + void remove(ApplicationId applicationId); } diff --git a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationServiceImpl.java b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationServiceImpl.java index 7ab50947420e..b0b8e566994b 100644 --- a/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationServiceImpl.java +++ b/batch/src/main/java/com/navercorp/pinpoint/batch/service/BatchApplicationServiceImpl.java @@ -16,9 +16,10 @@ package com.navercorp.pinpoint.batch.service; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; +import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDaoV2; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import org.springframework.stereotype.Service; @@ -32,38 +33,39 @@ @Service public class BatchApplicationServiceImpl implements BatchApplicationService { - private final ApplicationIndexDao applicationIndexDao; - private final ApplicationTraceIndexDao applicationTraceIndexDao; + private final ApplicationService applicationService; + private final ApplicationTraceIndexDaoV2 applicationTraceIndexDao; public BatchApplicationServiceImpl( - ApplicationIndexDao applicationIndexDao, - ApplicationTraceIndexDao applicationTraceIndexDao + ApplicationService applicationService, + ApplicationTraceIndexDaoV2 applicationTraceIndexDao ) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.applicationTraceIndexDao = Objects.requireNonNull(applicationTraceIndexDao, "applicationTraceIndexDao"); } @Override - public List getAll() { - return this.applicationIndexDao.selectAllApplicationNames() + public List getAll() { + return this.applicationService.getApplications() .stream() - .map(Application::getName) + .map(Application::id) .toList(); } @Override - public boolean isActive(String applicationName, Duration duration) { + public boolean isActive(ApplicationId applicationId, Duration duration) { long now = System.currentTimeMillis(); Range range = Range.between(now - duration.toMillis(), now); - return hasTrace(applicationName, range); + return hasTrace(applicationId, range); } - private boolean hasTrace(String applicationName, Range range) { - return this.applicationTraceIndexDao.hasTraceIndex(applicationName, range,false); + private boolean hasTrace(ApplicationId applicationId, Range range) { + return this.applicationTraceIndexDao.hasTraceIndex(applicationId, range,false); } @Override - public void remove(String applicationName) { - this.applicationIndexDao.deleteApplicationName(applicationName); + public void remove(ApplicationId applicationId) { + this.applicationService.deleteApplication(applicationId); } + } diff --git a/batch/src/main/resources/job/applicationContext-cleanupInactiveApplicationsJob.xml b/batch/src/main/resources/job/applicationContext-cleanupInactiveApplicationsJob.xml index 7c708de984fc..b1a78d70a55a 100644 --- a/batch/src/main/resources/job/applicationContext-cleanupInactiveApplicationsJob.xml +++ b/batch/src/main/resources/job/applicationContext-cleanupInactiveApplicationsJob.xml @@ -53,7 +53,7 @@ - + diff --git a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessorTest.java b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessorTest.java index 406cdea5a823..dda419dd681c 100644 --- a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessorTest.java +++ b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmProcessorTest.java @@ -6,9 +6,9 @@ import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.alarm.CheckerCategory; import com.navercorp.pinpoint.web.alarm.vo.Rule; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AgentInfoService; import com.navercorp.pinpoint.web.service.AlarmService; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -42,7 +42,7 @@ public class AlarmProcessorTest { private AlarmService alarmService; @Mock - private ApplicationIndexDao applicationIndexDao; + private ApplicationService applicationService; @Mock private AgentInfoService agentInfoService; @@ -63,7 +63,7 @@ public void shouldSkipIfNoRule() { when(alarmService.selectRuleByApplicationId(SERVICE_NAME)).thenReturn(List.of()); - AlarmProcessor proc = new AlarmProcessor(dataCollectorFactory, alarmService, applicationIndexDao, agentInfoService, checkerRegistry); + AlarmProcessor proc = new AlarmProcessor(dataCollectorFactory, alarmService, applicationService, agentInfoService, checkerRegistry); AppAlarmChecker checker = proc.process(app); assertNull(checker, "should be skipped"); @@ -82,7 +82,7 @@ public void test() { when(agentStatDataCollector.getHeapUsageRate()).thenReturn(heapUsageRate); // Executions - AlarmProcessor processor = new AlarmProcessor(dataCollectorFactory, alarmService, applicationIndexDao, agentInfoService, checkerRegistry); + AlarmProcessor processor = new AlarmProcessor(dataCollectorFactory, alarmService, applicationService, agentInfoService, checkerRegistry); AppAlarmChecker appChecker = processor.process(application); // Validations diff --git a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmReaderTest.java b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmReaderTest.java index 3b9786cdf71a..f03caa12b3a4 100644 --- a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmReaderTest.java +++ b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/AlarmReaderTest.java @@ -16,9 +16,10 @@ package com.navercorp.pinpoint.batch.alarm; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.trace.ServiceType; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.service.AlarmService; +import com.navercorp.pinpoint.web.service.ApplicationService; import com.navercorp.pinpoint.web.vo.Application; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -27,6 +28,7 @@ import org.springframework.batch.core.StepExecution; import java.util.List; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -36,7 +38,7 @@ public class AlarmReaderTest { @Mock - private ApplicationIndexDao applicationIndexDao; + private ApplicationService applicationService; @Mock private AlarmService alarmService; @@ -45,22 +47,22 @@ public class AlarmReaderTest { private StepExecution stepExecution; private static final List mockApplications = List.of( - new Application("testApplication0", ServiceType.TEST), - new Application("testApplication1", ServiceType.TEST), - new Application("testApplication2", ServiceType.TEST), - new Application("testApplication3", ServiceType.TEST) + new Application(ApplicationId.of(UUID.randomUUID()), "testApplication0", ServiceType.TEST), + new Application(ApplicationId.of(UUID.randomUUID()), "testApplication1", ServiceType.TEST), + new Application(ApplicationId.of(UUID.randomUUID()), "testApplication2", ServiceType.TEST), + new Application(ApplicationId.of(UUID.randomUUID()), "testApplication3", ServiceType.TEST) ); private static final List applicationIds = mockApplications.stream() - .map(Application::getName) + .map(Application::name) .toList(); @Test public void pollingTest() { - when(applicationIndexDao.selectAllApplicationNames()).thenReturn(mockApplications); + when(applicationService.getApplications()).thenReturn(mockApplications); when(alarmService.selectApplicationId()).thenReturn(applicationIds); - AlarmReader reader = new AlarmReader(applicationIndexDao, alarmService); + AlarmReader reader = new AlarmReader(applicationService, alarmService); reader.beforeStep(stepExecution); for (int i = 0; i < 4; i++) { assertEquals(mockApplications.get(i), reader.read(), "polled application should be same"); @@ -70,9 +72,9 @@ public void pollingTest() { @Test public void pollingFromEmptyTest() { - when(applicationIndexDao.selectAllApplicationNames()).thenReturn(List.of()); + when(applicationService.getApplications()).thenReturn(List.of()); - AlarmReader reader = new AlarmReader(applicationIndexDao, alarmService); + AlarmReader reader = new AlarmReader(applicationService, alarmService); reader.beforeStep(stepExecution); assertNull(reader.read()); } diff --git a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/checker/GcCountCheckerTest.java b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/checker/GcCountCheckerTest.java index 7fabbf226bc0..cce4bdcdb0d7 100644 --- a/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/checker/GcCountCheckerTest.java +++ b/batch/src/test/java/com/navercorp/pinpoint/batch/alarm/checker/GcCountCheckerTest.java @@ -91,12 +91,12 @@ public boolean agentStatExists(String agentId, Range range) { applicationIndexDao = new ApplicationIndexDao() { @Override - public List selectAllApplicationNames() { + public List selectAllApplications() { throw new UnsupportedOperationException(); } @Override - public List selectApplicationName(String applicationName) { + public List selectApplicationByName(String applicationName) { throw new UnsupportedOperationException(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentInfoDao.java index 76fd0415ba66..23f5ee7d5b6e 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentInfoDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/AgentInfoDao.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.dao; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; /** @@ -25,5 +26,5 @@ public interface AgentInfoDao { void insert(AgentInfoBo agentInfo); - AgentInfoBo getAgentInfo(String agentId, long timestamp); + AgentInfoBo getAgentInfo(AgentId agentId, long timestamp); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationInfoDao.java new file mode 100644 index 000000000000..df6c76f0d602 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ApplicationInfoDao.java @@ -0,0 +1,41 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.collector.dao; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; + +import java.util.List; + +/** + * @author youngjin.kim2 + */ +public interface ApplicationInfoDao { + + ApplicationId getApplicationId(ApplicationSelector application); + + ApplicationInfo getApplication(ApplicationId applicationId); + + ApplicationId putApplicationIdIfAbsent(ApplicationInfo application); + + void ensureInverse(ApplicationInfo application); + + List getApplications(ServiceId serviceId); + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java index 3cd392c1a69a..ae14b24c6f5c 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCalleeDao.java @@ -24,5 +24,7 @@ * @author emeroad */ public interface MapStatisticsCalleeDao extends CachedStatisticsDao { - void update(String calleeApplicationName, ServiceType calleeServiceType, String callerApplicationName, ServiceType callerServiceType, String callerHost, int elapsed, boolean isError); + void update(String calleeApplicationName, ServiceType calleeServiceType, + String callerApplicationName, ServiceType callerServiceType, String callerHost, + int elapsed, boolean isError); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java index a0db76976df3..1cd3abcd29a9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/MapStatisticsCallerDao.java @@ -24,5 +24,7 @@ * @author emeroad */ public interface MapStatisticsCallerDao extends CachedStatisticsDao { - void update(String callerApplicationName, ServiceType callerServiceType, String callerAgentId, String calleeApplicationName, ServiceType calleeServiceType, String calleeHost, int elapsed, boolean isError); + void update(String callerApplicationName, ServiceType callerServiceType, String callerAgentId, + String calleeApplicationName, ServiceType calleeServiceType, String calleeHost, + int elapsed, boolean isError); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ServiceInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ServiceInfoDao.java new file mode 100644 index 000000000000..af9680a8760e --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/ServiceInfoDao.java @@ -0,0 +1,34 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.dao; + +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; + +/** + * @author youngjin.kim2 + */ +public interface ServiceInfoDao { + + ServiceId getServiceId(String serviceName); + + ServiceInfo getServiceInfo(ServiceId serviceId); + + ServiceId putServiceIdIfAbsent(String serviceName, ServiceId serviceId); + + void ensurePut(String serviceName, ServiceId serviceId); + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentEventDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentEventDao.java index 15d22c7484de..d820c77b0597 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentEventDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentEventDao.java @@ -86,6 +86,6 @@ public void insert(AgentEventBo agentEventBo) { } byte[] createRowKey(String agentId, long eventTimestamp) { - return rowKeyEncoder.encodeRowKey(agentId, eventTimestamp); + return rowKeyEncoder.encodeRowKey(agentId, eventTimestamp); } } \ No newline at end of file diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java index 1686608f90b8..ec2dd86ff9bd 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseAgentInfoDao.java @@ -22,6 +22,7 @@ import com.navercorp.pinpoint.common.hbase.HbaseOperations; import com.navercorp.pinpoint.common.hbase.ResultsExtractor; import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.common.server.bo.serializer.agent.AgentIdRowKeyEncoder; import com.navercorp.pinpoint.common.server.util.RowKeyUtils; @@ -73,10 +74,10 @@ public void insert(AgentInfoBo agentInfo) { //check agentName if set CollectorUtils.checkAgentName(agentInfo.getAgentName()); - final byte[] rowKey = rowKeyEncoder.encodeRowKey(agentInfo.getAgentId(), agentInfo.getStartTime()); + final byte[] rowKey = rowKeyEncoder.encodeRowKey(AgentId.unwrap(agentInfo.getAgentId()), agentInfo.getStartTime()); final Put put = new Put(rowKey); - // should add additional agent informations. for now added only starttime for sqlMetaData + // should add additional agent information. for now added only start-time for sqlMetaData final byte[] agentInfoBoValue = agentInfo.writeValue(); put.addColumn(DESCRIPTOR.getName(), DESCRIPTOR.QUALIFIER_IDENTIFIER, agentInfoBoValue); @@ -94,7 +95,8 @@ public void insert(AgentInfoBo agentInfo) { hbaseTemplate.put(agentInfoTableName, put); } - public AgentInfoBo getAgentInfo(final String agentId, final long timestamp) { + @Override + public AgentInfoBo getAgentInfo(final AgentId agentId, final long timestamp) { Objects.requireNonNull(agentId, "agentId"); final Scan scan = createScan(agentId, timestamp); @@ -102,11 +104,11 @@ public AgentInfoBo getAgentInfo(final String agentId, final long timestamp) { return this.hbaseTemplate.find(agentInfoTableName, scan, agentInfoResultsExtractor); } - private Scan createScan(String agentId, long currentTime) { + private Scan createScan(AgentId agentId, long currentTime) { final Scan scan = new Scan(); - final byte[] startKeyBytes = rowKeyEncoder.encodeRowKey(agentId, currentTime); - final byte[] endKeyBytes = RowKeyUtils.agentIdAndTimestamp(agentId, Long.MAX_VALUE); + final byte[] startKeyBytes = rowKeyEncoder.encodeRowKey(AgentId.unwrap(agentId), currentTime); + final byte[] endKeyBytes = RowKeyUtils.agentIdAndTimestamp(AgentId.unwrap(agentId), Long.MAX_VALUE); scan.withStartRow(startKeyBytes); scan.withStopRow(endKeyBytes); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationIndexDao.java index dd9978c97eb5..68ce230b0feb 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationIndexDao.java @@ -21,12 +21,15 @@ import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; import com.navercorp.pinpoint.common.hbase.HbaseOperations; import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.hbase.ValueMapper; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import java.util.Objects; @@ -42,15 +45,20 @@ public class HbaseApplicationIndexDao implements ApplicationIndexDao { private final Logger logger = LogManager.getLogger(this.getClass()); - private static final HbaseColumnFamily.ApplicationIndex DESCRIPTOR = HbaseColumnFamily.APPLICATION_INDEX_AGENTS; + private static final HbaseColumnFamily.ApplicationIndex DESCRIPTOR = HbaseColumnFamily.APPLICATION_INDEX_AGENTS_VER2; private final HbaseOperations hbaseTemplate; private final TableNameProvider tableNameProvider; + private final ValueMapper valueMapper; - public HbaseApplicationIndexDao(HbaseOperations hbaseTemplate, TableNameProvider tableNameProvider) { + public HbaseApplicationIndexDao( + HbaseOperations hbaseTemplate, + TableNameProvider tableNameProvider, + @Qualifier("applicationIndexValueMapper") ValueMapper valueMapper) { this.hbaseTemplate = Objects.requireNonNull(hbaseTemplate, "hbaseTemplate"); this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.valueMapper = Objects.requireNonNull(valueMapper, "valueMapper"); } @Override @@ -62,9 +70,9 @@ public void insert(final AgentInfoBo agentInfo) { // Assert applicationName CollectorUtils.checkApplicationName(agentInfo.getApplicationName()); - final Put put = new Put(Bytes.toBytes(agentInfo.getApplicationName())); - final byte[] qualifier = Bytes.toBytes(agentInfo.getAgentId()); - final byte[] value = Bytes.toBytes(agentInfo.getServiceTypeCode()); + final Put put = new Put(agentInfo.getApplicationId().toBytes()); + final byte[] qualifier = Bytes.toBytes(AgentId.unwrap(agentInfo.getAgentId())); + final byte[] value = this.valueMapper.mapValue(agentInfo); put.addColumn(DESCRIPTOR.getName(), qualifier, value); final TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationInfoDao.java new file mode 100644 index 000000000000..a0d754cbe621 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationInfoDao.java @@ -0,0 +1,190 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.collector.dao.hbase; + +import com.navercorp.pinpoint.collector.dao.ApplicationInfoDao; +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.CheckAndMutate; +import org.apache.hadoop.hbase.client.CheckAndMutateResult; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Repository +public class HbaseApplicationInfoDao implements ApplicationInfoDao { + private final Logger logger = LogManager.getLogger(this.getClass()); + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR_FORWARD = HbaseColumnFamily.APPLICATION_ID_FORWARD; + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR_INVERSE = HbaseColumnFamily.APPLICATION_ID_INVERSE; + + private final HbaseOperations hbaseTemplate; + private final TableNameProvider tableNameProvider; + private final RowMapper forwardRowMapper; + private final RowMapper inverseRowMapper; + + public HbaseApplicationInfoDao( + HbaseOperations hbaseTemplate, + TableNameProvider tableNameProvider, + @Qualifier("applicationIdForwardMapper") RowMapper forwardRowMapper, + @Qualifier("applicationIdInverseMapper") RowMapper inverseRowMapper) { + this.hbaseTemplate = Objects.requireNonNull(hbaseTemplate, "hbaseTemplate"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.forwardRowMapper = Objects.requireNonNull(forwardRowMapper, "forwardRowMapper"); + this.inverseRowMapper = Objects.requireNonNull(inverseRowMapper, "inverseRowMapper"); + } + + @Override + public ApplicationId getApplicationId(ApplicationSelector application) { + Objects.requireNonNull(application, "application"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplicationId() applicationName:{}", application.name()); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = application.toBytes(); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.inverseRowMapper); + } + + @Override + public ApplicationInfo getApplication(ApplicationId applicationId) { + Objects.requireNonNull(applicationId, "applicationId"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplication() applicationId:{}", applicationId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = applicationId.toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.forwardRowMapper); + } + + @Override + public ApplicationId putApplicationIdIfAbsent(ApplicationInfo application) { + Objects.requireNonNull(application, "application"); + + if (logger.isDebugEnabled()) { + logger.debug("putApplicationIdIfAbsent() serviceId: {}, applicationName:{}, applicationId:{}", + application.serviceId(), application.name(), application.id()); + } + + CheckAndMutateResult camResult = putInverse(application); + if (camResult.isSuccess()) { + putForward(application); + } + + ApplicationId applicationId = getApplicationId(new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode())); + if (applicationId == null) { + throw new IllegalStateException("Failed to put applicationId: " + application); + } + + return applicationId; + } + + @Override + public void ensureInverse(ApplicationInfo application) { + Objects.requireNonNull(application, "application"); + + if (logger.isDebugEnabled()) { + logger.debug("ensurePut() serviceId: {}, applicationName:{}, applicationId:{}", + application.serviceId(), application.name(), application.id()); + } + + putInverse(application); + } + + @Override + public List getApplications(ServiceId serviceId) { + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplications() serviceId:{}", serviceId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + + Scan scan = new Scan(); + scan.setStartStopRowForPrefixScan(serviceId.toBytes()); + + return hbaseTemplate.find(tableName, scan, this.inverseRowMapper); + } + + private CheckAndMutateResult putInverse(ApplicationInfo application) { + ApplicationSelector selector = new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode()); + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = selector.toBytes(); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + byte[] value = application.id().toBytes(); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + CheckAndMutate checkAndMutate = CheckAndMutate.newBuilder(rowKey) + .ifNotExists(family, qualifier) + .build(put); + + return hbaseTemplate.checkAndMutate(tableName, checkAndMutate); + } + + private void putForward(ApplicationInfo application) { + ApplicationSelector selector = new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode()); + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = application.id().toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + byte[] value = selector.toBytes(); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + hbaseTemplate.put(tableName, put); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java index 2beffeb32698..3e3403b47074 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseApplicationTraceIndexDao.java @@ -24,6 +24,7 @@ import com.navercorp.pinpoint.common.hbase.HbaseTableConstants; import com.navercorp.pinpoint.common.hbase.TableNameProvider; import com.navercorp.pinpoint.common.hbase.async.HbasePutWriter; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.serializer.RowKeyEncoder; import com.navercorp.pinpoint.common.server.util.SpanUtils; @@ -48,15 +49,13 @@ public class HbaseApplicationTraceIndexDao implements ApplicationTraceIndexDao { private final Logger logger = LogManager.getLogger(this.getClass()); - private static final HbaseColumnFamily.ApplicationTraceIndexTrace INDEX = HbaseColumnFamily.APPLICATION_TRACE_INDEX_TRACE; - private static final HbaseColumnFamily.ApplicationTraceIndexTrace META = HbaseColumnFamily.APPLICATION_TRACE_INDEX_META; + private static final HbaseColumnFamily.ApplicationTraceIndexTrace INDEX = HbaseColumnFamily.APPLICATION_TRACE_INDEX_TRACE_VER2; + private static final HbaseColumnFamily.ApplicationTraceIndexTrace META = HbaseColumnFamily.APPLICATION_TRACE_INDEX_META_VER2; private final HbasePutWriter putWriter; private final TableNameProvider tableNameProvider; - private final RowKeyEncoder applicationIndexRowKeyEncoder; - public HbaseApplicationTraceIndexDao(HbasePutWriter putWriter, TableNameProvider tableNameProvider, @Qualifier("applicationIndexRowKeyEncoder") RowKeyEncoder applicationIndexRowKeyEncoder) { @@ -77,7 +76,7 @@ public void insert(final SpanBo span) { // Assert agentId CollectorUtils.checkAgentId(span.getAgentId()); // Assert applicationName - CollectorUtils.checkApplicationName(span.getApplicationId()); + CollectorUtils.checkApplicationName(span.getApplicationName()); final long acceptedTime = span.getCollectorAcceptTime(); final byte[] distributedKey = applicationIndexRowKeyEncoder.encodeRowKey(span); @@ -100,7 +99,7 @@ private byte[] buildIndexValue(SpanBo span) { final Buffer buffer = new AutomaticBuffer(10 + HbaseTableConstants.AGENT_ID_MAX_LEN); buffer.putVInt(span.getElapsed()); buffer.putSVInt(span.getErrCode()); - buffer.putPrefixedString(span.getAgentId()); + buffer.putPrefixedString(AgentId.unwrap(span.getAgentId())); return buffer.getBuffer(); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java index 2a1478c81710..f0b5bedac3ab 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCalleeDao.java @@ -82,14 +82,14 @@ public void update(String calleeApplicationName, ServiceType calleeServiceType, // there may be no endpoint in case of httpclient callerHost = StringUtils.defaultString(callerHost); - // TODO callee, caller parameter normalization + // TODO: callee, caller parameter normalization if (ignoreStatFilter.filter(calleeServiceType, callerHost)) { logger.debug("[Ignore-Callee] {} ({}) <- {} ({})[{}]", calleeApplicationName, calleeServiceType, callerApplicationName, callerServiceType, callerHost); return; } - // make row key. rowkey is me + // make row key. row key is me final long acceptedTime = acceptedTimeService.getAcceptedTime(); final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); final RowKey calleeRowKey = new CallRowKey(calleeApplicationName, calleeServiceType.getCode(), rowTimeSlot); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java index 2edf93f85fe5..9884cfa9200a 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseMapStatisticsCallerDao.java @@ -62,7 +62,7 @@ public HbaseMapStatisticsCallerDao(MapLinkConfiguration mapLinkConfiguration, this.acceptedTimeService = Objects.requireNonNull(acceptedTimeService, "acceptedTimeService"); this.timeSlot = Objects.requireNonNull(timeSlot, "timeSlot"); - this.bulkWriter = Objects.requireNonNull(bulkWriter, "bulkWrtier"); + this.bulkWriter = Objects.requireNonNull(bulkWriter, "bulkWriter"); } @@ -80,7 +80,7 @@ public void update(String callerApplicationName, ServiceType callerServiceType, // there may be no endpoint in case of httpclient calleeHost = StringUtils.defaultString(calleeHost); - // make row key. rowkey is me + // make row key. row key is me final long acceptedTime = acceptedTimeService.getAcceptedTime(); final long rowTimeSlot = timeSlot.getTimeSlot(acceptedTime); final RowKey callerRowKey = new CallRowKey(callerApplicationName, callerServiceType.getCode(), rowTimeSlot); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseServiceInfoDao.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseServiceInfoDao.java new file mode 100644 index 000000000000..82fcf25fb4c4 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseServiceInfoDao.java @@ -0,0 +1,169 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.dao.hbase; + +import com.navercorp.pinpoint.collector.dao.ServiceInfoDao; +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import com.navercorp.pinpoint.common.util.BytesUtils; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.CheckAndMutate; +import org.apache.hadoop.hbase.client.CheckAndMutateResult; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Put; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Repository +public class HbaseServiceInfoDao implements ServiceInfoDao { + + private final Logger logger = LogManager.getLogger(this.getClass()); + + private static final HbaseColumnFamily.ServiceId DESCRIPTOR_FORWARD = HbaseColumnFamily.SERVICE_ID_FORWARD; + private static final HbaseColumnFamily.ServiceId DESCRIPTOR_INVERSE = HbaseColumnFamily.SERVICE_ID_INVERSE; + + private final HbaseOperations hbaseTemplate; + private final TableNameProvider tableNameProvider; + private final RowMapper forwardRowMapper; + private final RowMapper inverseRowMapper; + + public HbaseServiceInfoDao( + HbaseOperations hbaseTemplate, + TableNameProvider tableNameProvider, + @Qualifier("serviceIdForwardMapper") RowMapper forwardRowMapper, + @Qualifier("serviceIdInverseMapper") RowMapper inverseRowMapper) { + this.hbaseTemplate = Objects.requireNonNull(hbaseTemplate, "hbaseTemplate"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.forwardRowMapper = Objects.requireNonNull(forwardRowMapper, "forwardRowMapper"); + this.inverseRowMapper = Objects.requireNonNull(inverseRowMapper, "inverseRowMapper"); + } + + @Override + public ServiceId getServiceId(String serviceName) { + Objects.requireNonNull(serviceName, "serviceName"); + + if (logger.isDebugEnabled()) { + logger.debug("getServiceId() serviceName:{}", serviceName); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = encodeStringAsRowKey(serviceName); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.inverseRowMapper); + } + + @Override + public ServiceInfo getServiceInfo(ServiceId serviceId) { + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("getServiceInfo() serviceId:{}", serviceId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = serviceId.toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.forwardRowMapper); + } + + @Override + public ServiceId putServiceIdIfAbsent(String serviceName, ServiceId serviceId) { + Objects.requireNonNull(serviceName, "serviceName"); + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("putServiceIdIfAbsent() serviceName:{}, serviceId:{}", serviceName, serviceId); + } + + ServiceInfo service = new ServiceInfo(serviceId, serviceName); + CheckAndMutateResult camResult = this.putInverse(service); + + if (camResult.isSuccess()) { + putForward(service); + } + + return getServiceId(serviceName); + } + + @Override + public void ensurePut(String serviceName, ServiceId serviceId) { + Objects.requireNonNull(serviceName, "serviceName"); + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("ensurePut() serviceName:{}, serviceId:{}", serviceName, serviceId); + } + + ServiceInfo service = new ServiceInfo(serviceId, serviceName); + putForward(service); + } + + private CheckAndMutateResult putInverse(ServiceInfo service) { + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = encodeStringAsRowKey(service.name()); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + byte[] value = service.id().toBytes(); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + CheckAndMutate checkAndMutate = CheckAndMutate.newBuilder(rowKey) + .ifNotExists(family, qualifier) + .build(put); + + return hbaseTemplate.checkAndMutate(tableName, checkAndMutate); + } + + private void putForward(ServiceInfo service) { + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = service.id().toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + byte[] value = BytesUtils.toBytes(service.name()); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + hbaseTemplate.put(tableName, put); + } + + private static byte[] encodeStringAsRowKey(String str) { + return BytesUtils.toBytes(str); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoV2.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoV2.java index bdb02f221fe6..b7a92fc52e67 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoV2.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/HbaseTraceDaoV2.java @@ -101,7 +101,7 @@ public CompletableFuture asyncInsert(final SpanBo spanBo) { // Assert agentId CollectorUtils.checkAgentId(spanBo.getAgentId()); // Assert applicationName - CollectorUtils.checkApplicationName(spanBo.getApplicationId()); + CollectorUtils.checkApplicationName(spanBo.getApplicationName()); long acceptedTime = spanBo.getCollectorAcceptTime(); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV1.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV1.java index ac140697a64c..aca4a1831828 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV1.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV1.java @@ -38,7 +38,7 @@ public ApplicationIndexRowKeyEncoderV1(AbstractRowKeyDistributor rowKeyDistribut public byte[] encodeRowKey(SpanBo span) { // distribute key evenly long acceptedTime = span.getCollectorAcceptTime(); - final byte[] applicationTraceIndexRowKey = rowKeyEncoder.encodeRowKey(span.getApplicationId(), acceptedTime); + final byte[] applicationTraceIndexRowKey = rowKeyEncoder.encodeRowKey(span.getApplicationName(), acceptedTime); return rowKeyDistributor.getDistributedKey(applicationTraceIndexRowKey); } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2.java index 5c7bf3c6560b..ebcd6c831411 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.collector.dao.hbase.encode; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.serializer.RowKeyEncoder; import com.navercorp.pinpoint.common.server.bo.serializer.agent.ApplicationNameRowKeyEncoder; @@ -49,13 +50,13 @@ public byte[] encodeRowKey(SpanBo span) { return rowKeyDistributor.getDistributedKey(appTraceIndexRowKey); } - byte[] newRowKey(String applicationName, long acceptedTime, byte fuzzySlotKey) { - Objects.requireNonNull(applicationName, "applicationName"); + byte[] newRowKey(ApplicationId applicationId, long acceptedTime, byte fuzzySlotKey) { + Objects.requireNonNull(applicationId, "applicationId"); if (logger.isDebugEnabled()) { logger.debug("fuzzySlotKey:{}", fuzzySlotKey); } - byte[] rowKey = rowKeyEncoder.encodeRowKey(applicationName, acceptedTime); + byte[] rowKey = rowKeyEncoder.encodeRowKey(ApplicationId.unwrap(applicationId), acceptedTime); byte[] fuzzyRowKey = new byte[rowKey.length + 1]; System.arraycopy(rowKey, 0, fuzzyRowKey, 0, rowKey.length); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/mapper/ApplicationIndexValueMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/mapper/ApplicationIndexValueMapper.java new file mode 100644 index 000000000000..c9abb7e02b52 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/mapper/ApplicationIndexValueMapper.java @@ -0,0 +1,37 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.dao.hbase.mapper; + +import com.navercorp.pinpoint.common.buffer.AutomaticBuffer; +import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.hbase.ValueMapper; +import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; +import org.springframework.stereotype.Component; + +/** + * @author youngjin.kim2 + */ +@Component +public class ApplicationIndexValueMapper implements ValueMapper { + + @Override + public byte[] mapValue(AgentInfoBo value) { + Buffer buffer = new AutomaticBuffer(); + buffer.putShort(value.getServiceTypeCode()); + return buffer.getBuffer(); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CallRowKey.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CallRowKey.java index a93577ddea5c..cbac7bc6e5eb 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CallRowKey.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CallRowKey.java @@ -49,10 +49,7 @@ public boolean equals(Object o) { if (callServiceType != that.callServiceType) return false; if (rowTimeSlot != that.rowTimeSlot) return false; - if (callApplicationName != null ? !callApplicationName.equals(that.callApplicationName) : that.callApplicationName != null) - return false; - - return true; + return Objects.equals(callApplicationName, that.callApplicationName); } @Override @@ -60,7 +57,7 @@ public int hashCode() { if (hash != 0) { return hash; } - int result = callApplicationName != null ? callApplicationName.hashCode() : 0; + int result = callApplicationName.hashCode(); result = 31 * result + (int) callServiceType; result = 31 * result + (int) (rowTimeSlot ^ (rowTimeSlot >>> 32)); hash = result; @@ -69,11 +66,9 @@ public int hashCode() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("CallRowKey{"); - sb.append("callApplicationName='").append(callApplicationName).append('\''); - sb.append(", callServiceType=").append(callServiceType); - sb.append(", rowTimeSlot=").append(rowTimeSlot); - sb.append('}'); - return sb.toString(); + return "CallRowKey{" + "callApplicationName='" + callApplicationName + '\'' + + ", callServiceType=" + callServiceType + + ", rowTimeSlot=" + rowTimeSlot + + '}'; } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CalleeColumnName.java b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CalleeColumnName.java index 1cd6e5cfb49c..296dbea0a077 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CalleeColumnName.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/CalleeColumnName.java @@ -75,14 +75,12 @@ public boolean equals(Object o) { if (columnSlotNumber != that.columnSlotNumber) return false; if (!callHost.equals(that.callHost)) return false; if (!calleeApplicationName.equals(that.calleeApplicationName)) return false; - if (!callerAgentId.equals(that.callerAgentId)) return false; - - return true; + return callerAgentId.equals(that.callerAgentId); } @Override public int hashCode() { - // take care when modifying this method - contains hashCodes for hbasekeys + // take care when modifying this method - contains hashCodes for hbase keys if (hash != 0) { return hash; } @@ -99,14 +97,12 @@ public int hashCode() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("CalleeColumnName{"); - sb.append("callerAgentId=").append(callerAgentId); - sb.append(", calleeServiceType=").append(calleeServiceType); - sb.append(", calleeApplicationName='").append(calleeApplicationName).append('\''); - sb.append(", callHost='").append(callHost).append('\''); - sb.append(", columnSlotNumber=").append(columnSlotNumber); - sb.append(", callCount=").append(callCount); - sb.append('}'); - return sb.toString(); + return "CalleeColumnName{" + "callerAgentId=" + callerAgentId + + ", calleeServiceType=" + calleeServiceType + + ", calleeApplicationName='" + calleeApplicationName + '\'' + + ", callHost='" + callHost + '\'' + + ", columnSlotNumber=" + columnSlotNumber + + ", callCount=" + callCount + + '}'; } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandler.java index 7b030a7ddd93..e8223f818d54 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandler.java @@ -19,6 +19,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.collector.handler.RequestResponseHandler; import com.navercorp.pinpoint.collector.service.ApiMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.ApiMetaDataBo; import com.navercorp.pinpoint.common.server.bo.MethodTypeEnum; import com.navercorp.pinpoint.common.util.LineNumber; @@ -76,13 +77,13 @@ PResult handleApiMetaData(final PApiMetaData apiMetaData) { try { final Header header = ServerContext.getAgentInfo(); - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final long agentStartTime = header.getAgentStartTime(); final int line = LineNumber.defaultLineNumber(apiMetaData.getLine()); final MethodTypeEnum type = MethodTypeEnum.defaultValueOf(apiMetaData.getType()); - final ApiMetaDataBo apiMetaDataBo = new ApiMetaDataBo.Builder(agentId, agentStartTime, + final ApiMetaDataBo apiMetaDataBo = new ApiMetaDataBo.Builder(AgentId.unwrap(agentId), agentStartTime, apiMetaData.getApiId(), line, type, apiMetaData.getApiInfo()) .setLocation(apiMetaData.getLocation()) .build(); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcExceptionMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcExceptionMetaDataHandler.java index ab28ff21755f..baa366404c05 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcExceptionMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcExceptionMetaDataHandler.java @@ -18,6 +18,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.collector.handler.RequestResponseHandler; import com.navercorp.pinpoint.collector.service.ExceptionMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.exception.ExceptionMetaDataBo; import com.navercorp.pinpoint.common.server.bo.exception.ExceptionWrapperBo; @@ -103,14 +104,14 @@ private PResult handleExceptionMetaData(final PExceptionMetaData exceptionMetaDa private ExceptionMetaDataBo mapExceptionMetaDataBo( Header agentInfo, PExceptionMetaData exceptionMetaData ) { - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final TransactionId transactionId = newTransactionId(exceptionMetaData.getTransactionId(), agentId); return new ExceptionMetaDataBo( transactionId, exceptionMetaData.getSpanId(), (short) agentInfo.getServiceType(), agentInfo.getApplicationName(), - agentInfo.getAgentId(), + AgentId.unwrap(agentInfo.getAgentId()), StringUtils.defaultIfEmpty(exceptionMetaData.getUriTemplate(), EMPTY) ); } @@ -140,9 +141,9 @@ private List handleStackTraceElements(List { private final GrpcSpanFactory spanFactory; private final AcceptedTimeService acceptedTimeService; + private final ApplicationInfoService applicationInfoService; + private final ServiceInfoService serviceInfoService; private final Sampler sampler; - public GrpcSpanChunkHandler(TraceService[] traceServices, GrpcSpanFactory spanFactory, AcceptedTimeService acceptedTimeService, SpanSamplerFactory spanSamplerFactory) { + public GrpcSpanChunkHandler( + TraceService[] traceServices, + GrpcSpanFactory spanFactory, + AcceptedTimeService acceptedTimeService, + SpanSamplerFactory spanSamplerFactory, + ApplicationInfoService applicationInfoService, + ServiceInfoService serviceInfoService) { this.traceServices = Objects.requireNonNull(traceServices, "traceServices"); this.spanFactory = Objects.requireNonNull(spanFactory, "spanFactory"); this.acceptedTimeService = Objects.requireNonNull(acceptedTimeService, "acceptedTimeService"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); this.sampler = spanSamplerFactory.createBasicSpanSampler(); logger.info("TraceServices {}", Arrays.toString(traceServices)); @@ -77,7 +91,9 @@ private void handleSpanChunk(PSpanChunk spanChunk) { final Header header = ServerContext.getAgentInfo(); - final BindAttribute attribute = BindAttribute.of(header, acceptedTimeService.getAcceptedTime()); + final ServiceId serviceId = this.serviceInfoService.getServiceId(header.getServiceName()); + final ApplicationId applicationId = this.applicationInfoService.getApplicationId(serviceId, header.getApplicationName(), (short) header.getServiceType()); + final BindAttribute attribute = BindAttribute.of(header, applicationId, acceptedTimeService.getAcceptedTime()); final SpanChunkBo spanChunkBo = spanFactory.buildSpanChunkBo(spanChunk, attribute); if (!sampler.isSampling(spanChunkBo)) { if (isDebug) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSpanHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSpanHandler.java index 2811dd9dd369..43768b469c5f 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSpanHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSpanHandler.java @@ -20,8 +20,12 @@ import com.navercorp.pinpoint.collector.handler.SimpleHandler; import com.navercorp.pinpoint.collector.sampler.Sampler; import com.navercorp.pinpoint.collector.sampler.SpanSamplerFactory; +import com.navercorp.pinpoint.collector.service.ApplicationInfoService; +import com.navercorp.pinpoint.collector.service.ServiceInfoService; import com.navercorp.pinpoint.collector.service.TraceService; import com.navercorp.pinpoint.common.hbase.RequestNotPermittedException; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; import com.navercorp.pinpoint.common.profiler.logging.LogSampler; import com.navercorp.pinpoint.common.server.bo.BasicSpan; import com.navercorp.pinpoint.common.server.bo.SpanBo; @@ -62,13 +66,23 @@ public class GrpcSpanHandler implements SimpleHandler { private final GrpcSpanFactory spanFactory; private final AcceptedTimeService acceptedTimeService; + private final ApplicationInfoService applicationInfoService; + private final ServiceInfoService serviceInfoService; private final Sampler sampler; - public GrpcSpanHandler(TraceService[] traceServices, GrpcSpanFactory spanFactory, AcceptedTimeService acceptedTimeService, SpanSamplerFactory spanSamplerFactory) { + public GrpcSpanHandler( + TraceService[] traceServices, + GrpcSpanFactory spanFactory, + AcceptedTimeService acceptedTimeService, + SpanSamplerFactory spanSamplerFactory, + ApplicationInfoService applicationInfoService, + ServiceInfoService serviceInfoService) { this.traceServices = Objects.requireNonNull(traceServices, "traceServices"); this.spanFactory = Objects.requireNonNull(spanFactory, "spanFactory"); this.acceptedTimeService = Objects.requireNonNull(acceptedTimeService, "acceptedTimeService"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); this.sampler = spanSamplerFactory.createBasicSpanSampler(); logger.info("TraceServices {}", Arrays.toString(traceServices)); @@ -91,7 +105,9 @@ private void handleSpan(PSpan span) { } final Header header = ServerContext.getAgentInfo(); - final BindAttribute attribute = BindAttribute.of(header, acceptedTimeService.getAcceptedTime()); + final ServiceId serviceId = this.serviceInfoService.getServiceId(header.getServiceName()); + final ApplicationId applicationId = this.applicationInfoService.getApplicationId(serviceId, header.getApplicationName(), (short) header.getServiceType()); + final BindAttribute attribute = BindAttribute.of(header, applicationId, acceptedTimeService.getAcceptedTime()); final SpanBo spanBo = spanFactory.buildSpanBo(span, attribute); if (!sampler.isSampling(spanBo)) { if (isDebug) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlMetaDataHandler.java index 34e60139bdb3..469aefa2a1b5 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlMetaDataHandler.java @@ -19,12 +19,15 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.collector.handler.RequestResponseHandler; import com.navercorp.pinpoint.collector.service.SqlMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SqlMetaDataBo; +import com.navercorp.pinpoint.common.server.bo.SqlUidMetaDataBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.MessageFormatUtils; import com.navercorp.pinpoint.grpc.server.ServerContext; import com.navercorp.pinpoint.grpc.trace.PResult; import com.navercorp.pinpoint.grpc.trace.PSqlMetaData; +import com.navercorp.pinpoint.grpc.trace.PSqlUidMetaData; import com.navercorp.pinpoint.io.request.ServerRequest; import com.navercorp.pinpoint.io.request.ServerResponse; import com.navercorp.pinpoint.thrift.io.DefaultTBaseLocator; @@ -91,12 +94,22 @@ private PResult handleSqlMetaData(PSqlMetaData sqlMetaData) { } private static SqlMetaDataBo mapSqlMetaDataBo(Header agentInfo, PSqlMetaData sqlMetaData) { - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final long agentStartTime = agentInfo.getAgentStartTime(); final int sqlId = sqlMetaData.getSqlId(); final String sql = sqlMetaData.getSql(); - return new SqlMetaDataBo(agentId, agentStartTime, sqlId, sql); + return new SqlMetaDataBo(AgentId.unwrap(agentId), agentStartTime, sqlId, sql); + } + + private static SqlUidMetaDataBo mapSqlUidMetaDataBo(Header agentInfo, PSqlUidMetaData sqlUidMetaData) { + final AgentId agentId = agentInfo.getAgentId(); + final long agentStartTime = agentInfo.getAgentStartTime(); + final String applicationName = agentInfo.getApplicationName(); + final byte[] sqlUid = sqlUidMetaData.getSqlUid().toByteArray(); + final String sql = sqlUidMetaData.getSql(); + + return new SqlUidMetaDataBo(AgentId.unwrap(agentId), agentStartTime, applicationName, sqlUid, sql); } private static PResult newResult(boolean success) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlUidMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlUidMetaDataHandler.java index 0b3c49e69bc0..eaacca5992d7 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlUidMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcSqlUidMetaDataHandler.java @@ -19,6 +19,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.collector.handler.RequestResponseHandler; import com.navercorp.pinpoint.collector.service.SqlUidMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SqlUidMetaDataBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.MessageFormatUtils; @@ -88,13 +89,13 @@ private PResult handleSqlUidMetaData(PSqlUidMetaData sqlUidMetaData) { } private static SqlUidMetaDataBo mapSqlUidMetaDataBo(Header agentInfo, PSqlUidMetaData sqlUidMetaData) { - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final long agentStartTime = agentInfo.getAgentStartTime(); final String applicationName = agentInfo.getApplicationName(); final byte[] sqlUid = sqlUidMetaData.getSqlUid().toByteArray(); final String sql = sqlUidMetaData.getSql(); - return new SqlUidMetaDataBo(agentId, agentStartTime, applicationName, sqlUid, sql); + return new SqlUidMetaDataBo(AgentId.unwrap(agentId), agentStartTime, applicationName, sqlUid, sql); } private static PResult newResult(boolean success) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcStringMetaDataHandler.java b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcStringMetaDataHandler.java index d228a4ff8158..4c2cc91030e9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcStringMetaDataHandler.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcStringMetaDataHandler.java @@ -19,6 +19,7 @@ import com.google.protobuf.GeneratedMessageV3; import com.navercorp.pinpoint.collector.handler.RequestResponseHandler; import com.navercorp.pinpoint.collector.service.StringMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.StringMetaDataBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.MessageFormatUtils; @@ -41,7 +42,6 @@ @Service public class GrpcStringMetaDataHandler implements RequestResponseHandler { private final Logger logger = LogManager.getLogger(getClass()); - private final boolean isDebug = logger.isDebugEnabled(); private final StringMetaDataService stringMetaDataService; @@ -73,12 +73,12 @@ private PResult handleStringMetaData(final PStringMetaData stringMetaData) { try { final Header agentInfo = ServerContext.getAgentInfo(); - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final long agentStartTime = agentInfo.getAgentStartTime(); final String stringValue = stringMetaData.getStringValue(); - final StringMetaDataBo stringMetaDataBo = new StringMetaDataBo(agentId, agentStartTime, + final StringMetaDataBo stringMetaDataBo = new StringMetaDataBo(AgentId.unwrap(agentId), agentStartTime, stringMetaData.getStringId(), stringValue); stringMetaDataService.insert(stringMetaDataBo); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/GrpcAgentInfoBoMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/GrpcAgentInfoBoMapper.java index e0af25648f30..9fdfe17bf2a9 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/GrpcAgentInfoBoMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/GrpcAgentInfoBoMapper.java @@ -16,6 +16,11 @@ package com.navercorp.pinpoint.collector.mapper.grpc; +import com.navercorp.pinpoint.collector.service.ApplicationInfoService; +import com.navercorp.pinpoint.collector.service.ServiceInfoService; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.trace.PAgentInfo; @@ -30,19 +35,29 @@ */ @Component public class GrpcAgentInfoBoMapper { - private final GrpcServerMetaDataBoMapper serverMetaDataBoMapper; + private final GrpcServerMetaDataBoMapper serverMetaDataBoMapper; private final GrpcJvmInfoBoMapper jvmInfoBoMapper; + private final ApplicationInfoService applicationInfoService; + private final ServiceInfoService serviceInfoService; - public GrpcAgentInfoBoMapper(GrpcServerMetaDataBoMapper serverMetaDataBoMapper, GrpcJvmInfoBoMapper jvmInfoBoMapper) { + public GrpcAgentInfoBoMapper( + GrpcServerMetaDataBoMapper serverMetaDataBoMapper, + GrpcJvmInfoBoMapper jvmInfoBoMapper, + ApplicationInfoService applicationInfoService, + ServiceInfoService serviceInfoService + ) { this.serverMetaDataBoMapper = Objects.requireNonNull(serverMetaDataBoMapper, "serverMetaDataBoMapper"); this.jvmInfoBoMapper = Objects.requireNonNull(jvmInfoBoMapper, "jvmInfoBoMapper"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); } public AgentInfoBo map(final PAgentInfo agentInfo, final Header header) { - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final String agentName = header.getAgentName(); final String applicationName = header.getApplicationName(); + final String serviceName = header.getServiceName(); final long startTime = header.getAgentStartTime(); final String hostName = agentInfo.getHostname(); @@ -56,6 +71,10 @@ public AgentInfoBo map(final PAgentInfo agentInfo, final Header header) { final int endStatus = agentInfo.getEndStatus(); final boolean container = agentInfo.getContainer(); + final ServiceId serviceId = this.serviceInfoService.getServiceId(serviceName); + final ApplicationId applicationId = this.applicationInfoService.getApplicationId(serviceId, applicationName, serviceType); + this.applicationInfoService.ensureApplicationIdInverseIndexed(serviceId, applicationName, serviceType, applicationId); + final AgentInfoBo.Builder builder = new AgentInfoBo.Builder(); builder.setHostName(hostName); builder.setIp(ip); @@ -63,6 +82,9 @@ public AgentInfoBo map(final PAgentInfo agentInfo, final Header header) { builder.setAgentId(agentId); builder.setAgentName(agentName); builder.setApplicationName(applicationName); + builder.setApplicationId(applicationId); + builder.setServiceName(serviceName); + builder.setServiceId(serviceId); builder.setServiceTypeCode(serviceType); builder.setPid(pid); builder.setVmVersion(vmVersion); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventBatchMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventBatchMapper.java index 8e6ea68b5ea4..cc7515e0af43 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventBatchMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventBatchMapper.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.mapper.grpc.event; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.event.AgentEventBo; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.grpc.Header; @@ -42,7 +43,7 @@ public GrpcAgentEventBatchMapper(GrpcDeadlockEventBoMapper deadlockEventBoMapper } public List map(final PAgentStatBatch agentStatBatch, final Header header) { - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final long startTimestamp = header.getAgentStartTime(); final List agentStats = agentStatBatch.getAgentStatList(); @@ -56,7 +57,7 @@ public List map(final PAgentStatBatch agentStatBatch, final Header final long timestamp = agentStat.getTimestamp(); final PDeadlock deadlock = agentStat.getDeadlock(); if (CollectionUtils.hasLength(deadlock.getThreadDumpList())) { - agentEventBoList.add(deadlockEventBoMapper.map(agentId, startTimestamp, timestamp, deadlock)); + agentEventBoList.add(deadlockEventBoMapper.map(AgentId.unwrap(agentId), startTimestamp, timestamp, deadlock)); } } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventMapper.java index 60417756e155..6f7403453b85 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/event/GrpcAgentEventMapper.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.mapper.grpc.event; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.event.AgentEventBo; import com.navercorp.pinpoint.common.util.CollectionUtils; import com.navercorp.pinpoint.grpc.Header; @@ -38,14 +39,14 @@ public GrpcAgentEventMapper(GrpcDeadlockEventBoMapper deadlockEventBoMapper) { } public AgentEventBo map(final PAgentStat agentStat, final Header header) { - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final long startTimestamp = header.getAgentStartTime(); final long timestamp = agentStat.getTimestamp(); if (agentStat.hasDeadlock()) { final PDeadlock deadlock = agentStat.getDeadlock(); if (CollectionUtils.hasLength(deadlock.getThreadDumpList())) { - return deadlockEventBoMapper.map(agentId, startTimestamp, timestamp, deadlock); + return deadlockEventBoMapper.map(AgentId.unwrap(agentId), startTimestamp, timestamp, deadlock); } } return null; diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatBatchMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatBatchMapper.java index 5d84f0856dcc..92a10f5e3aca 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatBatchMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatBatchMapper.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.mapper.grpc.stat; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.stat.AgentStatBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.trace.PAgentStat; @@ -42,10 +43,10 @@ public AgentStatBo map(final PAgentStatBatch agentStatBatch, final Header header return null; } final String applicationName = header.getApplicationName(); - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final long startTimestamp = header.getAgentStartTime(); - final AgentStatBo.Builder builder = new AgentStatBo.Builder(applicationName, agentId, startTimestamp); + final AgentStatBo.Builder builder = new AgentStatBo.Builder(applicationName, AgentId.unwrap(agentId), startTimestamp); for (PAgentStat agentStat : agentStatBatch.getAgentStatList()) { this.mapper.map(agentStat, builder); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatMapper.java index c1016742742c..574bff1ecaf3 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentStatMapper.java @@ -16,12 +16,13 @@ package com.navercorp.pinpoint.collector.mapper.grpc.stat; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.stat.AgentStatBo; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.server.ServerContext; import com.navercorp.pinpoint.grpc.trace.PAgentStat; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import java.util.Objects; @@ -46,12 +47,12 @@ public AgentStatBo map(PAgentStat agentStat) { final Header agentInfo = ServerContext.getAgentInfo(); final String applicationName = agentInfo.getApplicationName(); - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final long startTimestamp = agentInfo.getAgentStartTime(); - final AgentStatBo.Builder builder = AgentStatBo.newBuilder(applicationName, agentId, startTimestamp); + final AgentStatBo.Builder builder = AgentStatBo.newBuilder(applicationName, AgentId.unwrap(agentId), startTimestamp); this.map(agentStat, builder); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentUriStatMapper.java b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentUriStatMapper.java index 262bcf211c85..00204de035d2 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentUriStatMapper.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/mapper/grpc/stat/GrpcAgentUriStatMapper.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.mapper.grpc.stat; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.stat.AgentUriStatBo; import com.navercorp.pinpoint.common.server.bo.stat.EachUriStatBo; import com.navercorp.pinpoint.common.server.bo.stat.UriStatHistogram; @@ -24,7 +25,6 @@ import com.navercorp.pinpoint.grpc.trace.PAgentUriStat; import com.navercorp.pinpoint.grpc.trace.PEachUriStat; import com.navercorp.pinpoint.grpc.trace.PUriHistogram; - import org.springframework.stereotype.Component; import java.util.List; @@ -38,7 +38,7 @@ public class GrpcAgentUriStatMapper { public AgentUriStatBo map(final PAgentUriStat agentUriStat) { final Header agentInfo = ServerContext.getAgentInfo(); - final String agentId = agentInfo.getAgentId(); + final AgentId agentId = agentInfo.getAgentId(); final String applicationName = agentInfo.getApplicationName(); int bucketVersion = agentUriStat.getBucketVersion(); @@ -46,7 +46,7 @@ public AgentUriStatBo map(final PAgentUriStat agentUriStat) { AgentUriStatBo agentUriStatBo = new AgentUriStatBo(); agentUriStatBo.setServiceName(""); // TODO: add serviceName when available agentUriStatBo.setApplicationName(applicationName); - agentUriStatBo.setAgentId(agentId); + agentUriStatBo.setAgentId(AgentId.unwrap(agentId)); agentUriStatBo.setBucketVersion((byte) bucketVersion); List eachUriStatList = agentUriStat.getEachUriStatList(); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/grpc/service/KeepAliveService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/grpc/service/KeepAliveService.java index 6ac043ec757c..95b209c8fba1 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/grpc/service/KeepAliveService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/receiver/grpc/service/KeepAliveService.java @@ -21,14 +21,14 @@ import com.navercorp.pinpoint.collector.service.async.AgentProperty; import com.navercorp.pinpoint.collector.service.async.DefaultAgentProperty; import com.navercorp.pinpoint.collector.util.ManagedAgentLifeCycle; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.util.AgentEventType; import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.server.lifecycle.PingSession; import com.navercorp.pinpoint.grpc.server.lifecycle.PingSessionRegistry; - -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.Collection; import java.util.Objects; @@ -62,7 +62,7 @@ public void updateState() { private AgentProperty newChannelProperties(Header header, short serviceType) { final String applicationName = header.getApplicationName(); - final String agentId = header.getAgentId(); + final AgentId agentId = header.getAgentId(); final long agentStartTime = header.getAgentStartTime(); return new DefaultAgentProperty(applicationName, serviceType, agentId, agentStartTime, header.getProperties()); } @@ -94,7 +94,7 @@ public void updateState(PingSession pingSession, boolean closeState, AgentLifeCy try { final AgentProperty agentProperty = newChannelProperties(header, pingSession.getServiceType()); long eventIdentifier = AgentLifeCycleAsyncTaskService.createEventIdentifier((int)socketId, (int) pingSession.nextEventIdAllocator()); - this.agentLifeCycleAsyncTask.handleLifeCycleEvent(agentProperty , pingTimestamp, agentLifeCycleState, eventIdentifier); + this.agentLifeCycleAsyncTask.handleLifeCycleEvent(agentProperty, pingTimestamp, agentLifeCycleState, eventIdentifier); this.agentEventAsyncTask.handleEvent(agentProperty, pingTimestamp, agentEventType); } catch (Exception e) { logger.warn("Failed to update state. closeState:{} lifeCycle={} {}/{}", closeState, pingSession, agentLifeCycleState, agentEventType, e); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/AgentInfoService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/AgentInfoService.java index 425f83b9e860..8684f4c1dc94 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/AgentInfoService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/AgentInfoService.java @@ -18,9 +18,9 @@ import com.navercorp.pinpoint.collector.dao.AgentInfoDao; import com.navercorp.pinpoint.collector.dao.ApplicationIndexDao; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.PositiveOrZero; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @@ -37,20 +37,26 @@ public class AgentInfoService { private final AgentInfoDao agentInfoDao; - private final ApplicationIndexDao applicationIndexDao; + private final ServiceInfoService serviceInfoService; - public AgentInfoService(AgentInfoDao agentInfoDao, ApplicationIndexDao applicationIndexDao) { + public AgentInfoService( + AgentInfoDao agentInfoDao, + ApplicationIndexDao applicationIndexDao, + ServiceInfoService serviceInfoService + ) { this.agentInfoDao = Objects.requireNonNull(agentInfoDao, "agentInfoDao"); this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); } public void insert(@Valid final AgentInfoBo agentInfoBo) { agentInfoDao.insert(agentInfoBo); applicationIndexDao.insert(agentInfoBo); + serviceInfoService.insertAgentInfo(agentInfoBo); } - public AgentInfoBo getAgentInfo(@NotBlank final String agentId, @PositiveOrZero final long timestamp) { + public AgentInfoBo getAgentInfo(AgentId agentId, @PositiveOrZero final long timestamp) { return agentInfoDao.getAgentInfo(agentId, timestamp); } -} \ No newline at end of file +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/ApplicationInfoService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ApplicationInfoService.java new file mode 100644 index 000000000000..6e221c32327a --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ApplicationInfoService.java @@ -0,0 +1,65 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.collector.service; + +import com.navercorp.pinpoint.collector.dao.ApplicationInfoDao; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import com.navercorp.pinpoint.common.util.UuidUtils; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Service +public class ApplicationInfoService { + + private final ApplicationInfoDao applicationInfoDao; + + public ApplicationInfoService(ApplicationInfoDao applicationInfoDao) { + this.applicationInfoDao = Objects.requireNonNull(applicationInfoDao, "applicationInfoDao"); + } + + @Cacheable(value = "applicationNameById", key = "#applicationId") + public ApplicationInfo getApplication(ApplicationId applicationId) { + return this.applicationInfoDao.getApplication(applicationId); + } + + @Cacheable(value = "applicationIdByName", key = "{ #serviceId, #applicationName, #serviceTypeCode }") + public ApplicationId getApplicationId(ServiceId serviceId, String applicationName, short serviceTypeCode) { + ApplicationSelector tuple = new ApplicationSelector(serviceId, applicationName, serviceTypeCode); + ApplicationId applicationId = this.applicationInfoDao.getApplicationId(tuple); + if (applicationId != null) { + return applicationId; + } + + ApplicationId newApplicationId = ApplicationId.of(UuidUtils.createV4()); + ApplicationInfo newApplication = new ApplicationInfo(newApplicationId, serviceId, applicationName, serviceTypeCode); + return this.applicationInfoDao.putApplicationIdIfAbsent(newApplication); + } + + public void ensureApplicationIdInverseIndexed(ServiceId serviceId, String applicationName, short serviceTypeCode, ApplicationId applicationId) { + ApplicationInfo application = new ApplicationInfo(applicationId, serviceId, applicationName, serviceTypeCode); + this.applicationInfoDao.ensureInverse(application); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/ChainServiceInfoService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ChainServiceInfoService.java new file mode 100644 index 000000000000..5fba9e06d479 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ChainServiceInfoService.java @@ -0,0 +1,68 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.service; + +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Service +@Primary +public class ChainServiceInfoService implements ServiceInfoService { + + private final ServiceInfoService delegate; + private final ServiceInfoService staticServiceInfoService; + + public ChainServiceInfoService( + @Qualifier("serviceInfoServiceImpl") ServiceInfoService delegate, + @Qualifier("staticServiceInfoService") ServiceInfoService staticServiceInfoService + ) { + this.delegate = Objects.requireNonNull(delegate, "delegate"); + this.staticServiceInfoService = Objects.requireNonNull(staticServiceInfoService, "staticServiceInfoService"); + } + + @Override + public ServiceId getServiceId(String serviceName) { + ServiceId serviceId = staticServiceInfoService.getServiceId(serviceName); + if (serviceId != null) { + return serviceId; + } + return delegate.getServiceId(serviceName); + } + + @Override + public ServiceInfo getServiceInfo(ServiceId serviceId) { + ServiceInfo service = staticServiceInfoService.getServiceInfo(serviceId); + if (service != null) { + return service; + } + return delegate.getServiceInfo(serviceId); + } + + @Override + public void insertAgentInfo(AgentInfoBo agent) { + delegate.insertAgentInfo(agent); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/HbaseTraceService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/HbaseTraceService.java index a1a3511b9cbe..498ed3f3a8f6 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/HbaseTraceService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/HbaseTraceService.java @@ -20,6 +20,7 @@ import com.navercorp.pinpoint.collector.dao.HostApplicationMapDao; import com.navercorp.pinpoint.collector.dao.TraceDao; import com.navercorp.pinpoint.collector.event.SpanStorePublisher; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.logging.ThrottledLogger; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanChunkBo; @@ -86,7 +87,7 @@ public void insertSpanChunk(@Valid final SpanChunkBo spanChunkBo) { final List spanEventList = spanChunkBo.getSpanEventBoList(); if (spanEventList != null) { // TODO need to batch update later. - insertSpanEventList(spanEventList, applicationServiceType, spanChunkBo.getApplicationId(), spanChunkBo.getAgentId(), spanChunkBo.getEndPoint()); + insertSpanEventList(spanEventList, applicationServiceType, spanChunkBo.getApplicationName(), AgentId.unwrap(spanChunkBo.getAgentId()), spanChunkBo.getEndPoint()); } // TODO should be able to tell whether the span chunk is successfully inserted @@ -114,18 +115,18 @@ public void insertSpan(@Valid final SpanBo spanBo) { }, grpcSpanServerExecutor); } - private void insertAcceptorHost(SpanEventBo spanEvent, String applicationId, ServiceType serviceType) { + private void insertAcceptorHost(SpanEventBo spanEvent, String applicationName, ServiceType serviceType) { final String endPoint = spanEvent.getEndPoint(); if (endPoint == null) { logger.debug("endPoint is null. spanEvent:{}", spanEvent); return; } - final String destinationId = spanEvent.getDestinationId(); - if (destinationId == null) { + final String destinationAppName = spanEvent.getDestinationId(); + if (destinationAppName == null) { logger.debug("destinationId is null. spanEvent:{}", spanEvent); return; } - hostApplicationMapDao.insert(endPoint, destinationId, spanEvent.getServiceType(), applicationId, serviceType.getCode()); + hostApplicationMapDao.insert(endPoint, destinationAppName, spanEvent.getServiceType(), applicationName, serviceType.getCode()); } private void insertAcceptorHost(SpanBo span) { @@ -136,17 +137,16 @@ private void insertAcceptorHost(SpanBo span) { logger.debug("acceptorHost is null {}", span); return; } - final String spanApplicationName = span.getApplicationId(); final short applicationServiceTypeCode = getApplicationServiceType(span).getCode(); - final String parentApplicationName = span.getParentApplicationId(); + final String parentApplicationName = span.getParentApplicationName(); final short parentServiceType = span.getParentApplicationServiceType(); final ServiceType spanServiceType = registry.findServiceType(span.getServiceType()); if (spanServiceType.isQueue()) { - hostApplicationMapDao.insert(span.getEndPoint(), spanApplicationName, applicationServiceTypeCode, parentApplicationName, parentServiceType); + hostApplicationMapDao.insert(span.getEndPoint(), span.getApplicationName(), applicationServiceTypeCode, parentApplicationName, parentServiceType); } else { - hostApplicationMapDao.insert(acceptorHost, spanApplicationName, applicationServiceTypeCode, parentApplicationName, parentServiceType); + hostApplicationMapDao.insert(acceptorHost, span.getApplicationName(), applicationServiceTypeCode, parentApplicationName, parentServiceType); } } @@ -165,23 +165,23 @@ private void insertSpanStat(SpanBo span) { if (span.getParentSpanId() == -1) { if (spanServiceType.isQueue()) { // create virtual queue node - statisticsService.updateCaller(span.getAcceptorHost(), spanServiceType, span.getRemoteAddr(), span.getApplicationId(), applicationServiceType, span.getEndPoint(), span.getElapsed(), isError); + statisticsService.updateCaller(span.getAcceptorHost(), spanServiceType, span.getRemoteAddr(), span.getApplicationName(), applicationServiceType, span.getEndPoint(), span.getElapsed(), isError); - statisticsService.updateCallee(span.getApplicationId(), applicationServiceType, span.getAcceptorHost(), spanServiceType, span.getAgentId(), span.getElapsed(), isError); + statisticsService.updateCallee(span.getApplicationName(), applicationServiceType, span.getAcceptorHost(), spanServiceType, AgentId.unwrap(span.getAgentId()), span.getElapsed(), isError); } else { // create virtual user - statisticsService.updateCaller(span.getApplicationId(), ServiceType.USER, span.getAgentId(), span.getApplicationId(), applicationServiceType, span.getAgentId(), span.getElapsed(), isError); + statisticsService.updateCaller(span.getApplicationName(), ServiceType.USER, AgentId.unwrap(span.getAgentId()), span.getApplicationName(), applicationServiceType, AgentId.unwrap(span.getAgentId()), span.getElapsed(), isError); // update the span information of the current node (self) - statisticsService.updateCallee(span.getApplicationId(), applicationServiceType, span.getApplicationId(), ServiceType.USER, span.getAgentId(), span.getElapsed(), isError); + statisticsService.updateCallee(span.getApplicationName(), applicationServiceType, span.getApplicationName(), ServiceType.USER, AgentId.unwrap(span.getAgentId()), span.getElapsed(), isError); } bugCheck++; } // save statistics info only when parentApplicationContext exists // when drawing server map based on statistics info, you must know the application name of the previous node. - if (span.getParentApplicationId() != null) { - String parentApplicationName = span.getParentApplicationId(); + if (span.getParentApplicationName() != null) { + String parentApplicationName = span.getParentApplicationName(); logger.debug("Received parent application name. {}", parentApplicationName); ServiceType parentApplicationType = registry.findServiceType(span.getParentApplicationServiceType()); @@ -194,14 +194,13 @@ private void insertSpanStat(SpanBo span) { // emulate virtual queue node's accept Span and record it's acceptor host hostApplicationMapDao.insert(span.getRemoteAddr(), span.getAcceptorHost(), spanServiceType.getCode(), parentApplicationName, parentApplicationType.getCode()); // emulate virtual queue node's send SpanEvent - statisticsService.updateCaller(span.getAcceptorHost(), spanServiceType, span.getRemoteAddr(), span.getApplicationId(), applicationServiceType, span.getEndPoint(), span.getElapsed(), isError); + statisticsService.updateCaller(span.getAcceptorHost(), spanServiceType, span.getRemoteAddr(), span.getApplicationName(), applicationServiceType, span.getEndPoint(), span.getElapsed(), isError); - parentApplicationName = span.getAcceptorHost(); parentApplicationType = spanServiceType; } } - statisticsService.updateCallee(span.getApplicationId(), applicationServiceType, parentApplicationName, parentApplicationType, span.getAgentId(), span.getElapsed(), isError); + statisticsService.updateCallee(span.getApplicationName(), applicationServiceType, parentApplicationName, parentApplicationType, AgentId.unwrap(span.getAgentId()), span.getElapsed(), isError); bugCheck++; } @@ -210,7 +209,7 @@ private void insertSpanStat(SpanBo span) { // it is odd to record reversely, because of already recording the caller data at previous node. // the data may be different due to timeout or network error. - statisticsService.updateResponseTime(span.getApplicationId(), applicationServiceType, span.getAgentId(), span.getElapsed(), isError); + statisticsService.updateResponseTime(span.getApplicationName(), applicationServiceType, AgentId.unwrap(span.getAgentId()), span.getElapsed(), isError); if (bugCheck != 1) { logger.info("ambiguous span found(bug). span:{}", span); @@ -224,21 +223,21 @@ private void insertSpanEventStat(SpanBo span) { return; } if (logger.isDebugEnabled()) { - logger.debug("handle spanEvent {}/{} size:{}", span.getApplicationId(), span.getAgentId(), spanEventList.size()); + logger.debug("handle spanEvent {}/{} size:{}", span.getApplicationName(), span.getAgentId(), spanEventList.size()); } final ServiceType applicationServiceType = getApplicationServiceType(span); // TODO need to batch update later. - insertSpanEventList(spanEventList, applicationServiceType, span.getApplicationId(), span.getAgentId(), span.getEndPoint()); + insertSpanEventList(spanEventList, applicationServiceType, span.getApplicationName(), AgentId.unwrap(span.getAgentId()), span.getEndPoint()); } - private void insertSpanEventList(List spanEventList, ServiceType applicationServiceType, String applicationId, String agentId, String endPoint) { + private void insertSpanEventList(List spanEventList, ServiceType applicationServiceType, String applicationName, String agentId, String endPoint) { for (SpanEventBo spanEvent : spanEventList) { final ServiceType spanEventType = registry.findServiceType(spanEvent.getServiceType()); if (isAlias(spanEventType, spanEvent)) { - insertAcceptorHost(spanEvent, applicationId, applicationServiceType); + insertAcceptorHost(spanEvent, applicationName, applicationServiceType); continue; } @@ -253,10 +252,10 @@ private void insertSpanEventList(List spanEventList, ServiceType ap final int elapsed = spanEvent.getEndElapsed(); final boolean hasException = spanEvent.hasException(); - if (applicationId == null || spanEventApplicationName == null) { + if (applicationName == null || spanEventApplicationName == null) { throttledLogger.info("Failed to insert statistics. Cause:SpanEvent has invalid format." + "(application:{}/{}[{}], spanEventApplication:{}[{}])", - applicationId, agentId, applicationServiceType, spanEventApplicationName, spanEventType); + applicationName, agentId, applicationServiceType, spanEventApplicationName, spanEventType); continue; } @@ -264,10 +263,10 @@ private void insertSpanEventList(List spanEventList, ServiceType ap * save information to draw a server map based on statistics */ // save the information of caller (the spanevent that called span) - statisticsService.updateCaller(applicationId, applicationServiceType, agentId, spanEventApplicationName, spanEventType, spanEventEndPoint, elapsed, hasException); + statisticsService.updateCaller(applicationName, applicationServiceType, agentId, spanEventApplicationName, spanEventType, spanEventEndPoint, elapsed, hasException); // save the information of callee (the span that spanevent called) - statisticsService.updateCallee(spanEventApplicationName, spanEventType, applicationId, applicationServiceType, endPoint, elapsed, hasException); + statisticsService.updateCallee(spanEventApplicationName, spanEventType, applicationName, applicationServiceType, endPoint, elapsed, hasException); } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoService.java new file mode 100644 index 000000000000..5152993d5312 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoService.java @@ -0,0 +1,33 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.service; + +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; + +/** + * @author youngjin.kim2 + */ +public interface ServiceInfoService { + + ServiceId getServiceId(String serviceName); + + ServiceInfo getServiceInfo(ServiceId serviceId); + + void insertAgentInfo(AgentInfoBo agent); + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoServiceImpl.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoServiceImpl.java new file mode 100644 index 000000000000..ac526a448418 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/ServiceInfoServiceImpl.java @@ -0,0 +1,62 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.service; + +import com.navercorp.pinpoint.collector.dao.ServiceInfoDao; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import com.navercorp.pinpoint.common.util.UuidUtils; +import org.springframework.stereotype.Service; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Service +public class ServiceInfoServiceImpl implements ServiceInfoService { + + private final ServiceInfoDao serviceInfoDao; + + public ServiceInfoServiceImpl(ServiceInfoDao serviceInfoDao) { + this.serviceInfoDao = Objects.requireNonNull(serviceInfoDao, "serviceInfoDao"); + } + + @Override + public ServiceId getServiceId(String serviceName) { + ServiceId serviceId = this.serviceInfoDao.getServiceId(serviceName); + if (serviceId != null) { + return serviceId; + } + + ServiceId newServiceId = ServiceId.of(UuidUtils.createV4()); + return this.serviceInfoDao.putServiceIdIfAbsent(serviceName, newServiceId); + } + + @Override + public void insertAgentInfo(AgentInfoBo agent) { + ServiceId serviceId = agent.getServiceId(); + String serviceName = agent.getServiceName(); + this.serviceInfoDao.ensurePut(serviceName, serviceId); + } + + @Override + public ServiceInfo getServiceInfo(ServiceId serviceId) { + return this.serviceInfoDao.getServiceInfo(serviceId); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/StaticServiceInfoService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/StaticServiceInfoService.java new file mode 100644 index 000000000000..199b96269458 --- /dev/null +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/StaticServiceInfoService.java @@ -0,0 +1,58 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.collector.service; + +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import org.springframework.stereotype.Service; + +/** + * @author youngjin.kim2 + */ +@Service +public class StaticServiceInfoService implements ServiceInfoService { + + private static final ServiceInfo[] reservations = new ServiceInfo[] { + new ServiceInfo(ServiceId.DEFAULT_ID, ServiceId.DEFAULT_SERVICE_NAME), + }; + + @Override + public ServiceId getServiceId(String serviceName) { + for (ServiceInfo reservation : reservations) { + if (reservation.name().equals(serviceName)) { + return reservation.id(); + } + } + return null; + } + + @Override + public ServiceInfo getServiceInfo(ServiceId serviceId) { + for (ServiceInfo reservation : reservations) { + if (reservation.id().equals(serviceId)) { + return reservation; + } + } + return null; + } + + @Override + public void insertAgentInfo(AgentInfoBo agent) { + throw new UnsupportedOperationException("insertAgentInfo"); + } + +} diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/StatisticsService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/StatisticsService.java index 9e256bee8f06..736481cb1218 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/StatisticsService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/StatisticsService.java @@ -67,7 +67,10 @@ public void updateCaller( int elapsed, boolean isError ) { - mapStatisticsCallerDao.update(callerApplicationName, callerServiceType, callerAgentId, calleeApplicationName, calleeServiceType, calleeHost, elapsed, isError); + mapStatisticsCallerDao.update( + callerApplicationName, callerServiceType, callerAgentId, + calleeApplicationName, calleeServiceType, calleeHost, + elapsed, isError); } /** @@ -93,7 +96,10 @@ public void updateCallee( int elapsed, boolean isError ) { - mapStatisticsCalleeDao.update(calleeApplicationName, calleeServiceType, callerApplicationName, callerServiceType, callerHost, elapsed, isError); + mapStatisticsCalleeDao.update( + calleeApplicationName, calleeServiceType, + callerApplicationName, callerServiceType, + callerHost, elapsed, isError); } public void updateResponseTime( diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentEventAsyncTaskService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentEventAsyncTaskService.java index 39c91ad89764..bfd86e97a96b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentEventAsyncTaskService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentEventAsyncTaskService.java @@ -17,10 +17,11 @@ package com.navercorp.pinpoint.collector.service.async; import com.navercorp.pinpoint.collector.service.AgentEventService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.event.AgentEventBo; import com.navercorp.pinpoint.common.server.util.AgentEventType; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -45,9 +46,9 @@ public void handleEvent(final AgentProperty agentProperty, long eventTimestamp, Objects.requireNonNull(agentProperty, "agentProperty"); Objects.requireNonNull(eventType, "eventType"); - final String agentId = agentProperty.getAgentId(); + final AgentId agentId = agentProperty.getAgentId(); final long startTimestamp = agentProperty.getStartTime(); - final AgentEventBo agentEventBo = newAgentEventBo(agentId, startTimestamp, eventTimestamp, eventType); + final AgentEventBo agentEventBo = newAgentEventBo(AgentId.unwrap(agentId), startTimestamp, eventTimestamp, eventType); this.agentEventService.insert(agentEventBo); } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentLifeCycleAsyncTaskService.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentLifeCycleAsyncTaskService.java index 7a0b9269fa35..f5949445e24b 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentLifeCycleAsyncTaskService.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentLifeCycleAsyncTaskService.java @@ -19,13 +19,14 @@ import com.navercorp.pinpoint.collector.config.CollectorProperties; import com.navercorp.pinpoint.collector.service.AgentLifeCycleService; import com.navercorp.pinpoint.collector.service.StatisticsService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentLifeCycleBo; import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.BytesUtils; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -60,7 +61,7 @@ public void handleLifeCycleEvent(AgentProperty agentProperty, long eventTimestam Objects.requireNonNull(agentProperty, "agentProperty"); Objects.requireNonNull(agentLifeCycleState, "agentLifeCycleState"); - final String agentId = agentProperty.getAgentId(); + final AgentId agentId = agentProperty.getAgentId(); if (agentId == null) { logger.warn("Failed to handle event of agent life cycle, agentId is null. agentProperty={}", agentProperty); return; @@ -72,12 +73,12 @@ public void handleLifeCycleEvent(AgentProperty agentProperty, long eventTimestam } final long startTimestamp = agentProperty.getStartTime(); - final AgentLifeCycleBo agentLifeCycleBo = new AgentLifeCycleBo(agentId, startTimestamp, eventTimestamp, eventIdentifier, agentLifeCycleState); + final AgentLifeCycleBo agentLifeCycleBo = new AgentLifeCycleBo(AgentId.unwrap(agentId), startTimestamp, eventTimestamp, eventIdentifier, agentLifeCycleState); agentLifeCycleService.insert(agentLifeCycleBo); final ServiceType serviceType = registry.findServiceType(agentProperty.getServiceType()); if (isUpdateAgentState(serviceType)) { - statisticsService.updateAgentState(applicationName, serviceType, agentId); + statisticsService.updateAgentState(applicationName, serviceType, AgentId.unwrap(agentId)); } } @@ -85,7 +86,7 @@ public void handleLifeCycleEvent(AgentProperty agentProperty, long eventTimestam public void handlePingEvent(AgentProperty agentProperty) { Objects.requireNonNull(agentProperty, "agentProperty"); - final String agentId = agentProperty.getAgentId(); + final AgentId agentId = agentProperty.getAgentId(); if (agentId == null) { logger.warn("Failed to handle event of agent ping, agentId is null. agentProperty={}", agentProperty); return; @@ -99,7 +100,7 @@ public void handlePingEvent(AgentProperty agentProperty) { final ServiceType serviceType = registry.findServiceType(agentProperty.getServiceType()); if (isUpdateAgentState(serviceType)) { - statisticsService.updateAgentState(applicationName, serviceType, agentId); + statisticsService.updateAgentState(applicationName, serviceType, AgentId.unwrap(agentId)); } } @@ -107,10 +108,7 @@ private boolean isUpdateAgentState(ServiceType serviceType) { if (!collectorProperties.isStatisticsAgentStateEnable()) { return false; } - if (serviceType == null || serviceType == ServiceType.UNDEFINED) { - return false; - } - return true; + return serviceType != null && serviceType != ServiceType.UNDEFINED; } public static long createEventIdentifier(int socketId, int eventCounter) { diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentProperty.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentProperty.java index 6e4726e18374..7aa0933bcc53 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentProperty.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentProperty.java @@ -16,13 +16,15 @@ package com.navercorp.pinpoint.collector.service.async; +import com.navercorp.pinpoint.common.id.AgentId; + /** * @author Woonduk Kang(emeroad) * @author jaehong.kim */ public interface AgentProperty { String getApplicationName(); - String getAgentId(); + AgentId getAgentId(); long getStartTime(); Object get(String key); short getServiceType(); diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentPropertyChannelAdaptor.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentPropertyChannelAdaptor.java index d87ce4722c0e..3472b851009d 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentPropertyChannelAdaptor.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/AgentPropertyChannelAdaptor.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.service.async; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.rpc.server.ChannelProperties; import java.util.Objects; @@ -38,8 +39,8 @@ public String getApplicationName() { } @Override - public String getAgentId() { - return channelProperties.getAgentId(); + public AgentId getAgentId() { + return AgentId.of(channelProperties.getAgentId()); } @Override @@ -59,9 +60,7 @@ public short getServiceType() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("AgentPropertyChannelAdaptor{"); - sb.append("channelProperties=").append(channelProperties); - sb.append('}'); - return sb.toString(); + return "AgentPropertyChannelAdaptor{" + "channelProperties=" + channelProperties + + '}'; } } \ No newline at end of file diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/DefaultAgentProperty.java b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/DefaultAgentProperty.java index 1ca6283de879..3b9eed9e4f75 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/DefaultAgentProperty.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/service/async/DefaultAgentProperty.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.collector.service.async; +import com.navercorp.pinpoint.common.id.AgentId; + import java.util.Map; import java.util.Objects; @@ -25,12 +27,12 @@ */ public class DefaultAgentProperty implements AgentProperty { private final String applicationName; - private final String agentId; + private final AgentId agentId; private final long agentStartTime; private final Map properties; private final short serviceType; - public DefaultAgentProperty(String applicationName, short serviceType, String agentId, long agentStartTime, Map properties) { + public DefaultAgentProperty(String applicationName, short serviceType, AgentId agentId, long agentStartTime, Map properties) { this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); this.serviceType = serviceType; this.agentId = Objects.requireNonNull(agentId, "agentId"); @@ -49,7 +51,7 @@ public short getServiceType() { } @Override - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -65,13 +67,11 @@ public Object get(String key) { @Override public String toString() { - final StringBuilder sb = new StringBuilder("DefaultAgentProperty{"); - sb.append("applicationName='").append(applicationName).append('\''); - sb.append(", agentId='").append(agentId).append('\''); - sb.append(", agentStartTime=").append(agentStartTime); - sb.append(", properties=").append(properties); - sb.append(", serviceType=").append(serviceType); - sb.append('}'); - return sb.toString(); + return "DefaultAgentProperty{" + "applicationName='" + applicationName + '\'' + + ", agentId='" + agentId + '\'' + + ", agentStartTime=" + agentStartTime + + ", properties=" + properties + + ", serviceType=" + serviceType + + '}'; } } diff --git a/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java index 5596c9170c4a..10afb76342fd 100644 --- a/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java +++ b/collector/src/main/java/com/navercorp/pinpoint/collector/util/CollectorUtils.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.collector.util; import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.IdValidateUtils; import com.navercorp.pinpoint.common.util.StringUtils; @@ -50,6 +51,10 @@ public static String getHumanFriendlyServerIdentifier() { return hostName + "@" + pid; } + public static void checkAgentId(final AgentId agentId) { + checkAgentId(AgentId.unwrap(agentId)); + } + public static void checkAgentId(final String agentId) { if (!IdValidateUtils.validateId(agentId)) { throw new IllegalArgumentException("invalid agentId. agentId=" + agentId); @@ -57,7 +62,7 @@ public static void checkAgentId(final String agentId) { } public static void checkApplicationName(final String applicationName) { - if (!IdValidateUtils.validateId(applicationName)) { + if (!IdValidateUtils.validateId(applicationName, PinpointConstants.APPLICATION_NAME_MAX_LEN)) { throw new IllegalArgumentException("invalid applicationName. applicationName=" + applicationName); } } diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2Test.java b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2Test.java index 3c2afd7b41bf..e5a2015853af 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2Test.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/dao/hbase/encode/ApplicationIndexRowKeyEncoderV2Test.java @@ -18,6 +18,7 @@ package com.navercorp.pinpoint.collector.dao.hbase.encode; import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.sematext.hbase.wd.AbstractRowKeyDistributor; import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix; import org.apache.hadoop.hbase.util.Bytes; @@ -25,6 +26,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.UUID; + import static org.assertj.core.api.Assertions.assertThat; class ApplicationIndexRowKeyEncoderV2Test { @@ -44,8 +47,7 @@ private AbstractRowKeyDistributor applicationTraceIndexDistributor() { @Test void newRowKey() { - - byte[] rowKey = encoder.newRowKey("agent", 100, (byte) 10); + byte[] rowKey = encoder.newRowKey(ApplicationId.of(new UUID(100, 100)), 100, (byte) 10); int fuzzySize = PinpointConstants.APPLICATION_NAME_MAX_LEN + Bytes.SIZEOF_LONG + 1; assertThat(rowKey).hasSize(fuzzySize); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcAgentUriMetricHandlerV2Test.java b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcAgentUriMetricHandlerV2Test.java index 8bc276c376fe..73fa80ddf3e4 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcAgentUriMetricHandlerV2Test.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcAgentUriMetricHandlerV2Test.java @@ -26,6 +26,7 @@ import com.navercorp.pinpoint.collector.mapper.grpc.stat.GrpcAgentUriStatMapper; import com.navercorp.pinpoint.collector.service.AgentStatService; import com.navercorp.pinpoint.collector.service.AgentUriStatService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.trace.UriStatHistogramBucket; import com.navercorp.pinpoint.grpc.Header; @@ -95,7 +96,8 @@ public void skipTest() { public void handleTest() { AgentUriStatService mockAgentUriStatService = mock(AgentUriStatService.class); - attachContext(new Header("name", "agentId", "agentName", "applicationName", ServiceType.UNKNOWN.getCode(), System.currentTimeMillis(), Header.SOCKET_ID_NOT_EXIST, new ArrayList<>())); + attachContext(new Header("name", AgentId.of("agentId"), "agentName", "applicationName", "serviceName", + ServiceType.UNKNOWN.getCode(), System.currentTimeMillis(), Header.SOCKET_ID_NOT_EXIST, new ArrayList<>())); PAgentUriStat pAgentUriStat = createPAgentUriStat(); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandlerTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandlerTest.java index 97a36fb1c259..40ba50ba6dca 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandlerTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/handler/grpc/GrpcApiMetaDataHandlerTest.java @@ -1,6 +1,7 @@ package com.navercorp.pinpoint.collector.handler.grpc; import com.navercorp.pinpoint.collector.service.ApiMetaDataService; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.ApiMetaDataBo; import com.navercorp.pinpoint.common.server.bo.MethodTypeEnum; import com.navercorp.pinpoint.grpc.Header; @@ -34,7 +35,7 @@ public void stubToApiMetaData() { .setLocation("/Users/workspace/pinpoint/@pinpoint-naver-apm/pinpoint-agent-node/samples/express/src/routes/index.js") .build(); - Header header = new Header("name", "express-node-sample-id", "agentName", "applicationName", 0, 1668495162817L, 0, Collections.emptyList()); + Header header = new Header("name", AgentId.of("express-node-sample-id"), "agentName", "applicationName", "serviceName", 0, 1668495162817L, 0, Collections.emptyList()); Context headerContext = Context.current().withValue(ServerContext.AGENT_INFO_KEY, header); headerContext.run(new Runnable() { @Override diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/AgentClientMock.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/AgentClientMock.java index 5a0e5a72a10e..1b0352fa773d 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/AgentClientMock.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/AgentClientMock.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.collector.receiver.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.AgentHeaderFactory; import com.navercorp.pinpoint.grpc.client.HeaderFactory; @@ -66,7 +67,7 @@ public AgentClientMock(final String host, final int port, final boolean agentHea NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); if (agentHeader) { - HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockAgentName", "mockApplicationName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); + HeaderFactory headerFactory = new AgentHeaderFactory(AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); final Metadata extraHeaders = headerFactory.newHeader(); final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); builder.intercept(headersInterceptor); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientMock.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientMock.java index 6bdb7c43ca88..2874bff3cb22 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientMock.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientMock.java @@ -18,6 +18,7 @@ import com.google.common.util.concurrent.Uninterruptibles; import com.google.protobuf.GeneratedMessageV3; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.concurrent.PinpointThreadFactory; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.AgentHeaderFactory; @@ -44,9 +45,7 @@ import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -55,8 +54,6 @@ public class MetadataClientMock { private static final int MAX_TOTAL_ATTEMPTS = 3; - private static final ScheduledExecutorService RECONNECT_SCHEDULER - = Executors.newScheduledThreadPool(1, new PinpointThreadFactory("Pinpoint-reconnect-thread")); private final Logger logger = LogManager.getLogger(this.getClass()); @@ -67,18 +64,15 @@ public class MetadataClientMock { private final MetadataGrpc.MetadataStub metadataStub; private final AtomicInteger requestCounter = new AtomicInteger(0); - private final AtomicInteger responseCounter = new AtomicInteger(0); private final List responseList = new ArrayList<>(); - public MetadataClientMock(final String host, final int port, final boolean agentHeader) { - - + public MetadataClientMock(final String host, final int port) { this.retryTimer = newTimer(this.getClass().getName()); this.channelFactory = newChannelFactory(); this.channel = channelFactory.build(host, port); this.metadataStub = MetadataGrpc.newStub(channel); - this.retryScheduler = new RetryScheduler() { + this.retryScheduler = new RetryScheduler<>() { @Override public boolean isSuccess(PResult response) { return response.getSuccess(); @@ -92,7 +86,7 @@ public void scheduleNextRetry(GeneratedMessageV3 request, int remainingRetryCoun } private ChannelFactory newChannelFactory() { - HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockAgentName", "mockApplicationName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); + HeaderFactory headerFactory = new AgentHeaderFactory(AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); ChannelFactoryBuilder channelFactoryBuilder = new DefaultChannelFactoryBuilder("MetadataClientMock"); channelFactoryBuilder.setHeaderFactory(headerFactory); channelFactoryBuilder.setClientOption(new ClientOption()); @@ -114,10 +108,6 @@ private Timer newTimer(String name) { return new HashedWheelTimer(threadFactory, 100, TimeUnit.MILLISECONDS, 512, false, 100); } - public void apiMetaData() { - apiMetaData(1); - } - public void apiMetaData(final int count) { for (int i = 0; i < count; i++) { PApiMetaData request = PApiMetaData.newBuilder().setApiId(i).build(); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientTestMain.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientTestMain.java index c7885773a924..3180705d17af 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientTestMain.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/MetadataClientTestMain.java @@ -26,7 +26,7 @@ public class MetadataClientTestMain { public static void main(String[] args) { - MetadataClientMock clientMock = new MetadataClientMock("localhost", 9997, true); + MetadataClientMock clientMock = new MetadataClientMock("localhost", 9997); clientMock.apiMetaData(100); Uninterruptibles.sleepUninterruptibly(60, SECONDS); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/SpanClientMock.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/SpanClientMock.java index 9e8efa57ffef..dddea21b9ac5 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/SpanClientMock.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/SpanClientMock.java @@ -18,6 +18,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.Empty; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.AgentHeaderFactory; import com.navercorp.pinpoint.grpc.client.ChannelFactory; @@ -61,8 +62,6 @@ public class SpanClientMock { private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); private final ReconnectExecutor reconnectExecutor = new ReconnectExecutor(scheduledExecutorService); - - private final ManagedChannel channel; private final SpanGrpc.SpanStub spanStub; private final ChannelFactory channelFactory; @@ -133,7 +132,7 @@ private StreamObserver newSpanStream() { System.out.println("NEW SpanStream"); System.out.println("###"); StreamId spanId = StreamId.newStreamId("SpanStream"); - StreamEventListener listener = new StreamEventListener() { + StreamEventListener listener = new StreamEventListener<>() { @Override public void start(ClientCallStreamObserver requestStream) { @@ -156,7 +155,7 @@ public void onCompleted() { private ChannelFactory newChannelFactory() { - HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockAgentName", "mockApplicationName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); + HeaderFactory headerFactory = new AgentHeaderFactory(AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); ChannelFactoryBuilder channelFactoryBuilder = new DefaultChannelFactoryBuilder("SpanClientMock"); final ClientInterceptor unaryCallDeadlineInterceptor = new UnaryCallDeadlineInterceptor(1000); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/StatClientMock.java b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/StatClientMock.java index 96cb98a28c2e..c00747f695d7 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/StatClientMock.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/receiver/grpc/StatClientMock.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.collector.receiver.grpc; import com.google.protobuf.Empty; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.AgentHeaderFactory; import com.navercorp.pinpoint.grpc.client.HeaderFactory; @@ -30,8 +31,8 @@ import io.grpc.netty.NettyChannelBuilder; import io.grpc.stub.MetadataUtils; import io.grpc.stub.StreamObserver; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.concurrent.TimeUnit; @@ -43,7 +44,7 @@ public class StatClientMock { public StatClientMock(final String host, final int port) { NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); - HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockAgentName", "mockApplicationName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); + HeaderFactory headerFactory = new AgentHeaderFactory(AgentId.of("mockAgentId"), "mockAgentName", "mockApplicationName", "mockServiceName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); final Metadata extraHeaders = headerFactory.newHeader(); final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); builder.intercept(headersInterceptor); diff --git a/collector/src/test/java/com/navercorp/pinpoint/collector/sampler/SimpleSpanFactoryTest.java b/collector/src/test/java/com/navercorp/pinpoint/collector/sampler/SimpleSpanFactoryTest.java index 710afb7c2129..6c3ce26ffe03 100644 --- a/collector/src/test/java/com/navercorp/pinpoint/collector/sampler/SimpleSpanFactoryTest.java +++ b/collector/src/test/java/com/navercorp/pinpoint/collector/sampler/SimpleSpanFactoryTest.java @@ -1,6 +1,7 @@ package com.navercorp.pinpoint.collector.sampler; import com.navercorp.pinpoint.collector.config.CollectorProperties; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import com.navercorp.pinpoint.common.server.bo.BasicSpan; @@ -38,7 +39,7 @@ public void TransactionIdSampleTest() { SpanSamplerFactory spanSamplerFactory = new SimpleSpanSamplerFactory(mockProperties); Sampler sampler = spanSamplerFactory.createBasicSpanSampler(); - String agentId = "testAgentId"; + AgentId agentId = AgentId.of("testAgentId"); long time = System.currentTimeMillis(); SpanChunkBo mockSpanChunkBo = mock(SpanChunkBo.class); SpanBo mockSpanBo = mock(SpanBo.class); @@ -54,7 +55,7 @@ public void TransactionIdSampleTest() { verify(mockSpanChunkBo, atLeastOnce()).getTransactionId(); } - private TransactionId createTransactionId(String agentId, long agentStartTime, long sequenceId) { + private TransactionId createTransactionId(AgentId agentId, long agentStartTime, long sequenceId) { return TransactionIdUtils.parseTransactionId(TransactionIdUtils.formatString(agentId, agentStartTime, sequenceId)); } diff --git a/commons-buffer/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java b/commons-buffer/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java index 1cfec07f5b04..43cd791d8650 100644 --- a/commons-buffer/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java +++ b/commons-buffer/src/main/java/com/navercorp/pinpoint/common/buffer/Buffer.java @@ -19,6 +19,7 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.UUID; /** * @author emeroad @@ -89,7 +90,10 @@ public interface Buffer { void putLong(long v); - + default void putUUID(UUID v) { + putLong(v.getMostSignificantBits()); + putLong(v.getLeastSignificantBits()); + } /** * put value using the variable-length encoding especially for constants @@ -150,6 +154,12 @@ public interface Buffer { long readLong(); + default UUID readUUID() { + long mostSigBits = readLong(); + long leastSigBits = readLong(); + return new UUID(mostSigBits, leastSigBits); + } + long readVLong(); long readSVLong(); diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseColumnFamily.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseColumnFamily.java index 1198996d531d..b6dac4629e15 100644 --- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseColumnFamily.java +++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseColumnFamily.java @@ -82,12 +82,29 @@ private ApiMetadata(HbaseTable hBaseTable, byte[] columnFamilyName) { } public static final ApplicationIndex APPLICATION_INDEX_AGENTS = new ApplicationIndex(HbaseTable.APPLICATION_INDEX, Bytes.toBytes("Agents")); + public static final ApplicationIndex APPLICATION_INDEX_AGENTS_VER2 = new ApplicationIndex(HbaseTable.APPLICATION_INDEX_VER2, Bytes.toBytes("Agents")); public static class ApplicationIndex extends HbaseColumnFamily { private ApplicationIndex(HbaseTable hBaseTable, byte[] columnFamilyName) { super(hBaseTable, columnFamilyName); } } + public static final ApplicationId APPLICATION_ID_FORWARD = new ApplicationId(HbaseTable.APPLICATION_ID, Bytes.toBytes("F")); + public static final ApplicationId APPLICATION_ID_INVERSE = new ApplicationId(HbaseTable.APPLICATION_ID, Bytes.toBytes("I")); + public static class ApplicationId extends HbaseColumnFamily { + private ApplicationId(HbaseTable hBaseTable, byte[] columnFamilyName) { + super(hBaseTable, columnFamilyName); + } + } + + public static final ServiceId SERVICE_ID_FORWARD = new ServiceId(HbaseTable.SERVICE_ID, Bytes.toBytes("F")); + public static final ServiceId SERVICE_ID_INVERSE = new ServiceId(HbaseTable.SERVICE_ID, Bytes.toBytes("I")); + public static class ServiceId extends HbaseColumnFamily { + private ServiceId(HbaseTable hBaseTable, byte[] columnFamilyName) { + super(hBaseTable, columnFamilyName); + } + } + public static final ApplicationStatStatistics APPLICATION_STAT_STATISTICS = new ApplicationStatStatistics(HbaseTable.APPLICATION_STAT_AGGRE, Bytes.toBytes("S")); public static class ApplicationStatStatistics extends HbaseColumnFamily { public int TIMESPAN_MS = 5 * 60 * 1000; @@ -99,6 +116,8 @@ private ApplicationStatStatistics(HbaseTable hBaseTable, byte[] columnFamilyName public static final ApplicationTraceIndexTrace APPLICATION_TRACE_INDEX_TRACE = new ApplicationTraceIndexTrace(HbaseTable.APPLICATION_TRACE_INDEX, Bytes.toBytes("I")); public static final ApplicationTraceIndexTrace APPLICATION_TRACE_INDEX_META = new ApplicationTraceIndexTrace(HbaseTable.APPLICATION_TRACE_INDEX, Bytes.toBytes("M")); + public static final ApplicationTraceIndexTrace APPLICATION_TRACE_INDEX_TRACE_VER2 = new ApplicationTraceIndexTrace(HbaseTable.APPLICATION_TRACE_INDEX_VER2, Bytes.toBytes("I")); + public static final ApplicationTraceIndexTrace APPLICATION_TRACE_INDEX_META_VER2 = new ApplicationTraceIndexTrace(HbaseTable.APPLICATION_TRACE_INDEX_VER2, Bytes.toBytes("M")); public static class ApplicationTraceIndexTrace extends HbaseColumnFamily { public static final int ROW_DISTRIBUTE_SIZE = 1; // applicationIndex hash size diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTable.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTable.java index 07990ce8494f..3485a0ef2b8c 100644 --- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTable.java +++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/HbaseTable.java @@ -29,11 +29,16 @@ public enum HbaseTable { AGENT_URI_STAT("AgentUriStat"), API_METADATA("ApiMetaData"), APPLICATION_INDEX("ApplicationIndex"), + APPLICATION_INDEX_VER2("ApplicationIndex_Ver2"), + APPLICATION_ID("ApplicationId"), + SERVICE_ID("ServiceId"), APPLICATION_STAT_AGGRE("ApplicationStatAggre"), APPLICATION_TRACE_INDEX("ApplicationTraceIndex"), + APPLICATION_TRACE_INDEX_VER2("ApplicationTraceIndex_Ver2"), HOST_APPLICATION_MAP_VER2("HostApplicationMap_Ver2"), MAP_STATISTICS_CALLEE_VER2("ApplicationMapStatisticsCallee_Ver2"), MAP_STATISTICS_CALLER_VER2("ApplicationMapStatisticsCaller_Ver2"), + MAP_STATISTICS_CALLEE_VER3("ApplicationMapStatisticsCallee_Ver3"), MAP_STATISTICS_SELF_VER2("ApplicationMapStatisticsSelf_Ver2"), SQL_METADATA_VER2("SqlMetaData_Ver2"), SQL_UID_METADATA("SqlUidMetaData"), diff --git a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/util/CellUtils.java b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/util/CellUtils.java index 8a9d8fdd0d97..b18b2df0952b 100644 --- a/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/util/CellUtils.java +++ b/commons-hbase/src/main/java/com/navercorp/pinpoint/common/hbase/util/CellUtils.java @@ -1,5 +1,7 @@ package com.navercorp.pinpoint.common.hbase.util; +import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer; import com.navercorp.pinpoint.common.util.ArrayUtils; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; @@ -7,6 +9,7 @@ import org.apache.hadoop.hbase.util.Bytes; import java.util.Objects; +import java.util.UUID; public final class CellUtils { private CellUtils() { @@ -52,6 +55,12 @@ public static String valueToString(Cell cell) { return Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); } + public static UUID valueToUUID(Cell cell) { + Objects.requireNonNull(cell, "cell"); + Buffer buffer = new OffsetFixedBuffer(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); + return buffer.readUUID(); + } + public static Cell lastCell(Cell[] rawCells, byte[] columnFamily) { Cell last = null; diff --git a/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionId.java b/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionId.java index d2cca5c4525e..cd23f0b56d1e 100644 --- a/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionId.java +++ b/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionId.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.common.profiler.util; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.IdValidateUtils; /** @@ -23,11 +24,15 @@ */ public class TransactionId { - private final String agentId; + private final AgentId agentId; private final long agentStartTime; private final long transactionSequence; public TransactionId(String agentId, long agentStartTime, long transactionSequence) { + this(AgentId.of(agentId), agentStartTime, transactionSequence); + } + + public TransactionId(AgentId agentId, long agentStartTime, long transactionSequence) { if (!IdValidateUtils.validateId(agentId)) { throw new IllegalArgumentException("invalid agentId"); } @@ -36,7 +41,7 @@ public TransactionId(String agentId, long agentStartTime, long transactionSequen this.transactionSequence = transactionSequence; } - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -58,9 +63,7 @@ public boolean equals(Object o) { if (agentStartTime != that.agentStartTime) return false; if (transactionSequence != that.transactionSequence) return false; - if (!agentId.equals(that.agentId)) return false; - - return true; + return agentId.equals(that.agentId); } @Override diff --git a/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtils.java b/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtils.java index 838f5f480963..01de1252d2e1 100644 --- a/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtils.java +++ b/commons-profiler/src/main/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtils.java @@ -19,6 +19,7 @@ import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.buffer.Buffer; import com.navercorp.pinpoint.common.buffer.FixedBuffer; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.ArrayUtils; import com.navercorp.pinpoint.common.util.BytesUtils; import com.navercorp.pinpoint.common.util.IdValidateUtils; @@ -44,7 +45,7 @@ public static String formatString(TransactionId transactionId) { return formatString(transactionId.getAgentId(), transactionId.getAgentStartTime(), transactionId.getTransactionSequence()); } - public static String formatString(String agentId, long agentStartTime, long transactionSequence) { + public static String formatString(AgentId agentId, long agentStartTime, long transactionSequence) { Objects.requireNonNull(agentId, "agentId"); return agentId + @@ -54,19 +55,19 @@ public static String formatString(String agentId, long agentStartTime, long tran transactionSequence; } - public static byte[] formatBytes(String agentId, long agentStartTime, long transactionSequence) { + public static byte[] formatBytes(AgentId agentId, long agentStartTime, long transactionSequence) { return writeTransactionId(agentId, agentStartTime, transactionSequence); } - public static ByteBuffer formatByteBuffer(String agentId, long agentStartTime, long transactionSequence) { + public static ByteBuffer formatByteBuffer(AgentId agentId, long agentStartTime, long transactionSequence) { final byte[] buffer = writeTransactionId(agentId, agentStartTime, transactionSequence); return ByteBuffer.wrap(buffer); } - private static byte[] writeTransactionId(String agentId, long agentStartTime, long transactionSequence) { + private static byte[] writeTransactionId(AgentId agentId, long agentStartTime, long transactionSequence) { // agentId may be null // version + prefixed size + string + long + long - final byte[] agentIdBytes = BytesUtils.toBytes(agentId); + final byte[] agentIdBytes = toBytes(agentId); final int agentIdLength = ArrayUtils.getLength(agentIdBytes, Buffer.NULL); final int zigZagAgentIdLength = BytesUtils.intToZigZag(agentIdLength); final int agentIdPrefixSize = BytesUtils.computeVar32Size(zigZagAgentIdLength); @@ -88,7 +89,14 @@ private static byte[] writeTransactionId(String agentId, long agentStartTime, lo return buffer; } - public static TransactionId parseTransactionId(final byte[] transactionId, String defaultAgentId) { + private static byte[] toBytes(AgentId agentId) { + if (agentId == null) { + return null; + } + return BytesUtils.toBytes(AgentId.unwrap(agentId)); + } + + public static TransactionId parseTransactionId(final byte[] transactionId, AgentId defaultAgentId) { Objects.requireNonNull(transactionId, "transactionId"); final Buffer buffer = new FixedBuffer(transactionId); @@ -98,7 +106,7 @@ public static TransactionId parseTransactionId(final byte[] transactionId, Strin } String agentId = buffer.readPrefixedString(); - agentId = StringUtils.defaultString(agentId, defaultAgentId); + agentId = StringUtils.defaultString(agentId, AgentId.unwrap(defaultAgentId)); if (!IdValidateUtils.validateId(agentId)) { throw new IllegalArgumentException("invalid transactionId:" + Arrays.toString(transactionId)); } @@ -106,7 +114,7 @@ public static TransactionId parseTransactionId(final byte[] transactionId, Strin final long agentStartTime = buffer.readVLong(); final long transactionSequence = buffer.readVLong(); - return new TransactionId(agentId, agentStartTime,transactionSequence); + return new TransactionId(AgentId.of(agentId), agentStartTime,transactionSequence); } public static TransactionId parseTransactionId(final String transactionId) { @@ -122,7 +130,7 @@ public static TransactionId parseTransactionId(final String transactionId) { if (!IdValidateUtils.checkId(transactionId, 0, agentIdIndex)) { throw new IllegalArgumentException("invalid transactionId:" + transactionId); } - final String agentId = transactionId.substring(0, agentIdIndex); + final AgentId agentId = AgentId.of(transactionId.substring(0, agentIdIndex)); final int agentStartTimeIndex = nextIndex(transactionId, agentIdIndex + 1); if (agentStartTimeIndex == -1) { diff --git a/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdComparatorTest.java b/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdComparatorTest.java index 8b2aae1e1897..35d2f8eba1bd 100644 --- a/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdComparatorTest.java +++ b/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdComparatorTest.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.common.profiler.util; +import com.navercorp.pinpoint.common.id.AgentId; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Assertions; @@ -33,37 +34,37 @@ public class TransactionIdComparatorTest { @Test public void sameAll() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 1, 1); + TransactionId id1 = new TransactionId(AgentId.of("A1"), 1, 1); + TransactionId id2 = new TransactionId(AgentId.of("A1"), 1, 1); Assertions.assertEquals(0, comparator.compare(id1, id2)); } @Test public void diffAgentStartTimeAsc() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 2, 1); + TransactionId id1 = new TransactionId(AgentId.of("A1"), 1, 1); + TransactionId id2 = new TransactionId(AgentId.of("A1"), 2, 1); Assertions.assertEquals(-1, comparator.compare(id1, id2)); } @Test public void diffAgentStartTimeDesc() { - TransactionId id1 = new TransactionId("A1", 2, 1); - TransactionId id2 = new TransactionId("A1", 1, 1); + TransactionId id1 = new TransactionId(AgentId.of("A1"), 2, 1); + TransactionId id2 = new TransactionId(AgentId.of("A1"), 1, 1); Assertions.assertEquals(1, comparator.compare(id1, id2)); } @Test public void diffSeqAsc() { - TransactionId id1 = new TransactionId("A1", 1, 1); - TransactionId id2 = new TransactionId("A1", 1, 2); + TransactionId id1 = new TransactionId(AgentId.of("A1"), 1, 1); + TransactionId id2 = new TransactionId(AgentId.of("A1"), 1, 2); Assertions.assertEquals(-1, comparator.compare(id1, id2)); } @Test public void diffSeqDesc() { - TransactionId id1 = new TransactionId("A1", 1, 2); - TransactionId id2 = new TransactionId("A1", 1, 1); + TransactionId id1 = new TransactionId(AgentId.of("A1"), 1, 2); + TransactionId id2 = new TransactionId(AgentId.of("A1"), 1, 1); Assertions.assertEquals(1, comparator.compare(id1, id2)); } @@ -77,7 +78,7 @@ public void order() { List list = new ArrayList<>(); for (int i = 0; i < 10; i++) { - list.add(new TransactionId("A", 1, numbers.get(i))); + list.add(new TransactionId(AgentId.of("A"), 1, numbers.get(i))); } logger.debug("{}", list); diff --git a/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtilsTest.java b/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtilsTest.java index c3472e447cfe..de96a386022a 100644 --- a/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtilsTest.java +++ b/commons-profiler/src/test/java/com/navercorp/pinpoint/common/profiler/util/TransactionIdUtilsTest.java @@ -19,6 +19,7 @@ import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.buffer.AutomaticBuffer; import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.id.AgentId; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -30,12 +31,12 @@ */ public class TransactionIdUtilsTest { - public static final String AGENT_ID = "test"; + public static final AgentId AGENT_ID = AgentId.of("test"); @Test public void testParseTransactionId() { TransactionId transactionId = TransactionIdUtils.parseTransactionId(AGENT_ID + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "2"); - Assertions.assertEquals(transactionId.getAgentId(), "test"); + Assertions.assertEquals(transactionId.getAgentId().value(), "test"); Assertions.assertEquals(transactionId.getAgentStartTime(), 1L); Assertions.assertEquals(transactionId.getTransactionSequence(), 2L); } @@ -56,7 +57,7 @@ public void testParseTransactionId_RpcHeaderDuplicateAdd_BugReproduce() { String id1 = AGENT_ID + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "2"; String id2 = AGENT_ID + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "1" + TransactionIdUtils.TRANSACTION_ID_DELIMITER + "3"; TransactionId transactionId = TransactionIdUtils.parseTransactionId(id1 + ", " + id2); - Assertions.assertEquals(transactionId.getAgentId(), "test"); + Assertions.assertEquals(transactionId.getAgentId().value(), "test"); Assertions.assertEquals(transactionId.getAgentStartTime(), 1L); Assertions.assertEquals(transactionId.getTransactionSequence(), 2L); }); @@ -120,10 +121,10 @@ public void testParseTransactionIdByte_compatibility2() { } - private static ByteBuffer writeTransactionId_for_compatibility(String agentId, long agentStartTime, long transactionSequence) { + private static ByteBuffer writeTransactionId_for_compatibility(AgentId agentId, long agentStartTime, long transactionSequence) { final Buffer buffer = new AutomaticBuffer(1 + 5 + 24 + 10 + 10); buffer.putByte(TransactionIdUtils.VERSION); - buffer.putPrefixedString(agentId); + buffer.putPrefixedString(AgentId.unwrap(agentId)); buffer.putVLong(agentStartTime); buffer.putVLong(transactionSequence); return buffer.wrapByteBuffer(); @@ -138,7 +139,7 @@ public void validateAgentId() { @Test public void longAgentId() { - String agentId = StringUtils.repeat('a', PinpointConstants.AGENT_ID_MAX_LEN); + AgentId agentId = AgentId.of(StringUtils.repeat('a', PinpointConstants.AGENT_ID_MAX_LEN)); TransactionId transactionId = TransactionIdUtils.parseTransactionId(agentId + "^1^2"); Assertions.assertEquals(agentId, transactionId.getAgentId()); } @@ -146,7 +147,7 @@ public void longAgentId() { @Test public void tooLongAgentId() { Assertions.assertThrows(IllegalArgumentException.class, () -> { - String agentId = StringUtils.repeat('a', PinpointConstants.AGENT_ID_MAX_LEN + 1); + AgentId agentId = AgentId.of(StringUtils.repeat('a', PinpointConstants.AGENT_ID_MAX_LEN + 1)); TransactionId transactionId = TransactionIdUtils.parseTransactionId(agentId + "^1^2"); Assertions.assertEquals(agentId, transactionId.getAgentId()); }); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/alram/event/DeleteRuleEvent.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/alarm/event/DeleteRuleEvent.java similarity index 95% rename from commons-server/src/main/java/com/navercorp/pinpoint/common/server/alram/event/DeleteRuleEvent.java rename to commons-server/src/main/java/com/navercorp/pinpoint/common/server/alarm/event/DeleteRuleEvent.java index 19de7cda11ed..e59c20655b81 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/alram/event/DeleteRuleEvent.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/alarm/event/DeleteRuleEvent.java @@ -15,7 +15,7 @@ * */ -package com.navercorp.pinpoint.common.server.alram.event; +package com.navercorp.pinpoint.common.server.alarm.event; import java.util.Objects; diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/AgentInfoBo.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/AgentInfoBo.java index 751cb96f4de7..ef7de767b3df 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/AgentInfoBo.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/AgentInfoBo.java @@ -18,6 +18,9 @@ import com.navercorp.pinpoint.common.buffer.AutomaticBuffer; import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; import jakarta.validation.constraints.NotBlank; /** @@ -29,9 +32,12 @@ public class AgentInfoBo { private final String hostName; private final String ip; private final String ports; - @NotBlank private final String agentId; + private final AgentId agentId; private final String agentName; @NotBlank private final String applicationName; + private final ApplicationId applicationId; + @NotBlank private final String serviceName; + private final ServiceId serviceId; private final short serviceTypeCode; private final int pid; private final String vmVersion; @@ -55,6 +61,9 @@ private AgentInfoBo(Builder builder) { this.agentId = builder.agentId; this.agentName = builder.agentName; this.applicationName = builder.applicationName; + this.applicationId = builder.applicationId; + this.serviceName = builder.serviceName; + this.serviceId = builder.serviceId; this.serviceTypeCode = builder.serviceTypeCode; this.pid = builder.pid; this.vmVersion = builder.vmVersion; @@ -79,7 +88,7 @@ public String getPorts() { return ports; } - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -91,6 +100,18 @@ public String getApplicationName() { return applicationName; } + public ApplicationId getApplicationId() { + return applicationId; + } + + public String getServiceName() { + return serviceName; + } + + public ServiceId getServiceId() { + return serviceId; + } + public long getStartTime() { return startTime; } @@ -151,6 +172,10 @@ public byte[] writeValue() { buffer.putBoolean(this.isContainer()); buffer.putPrefixedString(this.getAgentName()); + buffer.putUUID(this.getApplicationId().value()); + buffer.putPrefixedString(this.getServiceName()); + buffer.putUUID(this.getServiceId().value()); + return buffer.getBuffer(); } @@ -172,11 +197,8 @@ public boolean equals(Object obj) { return false; AgentInfoBo other = (AgentInfoBo) obj; if (agentId == null) { - if (other.agentId != null) - return false; - } else if (!agentId.equals(other.agentId)) - return false; - return true; + return other.agentId == null; + } else return agentId.equals(other.agentId); } @Override @@ -188,6 +210,9 @@ public String toString() { ", agentId='" + agentId + '\'' + ", agentName='" + agentName + '\'' + ", applicationName='" + applicationName + '\'' + + ", applicationId='" + applicationId + '\'' + + ", serviceName='" + serviceName + '\'' + + ", serviceId='" + serviceId + '\'' + ", serviceTypeCode=" + serviceTypeCode + ", pid=" + pid + ", vmVersion='" + vmVersion + '\'' + @@ -205,9 +230,12 @@ public static class Builder { private String hostName; private String ip; private String ports; - private String agentId; + private AgentId agentId; private String agentName; private String applicationName; + private ApplicationId applicationId; + private String serviceName; + private ServiceId serviceId; private short serviceTypeCode; private int pid; private String vmVersion; @@ -238,7 +266,7 @@ public void setPorts(String ports) { this.ports = ports; } - public void setAgentId(String agentId) { + public void setAgentId(AgentId agentId) { this.agentId = agentId; } @@ -250,6 +278,18 @@ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } + public void setApplicationId(ApplicationId applicationId) { + this.applicationId = applicationId; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public void setServiceId(ServiceId serviceId) { + this.serviceId = serviceId; + } + public void setServiceTypeCode(short serviceTypeCode) { this.serviceTypeCode = serviceTypeCode; } @@ -302,11 +342,19 @@ public AgentInfoBo build() { if (this.ports == null) this.ports = ""; if (this.agentId == null) - this.agentId = ""; + this.agentId = AgentId.of(""); if (this.agentName == null) this.agentName = ""; if (this.applicationName == null) this.applicationName = ""; + if (this.applicationId == null) { + this.applicationId = ApplicationId.NOT_EXIST; + } + if (this.serviceName == null) + this.serviceName = ""; + if (this.serviceId == null) { + this.serviceId = ServiceId.NOT_EXIST; + } if (this.vmVersion == null) this.vmVersion = ""; if (this.agentVersion == null) { diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationInfo.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationInfo.java new file mode 100644 index 000000000000..d4b9cc4878bb --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationInfo.java @@ -0,0 +1,40 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.bo; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +public record ApplicationInfo( + ApplicationId id, + ServiceId serviceId, + String name, + short serviceTypeCode +) { + + public ApplicationInfo(ApplicationId id, ServiceId serviceId, String name, short serviceTypeCode) { + this.id = Objects.requireNonNull(id, "id"); + this.serviceId = Objects.requireNonNull(serviceId, "serviceId"); + this.name = Objects.requireNonNull(name, "name"); + this.serviceTypeCode = serviceTypeCode; + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelector.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelector.java new file mode 100644 index 000000000000..0bdc139fe0da --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelector.java @@ -0,0 +1,72 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.bo; + +import com.navercorp.pinpoint.common.buffer.AutomaticBuffer; +import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.util.BytesUtils; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +public record ApplicationSelector(ServiceId serviceId, String name, short serviceTypeCode) { + + public ApplicationSelector(ServiceId serviceId, String name, short serviceTypeCode) { + this.serviceId = Objects.requireNonNull(serviceId, "serviceId"); + this.name = Objects.requireNonNull(name, "name"); + this.serviceTypeCode = serviceTypeCode; + } + + public byte[] toBytes() { + Buffer buffer = new AutomaticBuffer(); + buffer.putUUID(serviceId.value()); + buffer.putShort(serviceTypeCode); + buffer.putBytes(BytesUtils.toBytes(name)); + return buffer.getBuffer(); + } + + public static ApplicationSelector fromBuffer(Buffer buffer) { + final ServiceId serviceId = new ServiceId(buffer.readUUID()); + final short serviceTypeCode = buffer.readShort(); + final String name = buffer.readPadString(buffer.remaining()); + return new ApplicationSelector(serviceId, name, serviceTypeCode); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ApplicationSelector selector = (ApplicationSelector) o; + return serviceTypeCode == selector.serviceTypeCode && Objects.equals(serviceId, selector.serviceId) && Objects.equals(name, selector.name); + } + + @Override + public int hashCode() { + return Objects.hash(serviceId, name, serviceTypeCode); + } + + @Override + public String toString() { + return "ApplicationSelector{" + + "serviceId=" + serviceId + + ", name='" + name + '\'' + + ", serviceTypeCode=" + serviceTypeCode + + '}'; + } +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/BasicSpan.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/BasicSpan.java index af3905ecf1c8..dd3c6eea97aa 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/BasicSpan.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/BasicSpan.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.common.server.bo; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; /** @@ -25,14 +27,17 @@ public interface BasicSpan { int getVersion(); - String getAgentId(); - void setAgentId(String agentId); + AgentId getAgentId(); + void setAgentId(AgentId agentId); String getAgentName(); void setAgentName(String agentName); - String getApplicationId(); - void setApplicationId(String applicationId); + String getApplicationName(); + void setApplicationName(String applicationName); + + ApplicationId getApplicationId(); + void setApplicationId(ApplicationId applicationId); long getAgentStartTime(); void setAgentStartTime(long agentStartTime); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ServiceInfo.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ServiceInfo.java new file mode 100644 index 000000000000..c16ed9466aef --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/ServiceInfo.java @@ -0,0 +1,35 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.bo; + +import com.navercorp.pinpoint.common.id.ServiceId; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +public record ServiceInfo( + ServiceId id, + String name +) { + + public ServiceInfo(ServiceId id, String name) { + this.id = Objects.requireNonNull(id, "id"); + this.name = Objects.requireNonNull(name, "name"); + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanBo.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanBo.java index 702622fc029c..139efbc25a5f 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanBo.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanBo.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.common.server.bo; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.PositiveOrZero; @@ -32,9 +34,10 @@ public class SpanBo implements Event, BasicSpan { private byte version = 0; // private AgentKeyBo agentKeyBo; - @NotBlank private String agentId; + private AgentId agentId; private String agentName; - @NotBlank private String applicationId; + @NotBlank private String applicationName; + private ApplicationId applicationId; @PositiveOrZero private long agentStartTime; private TransactionId transactionId; @@ -42,7 +45,7 @@ public class SpanBo implements Event, BasicSpan { private long spanId; private long parentSpanId; - private String parentApplicationId; + private String parentApplicationName; private short parentApplicationServiceType; private long startTime; @@ -109,12 +112,12 @@ public void setTransactionId(TransactionId transactionId) { } @Override - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @Override - public void setAgentId(String agentId) { + public void setAgentId(AgentId agentId) { this.agentId = agentId; } @@ -129,12 +132,22 @@ public void setAgentName(String agentName) { } @Override - public String getApplicationId() { + public String getApplicationName() { + return applicationName; + } + + @Override + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + @Override + public ApplicationId getApplicationId() { return applicationId; } @Override - public void setApplicationId(String applicationId) { + public void setApplicationId(ApplicationId applicationId) { this.applicationId = applicationId; } @@ -348,12 +361,12 @@ public short getApplicationServiceType() { } } - public String getParentApplicationId() { - return parentApplicationId; + public String getParentApplicationName() { + return parentApplicationName; } - public void setParentApplicationId(String parentApplicationId) { - this.parentApplicationId = parentApplicationId; + public void setParentApplicationName(String parentApplicationName) { + this.parentApplicationName = parentApplicationName; } public short getParentApplicationServiceType() { @@ -383,12 +396,13 @@ public String toString() { "version=" + version + ", agentId='" + agentId + '\'' + ", agentName='" + agentName + '\'' + + ", applicationName='" + applicationName + '\'' + ", applicationId='" + applicationId + '\'' + ", agentStartTime=" + agentStartTime + ", transactionId=" + transactionId + ", spanId=" + spanId + ", parentSpanId=" + parentSpanId + - ", parentApplicationId='" + parentApplicationId + '\'' + + ", parentApplicationId='" + parentApplicationName + '\'' + ", parentApplicationServiceType=" + parentApplicationServiceType + ", startTime=" + startTime + ", elapsed=" + elapsed + @@ -417,9 +431,10 @@ public static class Builder { private int version = 0; - private String agentId; + private AgentId agentId; private String agentName; - private String applicationId; + private String applicationName; + private ApplicationId applicationId; private long agentStartTime; private TransactionId transactionId; @@ -468,7 +483,7 @@ public Builder setVersion(int version) { return this; } - public Builder setAgentId(String agentId) { + public Builder setAgentId(AgentId agentId) { this.agentId = agentId; return this; } @@ -478,7 +493,12 @@ public Builder setAgentName(String agentName) { return this; } - public Builder setApplicationId(String applicationId) { + public Builder setApplicationName(String applicationName) { + this.applicationName = applicationName; + return this; + } + + public Builder setApplicationId(ApplicationId applicationId) { this.applicationId = applicationId; return this; } @@ -603,12 +623,13 @@ public SpanBo build() { result.setVersion(this.version); result.setAgentId(this.agentId); result.setAgentName(this.agentName); + result.setApplicationName(this.applicationName); result.setApplicationId(this.applicationId); result.setAgentStartTime(this.agentStartTime); result.setTransactionId(this.transactionId); result.setSpanId(this.spanId); result.setParentSpanId(this.parentSpanId); - result.setParentApplicationId(this.parentApplicationId); + result.setParentApplicationName(this.parentApplicationId); result.setParentApplicationServiceType(this.parentApplicationServiceType); result.setStartTime(this.startTime); result.setElapsed(this.elapsed); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanChunkBo.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanChunkBo.java index d8793369f3e3..74d6c2bc7b1b 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanChunkBo.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/SpanChunkBo.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.common.server.bo; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.PositiveOrZero; @@ -30,9 +32,10 @@ public class SpanChunkBo implements BasicSpan { private byte version = 0; - @NotBlank private String agentId; + private AgentId agentId; private String agentName; - @NotBlank private String applicationId; + @NotBlank private String applicationName; + private ApplicationId applicationId; @PositiveOrZero private long agentStartTime; private TransactionId transactionId; @@ -67,11 +70,11 @@ public void setVersion(int version) { } @Override - public String getAgentId() { + public AgentId getAgentId() { return agentId; } - public void setAgentId(String agentId) { + public void setAgentId(AgentId agentId) { this.agentId = agentId; } @@ -85,11 +88,22 @@ public void setAgentName(String agentName) { } @Override - public String getApplicationId() { - return applicationId; + public String getApplicationName() { + return applicationName; } - public void setApplicationId(String applicationId) { + @Override + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + @Override + public ApplicationId getApplicationId() { + return this.applicationId; + } + + @Override + public void setApplicationId(ApplicationId applicationId) { this.applicationId = applicationId; } @@ -200,7 +214,7 @@ public String toString() { "version=" + version + ", agentId='" + agentId + '\'' + ", agentName='" + agentName + '\'' + - ", applicationId='" + applicationId + '\'' + + ", applicationId='" + applicationName + '\'' + ", agentStartTime=" + agentStartTime + ", transactionId=" + transactionId + ", spanId=" + spanId + diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/BindAttribute.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/BindAttribute.java index e321cca4b08e..1f515cb54fc7 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/BindAttribute.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/BindAttribute.java @@ -1,25 +1,30 @@ package com.navercorp.pinpoint.common.server.bo.grpc; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.grpc.Header; import java.util.Objects; public class BindAttribute { - private final String agentId; + private final AgentId agentId; private final String applicationName; + private final ApplicationId applicationId; private final long agentStartTime; private final long acceptedTime; - public static BindAttribute of(Header header, long acceptedTime) { + public static BindAttribute of(Header header, ApplicationId applicationId, long acceptedTime) { return new BindAttribute(header.getAgentId(), header.getApplicationName(), + applicationId, header.getAgentStartTime(), acceptedTime); } - public BindAttribute(String agentId, String applicationName, long agentStartTime, long acceptedTime) { + public BindAttribute(AgentId agentId, String applicationName, ApplicationId applicationId, long agentStartTime, long acceptedTime) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); + this.applicationId = Objects.requireNonNull(applicationId, "applicationId"); this.agentStartTime = agentStartTime; this.acceptedTime = acceptedTime; } @@ -28,7 +33,7 @@ public long getAcceptedTime() { return acceptedTime; } - public String getAgentId() { + public AgentId getAgentId() { return this.agentId; } @@ -36,6 +41,10 @@ public String getApplicationName() { return this.applicationName; } + public ApplicationId getApplicationId() { + return this.applicationId; + } + public long getAgentStartTime() { return this.agentStartTime; } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/GrpcSpanBinder.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/GrpcSpanBinder.java index 9f351e6a8071..40a7d6a48738 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/GrpcSpanBinder.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/grpc/GrpcSpanBinder.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.common.server.bo.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; import com.navercorp.pinpoint.common.server.bo.AnnotationComparator; @@ -80,7 +81,8 @@ SpanBo newSpanBo(PSpan pSpan, BindAttribute attribute) { final SpanBo spanBo = new SpanBo(); spanBo.setVersion(pSpan.getVersion()); spanBo.setAgentId(attribute.getAgentId()); - spanBo.setApplicationId(attribute.getApplicationName()); + spanBo.setApplicationName(attribute.getApplicationName()); + spanBo.setApplicationId(attribute.getApplicationId()); spanBo.setAgentStartTime(attribute.getAgentStartTime()); spanBo.setCollectorAcceptTime(attribute.getAcceptedTime()); @@ -134,7 +136,7 @@ SpanBo newSpanBo(PSpan pSpan, BindAttribute attribute) { final String parentApplicationName = parentInfo.getParentApplicationName(); if (StringUtils.hasLength(parentApplicationName)) { - spanBo.setParentApplicationId(parentApplicationName); + spanBo.setParentApplicationName(parentApplicationName); } spanBo.setParentApplicationServiceType((short) parentInfo.getParentApplicationType()); } @@ -244,7 +246,8 @@ SpanChunkBo newSpanChunkBo(PSpanChunk pSpanChunk, BindAttribute attribute) { final SpanChunkBo spanChunkBo = new SpanChunkBo(); spanChunkBo.setVersion(pSpanChunk.getVersion()); spanChunkBo.setAgentId(attribute.getAgentId()); - spanChunkBo.setApplicationId(attribute.getApplicationName()); + spanChunkBo.setApplicationName(attribute.getApplicationName()); + spanChunkBo.setApplicationId(attribute.getApplicationId()); spanChunkBo.setAgentStartTime(attribute.getAgentStartTime()); spanChunkBo.setCollectorAcceptTime(attribute.getAcceptedTime()); @@ -266,7 +269,7 @@ SpanChunkBo newSpanChunkBo(PSpanChunk pSpanChunk, BindAttribute attribute) { return spanChunkBo; } - private TransactionId newTransactionId(PTransactionId pTransactionId, String spanAgentId) { + private TransactionId newTransactionId(PTransactionId pTransactionId, AgentId spanAgentId) { final String transactionAgentId = pTransactionId.getAgentId(); if (StringUtils.hasLength(transactionAgentId)) { return new TransactionId(transactionAgentId, pTransactionId.getAgentStartTime(), pTransactionId.getSequence()); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/AgentIdRowKeyEncoder.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/AgentIdRowKeyEncoder.java index bbb1933d5854..1d1e443e2a25 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/AgentIdRowKeyEncoder.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/AgentIdRowKeyEncoder.java @@ -8,8 +8,4 @@ public AgentIdRowKeyEncoder() { super(HbaseTableConstants.AGENT_ID_MAX_LEN); } - @Override - public byte[] encodeRowKey(String agentId, long timestamp) { - return super.encodeRowKey(agentId, timestamp); - } } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/ApplicationNameRowKeyEncoder.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/ApplicationNameRowKeyEncoder.java index 82b17c95a45e..4179fb1c9aa4 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/ApplicationNameRowKeyEncoder.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/ApplicationNameRowKeyEncoder.java @@ -8,8 +8,4 @@ public ApplicationNameRowKeyEncoder() { super(HbaseTableConstants.APPLICATION_NAME_MAX_LEN); } - @Override - public byte[] encodeRowKey(String applicationName, long timestamp) { - return super.encodeRowKey(applicationName, timestamp); - } } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/IdRowKeyEncoder.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/IdRowKeyEncoder.java index 22f8646e14b1..f548d752db47 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/IdRowKeyEncoder.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/agent/IdRowKeyEncoder.java @@ -3,6 +3,9 @@ import com.navercorp.pinpoint.common.server.util.RowKeyUtils; import com.navercorp.pinpoint.common.util.BytesUtils; import com.navercorp.pinpoint.common.util.TimeUtils; +import com.navercorp.pinpoint.common.util.UuidUtils; + +import java.util.UUID; public class IdRowKeyEncoder { @@ -12,9 +15,17 @@ public IdRowKeyEncoder(int max) { this.max = max; } - public byte[] encodeRowKey(String id, long timestamp) { - byte[] idKey = BytesUtils.toBytes(id); + public byte[] encodeRowKey(String idKey, long timestamp) { + return this.encodeRowKey(BytesUtils.toBytes(idKey), timestamp); + } + + public byte[] encodeRowKey(UUID idKey, long timestamp) { + return this.encodeRowKey(UuidUtils.toBytes(idKey), timestamp); + } + + private byte[] encodeRowKey(byte[] idKey, long timestamp) { long reverseTimestamp = TimeUtils.reverseTimeMillis(timestamp); return RowKeyUtils.concatFixedByteAndLong(idKey, max, reverseTimestamp); } + } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanDecoderV0.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanDecoderV0.java index 4cf16eaa1a77..4485308bd166 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanDecoderV0.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanDecoderV0.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.common.server.bo.serializer.trace.v2; import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; import com.navercorp.pinpoint.common.server.bo.AnnotationTranscoder; @@ -371,9 +372,9 @@ private AnnotationBo readDeltaAnnotationBo(Buffer buffer, AnnotationBo prev) { private void readQualifier(BasicSpan basicSpan, Buffer buffer) { String applicationId = buffer.readPrefixedString(); - basicSpan.setApplicationId(applicationId); + basicSpan.setApplicationName(applicationId); - String agentId = buffer.readPrefixedString(); + AgentId agentId = AgentId.of(buffer.readPrefixedString()); basicSpan.setAgentId(agentId); long agentStartTime = buffer.readVLong(); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanEncoderV0.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanEncoderV0.java index b07fe5cf207a..61148c83fcb8 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanEncoderV0.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanEncoderV0.java @@ -52,8 +52,8 @@ public ByteBuffer encodeSpanChunkQualifier(SpanEncodingContext enco private ByteBuffer encodeQualifier(byte type, BasicSpan basicSpan, SpanEventBo firstEvent, LocalAsyncIdBo localAsyncId) { final Buffer buffer = new AutomaticBuffer(128); buffer.putByte(type); - buffer.putPrefixedString(basicSpan.getApplicationId()); - buffer.putPrefixedString(basicSpan.getAgentId()); + buffer.putPrefixedString(basicSpan.getApplicationName()); + buffer.putPrefixedString(basicSpan.getAgentId().value()); buffer.putVLong(basicSpan.getAgentStartTime()); buffer.putLong(basicSpan.getSpanId()); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyDecoderV2.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyDecoderV2.java index 042c7e32a979..94bc19f2099e 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyDecoderV2.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyDecoderV2.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.common.server.bo.serializer.trace.v2; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.serializer.RowKeyDecoder; import com.navercorp.pinpoint.common.util.BytesUtils; @@ -53,7 +54,7 @@ public TransactionId decodeRowKey(byte[] rowkey) { private TransactionId readTransactionId(byte[] rowKey, int offset) { - String agentId = BytesUtils.toStringAndRightTrim(rowKey, offset, AGENT_ID_MAX_LEN); + AgentId agentId = AgentId.of(BytesUtils.toStringAndRightTrim(rowKey, offset, AGENT_ID_MAX_LEN)); long agentStartTime = BytesUtils.bytesToLong(rowKey, offset + AGENT_ID_MAX_LEN); long transactionSequence = BytesUtils.bytesToLong(rowKey, offset + BytesUtils.LONG_BYTE_LENGTH + AGENT_ID_MAX_LEN); diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyEncoderV2.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyEncoderV2.java index 5424b0c82919..deeac347406b 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyEncoderV2.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/TraceRowKeyEncoderV2.java @@ -41,7 +41,8 @@ public TraceRowKeyEncoderV2(AbstractRowKeyDistributor rowKeyDistributor) { public byte[] encodeRowKey(TransactionId transactionId) { Objects.requireNonNull(transactionId, "transactionId"); - byte[] rowKey = BytesUtils.stringLongLongToBytes(transactionId.getAgentId(), AGENT_ID_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence()); + byte[] rowKey = BytesUtils.stringLongLongToBytes( + transactionId.getAgentId().value(), AGENT_ID_MAX_LEN, transactionId.getAgentStartTime(), transactionId.getTransactionSequence()); return wrapDistributedRowKey(rowKey); } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactory.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactory.java index 6725d7e020ce..bafa2dc79393 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactory.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactory.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.common.server.bo.thrift; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; @@ -72,8 +73,8 @@ public SpanBo buildSpanBo(TSpan tSpan, long acceptedTime, SpanEventFilter spanEv // for test SpanBo newSpanBo(TSpan tSpan) { final SpanBo spanBo = new SpanBo(); - spanBo.setAgentId(tSpan.getAgentId()); - spanBo.setApplicationId(tSpan.getApplicationName()); + spanBo.setAgentId(AgentId.of(tSpan.getAgentId())); + spanBo.setApplicationName(tSpan.getApplicationName()); spanBo.setAgentStartTime(tSpan.getAgentStartTime()); final TransactionId transactionId = newTransactionId(tSpan.getTransactionId(), spanBo.getAgentId()); @@ -107,7 +108,7 @@ SpanBo newSpanBo(TSpan tSpan) { spanBo.setApplicationServiceType(tSpan.getServiceType()); } - spanBo.setParentApplicationId(tSpan.getParentApplicationName()); + spanBo.setParentApplicationName(tSpan.getParentApplicationName()); spanBo.setParentApplicationServiceType(tSpan.getParentApplicationType()); // FIXME span.errCode contains error of span and spanEvent @@ -201,8 +202,8 @@ private LocalAsyncIdBo getLocalAsyncId(TSpanChunk tSpanChunk) { // for test SpanChunkBo newSpanChunkBo(TSpanChunk tSpanChunk) { final SpanChunkBo spanChunkBo = new SpanChunkBo(); - spanChunkBo.setAgentId(tSpanChunk.getAgentId()); - spanChunkBo.setApplicationId(tSpanChunk.getApplicationName()); + spanChunkBo.setAgentId(AgentId.of(tSpanChunk.getAgentId())); + spanChunkBo.setApplicationName(tSpanChunk.getApplicationName()); spanChunkBo.setAgentStartTime(tSpanChunk.getAgentStartTime()); spanChunkBo.setServiceType(tSpanChunk.getServiceType()); if (tSpanChunk.isSetApplicationServiceType()) { @@ -220,7 +221,7 @@ SpanChunkBo newSpanChunkBo(TSpanChunk tSpanChunk) { return spanChunkBo; } - private TransactionId newTransactionId(byte[] transactionIdBytes, String spanAgentId) { + private TransactionId newTransactionId(byte[] transactionIdBytes, AgentId spanAgentId) { return TransactionIdUtils.parseTransactionId(transactionIdBytes, spanAgentId); } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/cluster/ClusterKey.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/cluster/ClusterKey.java index 90885bfd9ae2..5461b141a66b 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/cluster/ClusterKey.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/cluster/ClusterKey.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.common.server.cluster; +import com.navercorp.pinpoint.common.id.AgentId; import org.springframework.util.Assert; import java.util.Objects; @@ -33,6 +34,10 @@ public ClusterKey(String applicationName, String agentId, long startTimestamp) { this.startTimestamp = startTimestamp; } + public ClusterKey(String applicationName, AgentId agentId, long startTimestamp) { + this(applicationName, Objects.requireNonNull(agentId, "agentId").value(), startTimestamp); + } + public String getApplicationName() { return applicationName; } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CommonCacheManagerConfiguration.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CommonCacheManagerConfiguration.java index bbd7747872b2..f52450ab8da7 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CommonCacheManagerConfiguration.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CommonCacheManagerConfiguration.java @@ -25,6 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import java.util.List; import java.util.concurrent.TimeUnit; @Configuration @@ -33,12 +34,17 @@ public class CommonCacheManagerConfiguration { @Bean @Primary - public CacheManager cacheManager() { + public CacheManager cacheManager(List registrations) { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeine(Caffeine.newBuilder() .expireAfterWrite(600, TimeUnit.SECONDS) .initialCapacity(200) .maximumSize(1000)); + + for (CustomCacheRegistration registration : registrations) { + cacheManager.registerCustomCache(registration.name(), registration.cache()); + } + return cacheManager; } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CustomCacheRegistration.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CustomCacheRegistration.java new file mode 100644 index 000000000000..61a1a1827e82 --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/CustomCacheRegistration.java @@ -0,0 +1,29 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.config; + +import com.github.benmanes.caffeine.cache.Cache; + +/** + * @author youngjin.kim2 + */ +public interface CustomCacheRegistration { + + String name(); + + Cache cache(); + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/DefaultCustomCacheRegistration.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/DefaultCustomCacheRegistration.java new file mode 100644 index 000000000000..b3f9a72ed3b3 --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/config/DefaultCustomCacheRegistration.java @@ -0,0 +1,35 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.config; + +import com.github.benmanes.caffeine.cache.Cache; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +public record DefaultCustomCacheRegistration( + String name, + Cache cache +) implements CustomCacheRegistration { + + public DefaultCustomCacheRegistration(String name, Cache cache) { + this.name = Objects.requireNonNull(name, "name"); + this.cache = Objects.requireNonNull(cache, "cache"); + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/AgentInfoBoMapper.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/AgentInfoBoMapper.java index 4daa15172651..6953926776e0 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/AgentInfoBoMapper.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/AgentInfoBoMapper.java @@ -21,6 +21,9 @@ import com.navercorp.pinpoint.common.buffer.FixedBuffer; import com.navercorp.pinpoint.common.hbase.HbaseTableConstants; import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.common.server.bo.JvmInfoBo; import com.navercorp.pinpoint.common.server.bo.ServerMetaDataBo; @@ -41,7 +44,7 @@ public class AgentInfoBoMapper implements RowMapper { @Override public AgentInfoBo mapRow(Result result, int rowNum) throws Exception { byte[] rowKey = result.getRow(); - String agentId = BytesUtils.toStringAndRightTrim(rowKey, 0, PinpointConstants.AGENT_ID_MAX_LEN); + AgentId agentId = AgentId.of(BytesUtils.toStringAndRightTrim(rowKey, 0, PinpointConstants.AGENT_ID_MAX_LEN)); long reverseStartTime = BytesUtils.bytesToLong(rowKey, HbaseTableConstants.AGENT_ID_MAX_LEN); long startTime = TimeUtils.recoveryTimeMillis(reverseStartTime); @@ -87,6 +90,12 @@ private AgentInfoBo.Builder createBuilderFromValue(byte[] serializedAgentInfo) { if (buffer.hasRemaining()) { builder.setAgentName(buffer.readPrefixedString()); } + // 2024.03.11 added application id + if (buffer.hasRemaining()) { + builder.setApplicationId(ApplicationId.of(buffer.readUUID())); + builder.setServiceName(buffer.readPrefixedString()); + builder.setServiceId(ServiceId.of(buffer.readUUID())); + } return builder; } } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdForwardMapper.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdForwardMapper.java new file mode 100644 index 000000000000..52285cd769ab --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdForwardMapper.java @@ -0,0 +1,64 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.common.server.dao.hbase.mapper; + +import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer; +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.client.Result; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +@Component +public class ApplicationIdForwardMapper implements RowMapper { + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR = HbaseColumnFamily.APPLICATION_ID_FORWARD; + + @Override + public ApplicationInfo mapRow(Result result, int rowNum) throws Exception { + byte[] family = DESCRIPTOR.getName(); + byte[] qualifier = DESCRIPTOR.getName(); + Cell cell = result.getColumnLatestCell(family, qualifier); + if (cell == null) { + return null; + } + + return parseCell(cell); + } + + private static ApplicationInfo parseCell(Cell cell) { + Buffer valueBuffer = new OffsetFixedBuffer(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); + + ApplicationSelector application = ApplicationSelector.fromBuffer(valueBuffer); + + Buffer rowBuffer = new OffsetFixedBuffer(cell.getRowArray(), cell.getRowOffset(), cell.getRowOffset()); + UUID value = rowBuffer.readUUID(); + ApplicationId id = ApplicationId.of(value); + + return new ApplicationInfo(id, application.serviceId(), application.name(), application.serviceTypeCode()); + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdInverseMapper.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdInverseMapper.java new file mode 100644 index 000000000000..9477f2789249 --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ApplicationIdInverseMapper.java @@ -0,0 +1,54 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.common.server.dao.hbase.mapper; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.util.BytesUtils; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.client.Result; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +@Component +public class ApplicationIdInverseMapper implements RowMapper { + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR = HbaseColumnFamily.APPLICATION_ID_INVERSE; + + @Override + public ApplicationId mapRow(Result result, int rowNum) throws Exception { + byte[] family = DESCRIPTOR.getName(); + byte[] qualifier = DESCRIPTOR.getName(); + Cell cell = result.getColumnLatestCell(family, qualifier); + if (cell == null) { + return null; + } + + if (cell.getValueLength() < 16) { + throw new IllegalArgumentException("Invalid bytes length: " + cell.getValueLength()); + } + + UUID value = BytesUtils.bytesToUUID(cell.getValueArray(), cell.getValueOffset()); + return ApplicationId.of(value); + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdForwardMapper.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdForwardMapper.java new file mode 100644 index 000000000000..fb0ac00613c1 --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdForwardMapper.java @@ -0,0 +1,58 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.common.server.dao.hbase.mapper; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import com.navercorp.pinpoint.common.util.BytesUtils; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.client.Result; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +@Component +public class ServiceIdForwardMapper implements RowMapper { + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR = HbaseColumnFamily.APPLICATION_ID_FORWARD; + + @Override + public ServiceInfo mapRow(Result result, int rowNum) throws Exception { + byte[] family = DESCRIPTOR.getName(); + byte[] qualifier = DESCRIPTOR.getName(); + Cell cell = result.getColumnLatestCell(family, qualifier); + if (cell == null) { + return null; + } + + if (cell.getValueLength() < 16) { + throw new IllegalArgumentException("Invalid bytes length: " + cell.getValueLength()); + } + + UUID serviceIdValue = BytesUtils.bytesToUUID(cell.getRowArray(), cell.getRowOffset()); + ServiceId serviceId = ServiceId.of(serviceIdValue); + String serviceName = BytesUtils.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); + + return new ServiceInfo(serviceId, serviceName); + } + +} diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdInverseMapper.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdInverseMapper.java new file mode 100644 index 000000000000..d2b5d5049dde --- /dev/null +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/dao/hbase/mapper/ServiceIdInverseMapper.java @@ -0,0 +1,49 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.common.server.dao.hbase.mapper; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.util.BytesUtils; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.client.Result; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +@Component +public class ServiceIdInverseMapper implements RowMapper { + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR = HbaseColumnFamily.APPLICATION_ID_INVERSE; + + @Override + public ServiceId mapRow(Result result, int rowNum) throws Exception { + byte[] family = DESCRIPTOR.getName(); + byte[] qualifier = DESCRIPTOR.getName(); + Cell cell = result.getColumnLatestCell(family, qualifier); + if (cell == null) { + return null; + } + UUID serviceIdValue = BytesUtils.bytesToUUID(cell.getValueArray(), cell.getValueOffset()); + return ServiceId.of(serviceIdValue); + } + +} diff --git a/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/util/HashUtils.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/HashUtils.java similarity index 85% rename from exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/util/HashUtils.java rename to commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/HashUtils.java index 7ca07a3f4558..3d462e194907 100644 --- a/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/util/HashUtils.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/HashUtils.java @@ -1,19 +1,19 @@ /* - * Copyright 2023 NAVER Corp. + * Copyright 2024 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this 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. + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. * See the License for the specific language governing permissions and * limitations under the License. */ -package com.navercorp.pinpoint.exceptiontrace.common.util; +package com.navercorp.pinpoint.common.server.util; import com.google.common.hash.Funnel; @@ -48,6 +48,8 @@ public static HashCode objectsToHashCode(Iterable objects, Funnel funn return hc.hash(); } - + public static HashCode hashBytes(byte[] bytes) { + return HASH.hashBytes(bytes); + } } diff --git a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java index 5b182632b33c..0ed63729cced 100644 --- a/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java +++ b/commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/SpanUtils.java @@ -18,6 +18,7 @@ import com.navercorp.pinpoint.common.buffer.AutomaticBuffer; import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.SpanBo; @@ -37,13 +38,13 @@ public static byte[] getVarTransactionId(SpanBo span) { Objects.requireNonNull(span, "span"); final TransactionId transactionId = span.getTransactionId(); - String agentId = transactionId.getAgentId(); + AgentId agentId = transactionId.getAgentId(); if (agentId == null) { agentId = span.getAgentId(); } final Buffer buffer = new AutomaticBuffer(32); - buffer.putPrefixedString(agentId); + buffer.putPrefixedString(agentId.value()); buffer.putSVLong(transactionId.getAgentStartTime()); buffer.putVLong(transactionId.getTransactionSequence()); return buffer.getBuffer(); diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelectorTest.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelectorTest.java new file mode 100644 index 000000000000..99ec7f36dda7 --- /dev/null +++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/ApplicationSelectorTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.server.bo; + +import com.navercorp.pinpoint.common.buffer.Buffer; +import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.trace.ServiceType; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author youngjin.kim2 + */ +public class ApplicationSelectorTest { + + @Test + public void ApplicationSelectorSerdeTest() { + UUID serviceIdValue = new UUID(0, 1); + ApplicationSelector selector = new ApplicationSelector(ServiceId.of(serviceIdValue), "sampleApplication", ServiceType.SERVLET.getCode()); + Buffer buffer = new OffsetFixedBuffer(selector.toBytes()); + ApplicationSelector deserializedSelector = ApplicationSelector.fromBuffer(buffer); + + assertThat(deserializedSelector).isEqualTo(selector); + } + +} diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/RandomTSpan.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/RandomTSpan.java index 5c9a23b98a32..941686065ca8 100644 --- a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/RandomTSpan.java +++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/RandomTSpan.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.common.server.bo; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import com.navercorp.pinpoint.thrift.dto.TAnnotation; import com.navercorp.pinpoint.thrift.dto.TAnnotationValue; @@ -44,7 +45,7 @@ public TSpan randomTSpan() { tSpan.setApplicationName("appName"); tSpan.setAgentStartTime(System.currentTimeMillis()); - tSpan.setTransactionId(TransactionIdUtils.formatByteBuffer("agent", System.currentTimeMillis(), RandomUtils.nextLong(0, Long.MAX_VALUE))); + tSpan.setTransactionId(TransactionIdUtils.formatByteBuffer(AgentId.of("agent"), System.currentTimeMillis(), RandomUtils.nextLong(0, Long.MAX_VALUE))); tSpan.setSpanId(random.nextLong()); tSpan.setParentSpanId(RandomUtils.nextInt(0, 100000)); tSpan.setStartTime(System.currentTimeMillis() + RandomUtils.nextInt(0, 1000)); @@ -152,7 +153,7 @@ public TSpanChunk randomTSpanChunk() { tSpanChunk.setApplicationName("appName"); tSpanChunk.setAgentStartTime(System.currentTimeMillis()); - tSpanChunk.setTransactionId(TransactionIdUtils.formatByteBuffer("agent", System.currentTimeMillis(), RandomUtils.nextLong(0, Long.MAX_VALUE))); + tSpanChunk.setTransactionId(TransactionIdUtils.formatByteBuffer(AgentId.of("agent"), System.currentTimeMillis(), RandomUtils.nextLong(0, Long.MAX_VALUE))); tSpanChunk.setSpanId(random.nextLong()); tSpanChunk.setEndPoint(RandomStringUtils.random(20)); diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/SpanFactoryAssert.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/SpanFactoryAssert.java index e510608f2969..27a9d62ea81c 100644 --- a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/SpanFactoryAssert.java +++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/SpanFactoryAssert.java @@ -36,8 +36,8 @@ public class SpanFactoryAssert { public void assertSpan(TSpan tSpan, SpanBo spanBo) { - Assertions.assertEquals(tSpan.getAgentId(), spanBo.getAgentId()); - Assertions.assertEquals(tSpan.getApplicationName(), spanBo.getApplicationId()); + Assertions.assertEquals(tSpan.getAgentId(), spanBo.getAgentId().value()); + Assertions.assertEquals(tSpan.getApplicationName(), spanBo.getApplicationName()); Assertions.assertEquals(tSpan.getAgentStartTime(), spanBo.getAgentStartTime()); TransactionId transactionId = spanBo.getTransactionId(); @@ -60,7 +60,7 @@ public void assertSpan(TSpan tSpan, SpanBo spanBo) { Assertions.assertEquals(tSpan.getFlag(), spanBo.getFlag()); Assertions.assertEquals(tSpan.getErr(), spanBo.getErrCode()); - Assertions.assertEquals(tSpan.getParentApplicationName(), spanBo.getParentApplicationId()); + Assertions.assertEquals(tSpan.getParentApplicationName(), spanBo.getParentApplicationName()); Assertions.assertEquals(tSpan.getParentApplicationType(), spanBo.getParentApplicationServiceType()); Assertions.assertEquals(tSpan.getAcceptorHost(), spanBo.getAcceptorHost()); @@ -131,8 +131,8 @@ public void assertSpanEvent(TSpanEvent tSpanEvent, SpanEventBo spanEventBo) { public void assertSpanChunk(TSpanChunk tSpanChunk, SpanChunkBo spanChunkBo) { - Assertions.assertEquals(tSpanChunk.getAgentId(), spanChunkBo.getAgentId()); - Assertions.assertEquals(tSpanChunk.getApplicationName(), spanChunkBo.getApplicationId()); + Assertions.assertEquals(tSpanChunk.getAgentId(), spanChunkBo.getAgentId().value()); + Assertions.assertEquals(tSpanChunk.getApplicationName(), spanChunkBo.getApplicationName()); Assertions.assertEquals(tSpanChunk.getAgentStartTime(), spanChunkBo.getAgentStartTime()); diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/grpc/CollectorGrpcSpanFactoryTest.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/grpc/CollectorGrpcSpanFactoryTest.java index fb682bd94588..7e68bfaa156f 100644 --- a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/grpc/CollectorGrpcSpanFactoryTest.java +++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/grpc/CollectorGrpcSpanFactoryTest.java @@ -16,6 +16,8 @@ package com.navercorp.pinpoint.common.server.bo.grpc; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.bo.SpanChunkBo; import com.navercorp.pinpoint.common.server.bo.SpanEventBo; import com.navercorp.pinpoint.common.server.bo.filter.SequenceSpanEventFilter; @@ -28,12 +30,14 @@ import org.junit.jupiter.api.Test; import java.util.List; +import java.util.UUID; /** * @author Woonduk Kang(emeroad) */ public class CollectorGrpcSpanFactoryTest { private static final int MAX_SEQUENCE = 10; + private static final ApplicationId APPLICATION_ID = ApplicationId.of(UUID.randomUUID()); private final GrpcSpanBinder binder = new GrpcSpanBinder(); private final SpanEventFilter filter = new SequenceSpanEventFilter(MAX_SEQUENCE); @@ -41,7 +45,7 @@ public class CollectorGrpcSpanFactoryTest { private final BindAttribute attribute = newAttribute(); private BindAttribute newAttribute() { - return new BindAttribute("agentId", "applicationName", 88, System.currentTimeMillis()); + return new BindAttribute(AgentId.of("agentId"), "applicationName", APPLICATION_ID, 88, System.currentTimeMillis()); } private final GrpcSpanFactory factory = new CollectorGrpcSpanFactory(binder, filter); diff --git a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactoryTest.java b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactoryTest.java index 429c3d5feb53..144cdf9d75eb 100644 --- a/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactoryTest.java +++ b/commons-server/src/test/java/com/navercorp/pinpoint/common/server/bo/thrift/SpanFactoryTest.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.common.server.bo.thrift; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.profiler.util.TransactionIdUtils; import com.navercorp.pinpoint.common.server.bo.RandomTSpan; @@ -158,7 +159,7 @@ public void testTransactionId_skip_agentId() { SpanBo spanBo = spanFactory.newSpanBo(tSpan); TransactionId transactionId = spanBo.getTransactionId(); - Assertions.assertEquals(transactionId.getAgentId(), "agentId"); + Assertions.assertEquals(transactionId.getAgentId().value(), "agentId"); Assertions.assertEquals(transactionId.getAgentStartTime(), 1); Assertions.assertEquals(transactionId.getTransactionSequence(), 2); } @@ -167,13 +168,14 @@ public void testTransactionId_skip_agentId() { public void testTransactionId_include_agentId() { TSpan tSpan = new TSpan(); tSpan.setAgentId("agentId"); - byte[] transactionIdBytes = TransactionIdUtils.formatBytes("transactionAgentId", 1, 2); + AgentId transactionAgentId = AgentId.of("transactionAgentId"); + byte[] transactionIdBytes = TransactionIdUtils.formatBytes(transactionAgentId, 1, 2); tSpan.setTransactionId(transactionIdBytes); SpanBo spanBo = spanFactory.newSpanBo(tSpan); TransactionId transactionId = spanBo.getTransactionId(); - Assertions.assertEquals(transactionId.getAgentId(), "transactionAgentId"); + Assertions.assertEquals(transactionId.getAgentId(), transactionAgentId); Assertions.assertEquals(transactionId.getAgentStartTime(), 1); Assertions.assertEquals(transactionId.getTransactionSequence(), 2); } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/PinpointConstants.java b/commons/src/main/java/com/navercorp/pinpoint/common/PinpointConstants.java index cae648d29a58..92d82c79893a 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/PinpointConstants.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/PinpointConstants.java @@ -16,15 +16,23 @@ package com.navercorp.pinpoint.common; +import com.navercorp.pinpoint.common.trace.ServiceType; + /** * @author emeroad */ public final class PinpointConstants { - public static final int APPLICATION_NAME_MAX_LEN = 24; + public static final int APPLICATION_NAME_MAX_LEN = 255; + + public static final int SERVICE_NAME_MAX_LEN = 255; public static final int AGENT_ID_MAX_LEN = 24; public static final int AGENT_NAME_MAX_LEN = 255; + public static final ServiceType DEFAULT_SERVICE_TYPE = ServiceType.STAND_ALONE; + public static final String DEFAULT_SERVICE_TYPE_NAME = "STAND_ALONE"; + public static final short DEFAULT_SERVICE_TYPE_CODE = 1000; + } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/AbstractPinpointIdentifier.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/AbstractPinpointIdentifier.java new file mode 100644 index 000000000000..5a4ae1e8e4e1 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/AbstractPinpointIdentifier.java @@ -0,0 +1,48 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +public class AbstractPinpointIdentifier implements PinpointIdentifier { + + private final T value; + + public AbstractPinpointIdentifier(T value) { + this.value = Objects.requireNonNull(value, "value"); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AbstractPinpointIdentifier that = (AbstractPinpointIdentifier) o; + return Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + public T value() { + return value; + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/AgentId.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/AgentId.java new file mode 100644 index 000000000000..fcbb1af9f917 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/AgentId.java @@ -0,0 +1,60 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.util.AgentUuidUtils; +import com.navercorp.pinpoint.common.util.UuidUtils; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +public class AgentId extends StringPinpointIdentifier { + + private static final int MAX_LENGTH = PinpointConstants.AGENT_ID_MAX_LEN; + + private AgentId(String value) { + super(value); + + if (value().length() > MAX_LENGTH) { + throw new IllegalArgumentException("length of agentId cannot be greater than " + MAX_LENGTH); + } + } + + public static AgentId random() { + UUID uuid = UuidUtils.createV4(); + String str = AgentUuidUtils.encode(uuid); + return new AgentId(str); + } + + public static AgentId of(String value) { + if (value == null) { // TODO: null-check should be done prior + return null; + } + + return new AgentId(value); + } + + public static String unwrap(AgentId agentId) { + if (agentId == null) { // TODO: null-check should be done prior + return null; + } + return agentId.value(); + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/ApplicationId.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/ApplicationId.java new file mode 100644 index 000000000000..dd06e124aa49 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/ApplicationId.java @@ -0,0 +1,47 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +import com.navercorp.pinpoint.common.util.UuidUtils; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +public class ApplicationId extends UUIDPinpointIdentifier { + public static final ApplicationId NOT_EXIST = new ApplicationId(UuidUtils.EMPTY); + + public ApplicationId(UUID value) { + super(value); + } + + public static ApplicationId of(UUID value) { + return new ApplicationId(value); + } + + public byte[] toBytes() { + return UuidUtils.toBytes(this.value()); + } + + public static UUID unwrap(ApplicationId applicationId) { + if (applicationId == null) { + return null; + } + return applicationId.value(); + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/PinpointIdentifier.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/PinpointIdentifier.java new file mode 100644 index 000000000000..afc7166619a0 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/PinpointIdentifier.java @@ -0,0 +1,22 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +/** + * @author youngjin.kim2 + */ +public interface PinpointIdentifier { +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/ServiceId.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/ServiceId.java new file mode 100644 index 000000000000..b2971a446e6b --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/ServiceId.java @@ -0,0 +1,50 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +import com.navercorp.pinpoint.common.util.UuidUtils; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +public class ServiceId extends UUIDPinpointIdentifier { + + public static final ServiceId NOT_EXIST = new ServiceId(UuidUtils.EMPTY); + public static final ServiceId DEFAULT_ID = new ServiceId(new UUID(0L, 1L)); + public static final String DEFAULT_SERVICE_NAME = "DEFAULT_SERVICE"; + + public ServiceId(UUID value) { + super(value); + } + + public static ServiceId of(UUID value) { + return new ServiceId(value); + } + + public byte[] toBytes() { + return UuidUtils.toBytes(this.value()); + } + + public static UUID unwrap(ServiceId serviceId) { + if (serviceId == null) { + return null; + } + return serviceId.value(); + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/StringPinpointIdentifier.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/StringPinpointIdentifier.java new file mode 100644 index 000000000000..5ad36538f527 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/StringPinpointIdentifier.java @@ -0,0 +1,37 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +/** + * @author youngjin.kim2 + */ +public class StringPinpointIdentifier extends AbstractPinpointIdentifier implements Comparable { + + public StringPinpointIdentifier(String value) { + super(value); + } + + @Override + public String toString() { + return value(); + } + + @Override + public int compareTo(StringPinpointIdentifier other) { + return value().compareTo(other.value()); + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/id/UUIDPinpointIdentifier.java b/commons/src/main/java/com/navercorp/pinpoint/common/id/UUIDPinpointIdentifier.java new file mode 100644 index 000000000000..746dd4bfa8d3 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/id/UUIDPinpointIdentifier.java @@ -0,0 +1,39 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.common.id; + +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +public class UUIDPinpointIdentifier extends AbstractPinpointIdentifier implements Comparable { + + public UUIDPinpointIdentifier(UUID value) { + super(value); + } + + @Override + public String toString() { + return value().toString(); + } + + @Override + public int compareTo(UUIDPinpointIdentifier other) { + return value().compareTo(other.value()); + } + +} diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentUuidUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentUuidUtils.java index 8adc4b3221b1..c203b88ace25 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentUuidUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/AgentUuidUtils.java @@ -16,9 +16,6 @@ package com.navercorp.pinpoint.common.util; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; import java.util.UUID; /** @@ -26,8 +23,6 @@ */ public class AgentUuidUtils { - private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); - /** * Base64 encodes the given {@code uuidString} into URL and filename safe string as specified by RFC 4648 section 5. * The returned string is guaranteed to be 22 characters long (with 2 pad characters "=" removed) as a valid UUID @@ -40,10 +35,7 @@ public class AgentUuidUtils { * @throws IllegalArgumentException if {@code uuidString} is not a valid string representation of uuid */ public static String encode(String uuidString) { - Objects.requireNonNull(uuidString, "uuidString"); - - UUID uuid = UUID.fromString(uuidString); - return encode(uuid); + return UuidUtils.encode(uuidString); } /** @@ -58,14 +50,7 @@ public static String encode(String uuidString) { * @throws IllegalArgumentException if {@code uuid} is not a valid uuid */ public static String encode(UUID uuid) { - Objects.requireNonNull(uuid, "uuid"); - - final byte[] bytes = new byte[16]; - BytesUtils.writeLong(uuid.getMostSignificantBits(), bytes, 0); - BytesUtils.writeLong(uuid.getLeastSignificantBits(), bytes, BytesUtils.LONG_BYTE_LENGTH); - - byte[] encode = ENCODER.encode(bytes); - return new String(encode, StandardCharsets.US_ASCII); + return UuidUtils.encode(uuid); } /** @@ -80,17 +65,7 @@ public static String encode(UUID uuid) { * trailing pad characters */ public static UUID decode(String src) { - Objects.requireNonNull(src, "src"); - byte[] bytes = src.getBytes(StandardCharsets.US_ASCII); - if (bytes.length != 22) { - throw new IllegalArgumentException("Invalid src byte array: " + src); - } - - byte[] decoded = Base64.getUrlDecoder().decode(bytes); - - long mostSigBits = BytesUtils.bytesToLong(decoded, 0); - long leastSigBits = BytesUtils.bytesToLong(decoded, BytesUtils.LONG_BYTE_LENGTH); - return new UUID(mostSigBits, leastSigBits); + return UuidUtils.decode(src); } } diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java index 8e5e62d4626a..3b3064f78f9c 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java @@ -20,6 +20,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.UUID; /** * @author emeroad @@ -28,6 +29,7 @@ public final class BytesUtils { public static final int SHORT_BYTE_LENGTH = 2; public static final int INT_BYTE_LENGTH = 4; public static final int LONG_BYTE_LENGTH = 8; + public static final int UUID_BYTE_LENGTH = 16; public static final int LONG_LONG_BYTE_LENGTH = 16; public static final int VLONG_MAX_SIZE = 10; @@ -125,6 +127,17 @@ public static short bytesToShort(final byte[] buf, final int offset) { return v; } + public static UUID bytesToUUID(final byte[] buf, final int offset) { + if (buf == null) { + throw new NullPointerException("buf"); + } + checkBounds(buf, offset, UUID_BYTE_LENGTH); + + long msb = bytesToLong(buf, offset); + long lsb = bytesToLong(buf, offset + 8); + return new UUID(msb, lsb); + } + public static int bytesToSVar32(final byte[] buffer, final int offset) { return zigzagToInt(bytesToVar32(buffer, offset)); diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/IdValidateUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/IdValidateUtils.java index b05de2d9eaeb..da1d6f21d8a8 100644 --- a/commons/src/main/java/com/navercorp/pinpoint/common/util/IdValidateUtils.java +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/IdValidateUtils.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.common.util; import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.AgentId; import java.util.Objects; import java.util.regex.Matcher; @@ -42,6 +43,10 @@ public static boolean validateId(String id) { return validateId(id, DEFAULT_MAX_LENGTH); } + public static boolean validateId(AgentId agentId) { + return validateId(AgentId.unwrap(agentId)); + } + public static boolean validateId(String id, int maxLength) { final CheckResult result = checkId(id, maxLength); return result == CheckResult.SUCCESS; diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/UuidUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/UuidUtils.java new file mode 100644 index 000000000000..8ef9ac9c0a44 --- /dev/null +++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/UuidUtils.java @@ -0,0 +1,133 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.common.util; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; + +/** + * @author youngjin.kim2 + */ +public class UuidUtils { + + public static final UUID EMPTY = new UUID(0, 0); + + private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); + + /** + * Base64 encodes the given {@code uuidString} into URL and filename safe string as specified by RFC 4648 section 5. + * The returned string is guaranteed to be 22 characters long (with 2 pad characters "=" removed) as a valid UUID + * string will always be encoded into the same length. + * + * @param uuidString uuid string to encode + * @return URL and filename safe base64 encoded string with pad characters removed + * + * @throws NullPointerException if {@code uuidString} is null + * @throws IllegalArgumentException if {@code uuidString} is not a valid string representation of uuid + */ + public static String encode(String uuidString) { + Objects.requireNonNull(uuidString, "uuidString"); + + UUID uuid = UUID.fromString(uuidString); + return encode(uuid); + } + + /** + * Base64 encodes the given {@code uuid} into URL and filename safe string as specified by RFC 4648 section 5. + * The returned string is guaranteed to be 22 characters long (with 2 pad characters "=" removed) as a valid UUID + * string will always be encoded into the same length. + * + * @param uuid uuid to encode + * @return URL and filename safe base64 encoded string with pad characters removed + * + * @throws NullPointerException if {@code uuid} is null + * @throws IllegalArgumentException if {@code uuid} is not a valid uuid + */ + public static String encode(UUID uuid) { + Objects.requireNonNull(uuid, "uuid"); + + final byte[] bytes = UuidUtils.toBytes(uuid); + + byte[] encode = ENCODER.encode(bytes); + return new String(encode, StandardCharsets.US_ASCII); + } + + /** + * Decodes the given {@code src} string into a {@link UUID}. {@code src} must be a URL and filename safe base64 + * encoded string 22 characters in length without pad characters "=". + * + * @param src string to be decoded into {@link UUID} + * @return uuid decoded from the given {@code src} + * + * @throws NullPointerException if {@code src} is null + * @throws IllegalArgumentException if {@code src} is not a URL and filename safe base64 encoded string without + * trailing pad characters + */ + public static UUID decode(String src) { + Objects.requireNonNull(src, "src"); + byte[] bytes = src.getBytes(StandardCharsets.US_ASCII); + if (bytes.length != 22) { + throw new IllegalArgumentException("Invalid src byte array: " + src); + } + + byte[] decoded = Base64.getUrlDecoder().decode(bytes); + + return UuidUtils.fromBytes(decoded); + } + + public static UUID fromBytes(byte[] bytes) { + if (bytes == null) { + return null; + } + + if (bytes.length != 16) { + throw new IllegalArgumentException("Invalid bytes length: " + bytes.length); + } + + long mostSigBits = BytesUtils.bytesToLong(bytes, 0); + long leastSigBits = BytesUtils.bytesToLong(bytes, BytesUtils.LONG_BYTE_LENGTH); + return new UUID(mostSigBits, leastSigBits); + } + + public static byte[] toBytes(UUID uuid) { + if (uuid == null) { + return null; + } + + byte[] bytes = new byte[16]; + BytesUtils.writeLong(uuid.getMostSignificantBits(), bytes, 0); + BytesUtils.writeLong(uuid.getLeastSignificantBits(), bytes, BytesUtils.LONG_BYTE_LENGTH); + return bytes; + } + + public static UUID add(UUID a, int b) { + long mostSigBits = a.getMostSignificantBits(); + long leastSigBits = a.getLeastSignificantBits(); + leastSigBits += b; + if (leastSigBits - b < 0 && leastSigBits >= 0) { + mostSigBits++; + } + return new UUID(mostSigBits, leastSigBits); + } + + public static UUID createV4() { + return UUID.randomUUID(); + } + +} diff --git a/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/model/ExceptionMetaData.java b/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/model/ExceptionMetaData.java index f5483df65128..47d40cfa79c8 100644 --- a/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/model/ExceptionMetaData.java +++ b/exceptiontrace/exceptiontrace-common/src/main/java/com/navercorp/pinpoint/exceptiontrace/common/model/ExceptionMetaData.java @@ -16,13 +16,12 @@ package com.navercorp.pinpoint.exceptiontrace.common.model; +import com.navercorp.pinpoint.common.server.util.HashUtils; import com.navercorp.pinpoint.common.server.util.StringPrecondition; import com.navercorp.pinpoint.common.util.StringUtils; -import com.navercorp.pinpoint.exceptiontrace.common.util.HashUtils; import java.util.List; -import java.util.Objects; /** * @author intr3p1d diff --git a/grpc/src/main/java/com/navercorp/pinpoint/grpc/AgentHeaderFactory.java b/grpc/src/main/java/com/navercorp/pinpoint/grpc/AgentHeaderFactory.java index a68afbecd952..776f11e1dfda 100644 --- a/grpc/src/main/java/com/navercorp/pinpoint/grpc/AgentHeaderFactory.java +++ b/grpc/src/main/java/com/navercorp/pinpoint/grpc/AgentHeaderFactory.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.StringUtils; import com.navercorp.pinpoint.grpc.client.HeaderFactory; import io.grpc.Metadata; @@ -28,24 +29,28 @@ */ public class AgentHeaderFactory implements HeaderFactory { - private final String agentId; + private final AgentId agentId; private final String agentName; private final String applicationName; + private final String serviceName; private final long agentStartTime; private final int serviceType; - public AgentHeaderFactory(String agentId, String agentName, String applicationName, int serviceType, long agentStartTime) { + public AgentHeaderFactory(AgentId agentId, String agentName, String applicationName, String serviceName, + int serviceType, long agentStartTime) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.agentName = agentName; this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); + this.serviceName = Objects.requireNonNull(serviceName, "serviceName"); this.serviceType = serviceType; this.agentStartTime = agentStartTime; } public Metadata newHeader() { Metadata headers = new Metadata(); - headers.put(Header.AGENT_ID_KEY, agentId); + headers.put(Header.AGENT_ID_KEY, agentId.value()); headers.put(Header.APPLICATION_NAME_KEY, applicationName); + headers.put(Header.SERVICE_NAME_KEY, serviceName); headers.put(Header.SERVICE_TYPE_KEY, Integer.toString(serviceType)); headers.put(Header.AGENT_START_TIME_KEY, Long.toString(agentStartTime)); if (!StringUtils.isEmpty(agentName)) { diff --git a/grpc/src/main/java/com/navercorp/pinpoint/grpc/Header.java b/grpc/src/main/java/com/navercorp/pinpoint/grpc/Header.java index 62cf07f59876..c34c87710473 100644 --- a/grpc/src/main/java/com/navercorp/pinpoint/grpc/Header.java +++ b/grpc/src/main/java/com/navercorp/pinpoint/grpc/Header.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.grpc; +import com.navercorp.pinpoint.common.id.AgentId; import io.grpc.Metadata; import java.util.Collections; @@ -32,6 +33,7 @@ public class Header { public static final Metadata.Key AGENT_ID_KEY = newStringKey("agentid"); public static final Metadata.Key AGENT_NAME_KEY = newStringKey("agentname"); public static final Metadata.Key APPLICATION_NAME_KEY = newStringKey("applicationname"); + public static final Metadata.Key SERVICE_NAME_KEY = newStringKey("servicename"); public static final Metadata.Key AGENT_START_TIME_KEY = newStringKey("starttime"); // optional header @@ -51,25 +53,26 @@ private static Metadata.Key newStringKey(String s) { public static final List SUPPORT_COMMAND_CODE_LIST_PARSE_ERROR = Collections.emptyList(); private final String name; - private final String agentId; + private final AgentId agentId; private final String agentName; private final String applicationName; + private final String serviceName; private final long agentStartTime; private final long socketId; private final int serviceType; private final List supportCommandCodeList; private final Map properties; - public Header(String name, String agentId, String agentName, String applicationName, + public Header(String name, AgentId agentId, String agentName, String applicationName, String serviceName, int serviceType, long agentStartTime, long socketId, List supportCommandCodeList) { - this(name, agentId, agentName, applicationName, + this(name, agentId, agentName, applicationName, serviceName, serviceType, agentStartTime, socketId, supportCommandCodeList, Collections.emptyMap()); } public Header(String name, - String agentId, String agentName, String applicationName, + AgentId agentId, String agentName, String applicationName, String serviceName, int serviceType, long agentStartTime, long socketId, List supportCommandCodeList, @@ -77,6 +80,7 @@ public Header(String name, this.name = Objects.requireNonNull(name, "name"); this.agentId = Objects.requireNonNull(agentId, "agentId"); this.applicationName = Objects.requireNonNull(applicationName, "applicationName"); + this.serviceName = Objects.requireNonNull(serviceName, "serviceName"); this.serviceType = serviceType; this.agentStartTime = agentStartTime; this.socketId = socketId; @@ -86,7 +90,7 @@ public Header(String name, this.properties = Objects.requireNonNull(properties, "properties"); } - public String getAgentId() { + public AgentId getAgentId() { return agentId; } @@ -98,6 +102,10 @@ public String getApplicationName() { return applicationName; } + public String getServiceName() { + return serviceName; + } + public long getAgentStartTime() { return agentStartTime; } @@ -129,6 +137,7 @@ public String toString() { ", agentId='" + agentId + '\'' + ", agentName='" + agentName + '\'' + ", applicationName='" + applicationName + '\'' + + ", serviceName='" + serviceName + '\'' + ", agentStartTime=" + agentStartTime + ", socketId=" + socketId + ", serviceType=" + serviceType + @@ -151,6 +160,8 @@ public boolean equals(Object o) { if (agentId != null ? !agentId.equals(header.agentId) : header.agentId != null) return false; if (applicationName != null ? !applicationName.equals(header.applicationName) : header.applicationName != null) return false; + if (serviceName != null ? !serviceName.equals(header.serviceName) : header.serviceName != null) + return false; if (supportCommandCodeList != null ? !supportCommandCodeList.equals(header.supportCommandCodeList) : header.supportCommandCodeList != null) return false; return properties != null ? properties.equals(header.properties) : header.properties == null; @@ -161,6 +172,7 @@ public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (agentId != null ? agentId.hashCode() : 0); result = 31 * result + (applicationName != null ? applicationName.hashCode() : 0); + result = 31 * result + (serviceName != null ? serviceName.hashCode() : 0); result = 31 * result + (int) (agentStartTime ^ (agentStartTime >>> 32)); result = 31 * result + (int) (socketId ^ (socketId >>> 32)); result = 31 * result + serviceType; diff --git a/grpc/src/main/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReader.java b/grpc/src/main/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReader.java index b7e40252361b..674ca6e844ec 100644 --- a/grpc/src/main/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReader.java +++ b/grpc/src/main/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReader.java @@ -17,6 +17,8 @@ package com.navercorp.pinpoint.grpc.server; import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ServiceId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.IdValidateUtils; import com.navercorp.pinpoint.common.util.StringUtils; @@ -54,15 +56,16 @@ public AgentHeaderReader(String name, Function> me @Override public Header extract(Metadata headers) { - final String agentId = getId(headers, Header.AGENT_ID_KEY); + final String agentId = getId(headers, Header.AGENT_ID_KEY, PinpointConstants.AGENT_ID_MAX_LEN); final String agentName = getAgentName(headers, Header.AGENT_NAME_KEY); - final String applicationName = getId(headers, Header.APPLICATION_NAME_KEY); + final String applicationName = getId(headers, Header.APPLICATION_NAME_KEY, PinpointConstants.APPLICATION_NAME_MAX_LEN); + final String serviceName = getServiceName(headers, Header.SERVICE_NAME_KEY); final long startTime = getTime(headers, Header.AGENT_START_TIME_KEY); final int serviceType = getServiceType(headers); final long socketId = getSocketId(headers); final List supportCommandCodeList = getSupportCommandCodeList(headers); final Map properties = metadataConverter.apply(headers); - return new Header(name, agentId, agentName, applicationName, serviceType, startTime, socketId, supportCommandCodeList, properties); + return new Header(name, AgentId.of(agentId), agentName, applicationName, serviceName, serviceType, startTime, socketId, supportCommandCodeList, properties); } public static Map emptyProperties(Metadata headers) { @@ -82,12 +85,20 @@ protected long getTime(Metadata headers, Metadata.Key timeKey) { } } - protected String getId(Metadata headers, Metadata.Key idKey) { + protected String getId(Metadata headers, Metadata.Key idKey, int maxLen) { final String id = headers.get(idKey); if (id == null) { throw Status.INVALID_ARGUMENT.withDescription(idKey.name() + " header is missing").asRuntimeException(); } - return validateId(id, idKey); + return validateId(id, idKey, maxLen); + } + + protected String getServiceName(Metadata headers, Metadata.Key idKey) { + final String name = headers.get(idKey); + if (name == null) { + return ServiceId.DEFAULT_SERVICE_NAME; + } + return validateId(name, idKey, PinpointConstants.SERVICE_NAME_MAX_LEN); } protected String getAgentName(Metadata headers, Metadata.Key idKey) { @@ -141,8 +152,8 @@ protected List getSupportCommandCodeList(Metadata headers) { } } - String validateId(String id, Metadata.Key key) { - if (!IdValidateUtils.validateId(id)) { + String validateId(String id, Metadata.Key key, int maxLen) { + if (!IdValidateUtils.validateId(id, maxLen)) { throw Status.INVALID_ARGUMENT.withDescription("invalid " + key.name()).asRuntimeException(); } return id; diff --git a/grpc/src/test/java/com/navercorp/pinpoint/grpc/ChannelFactoryTest.java b/grpc/src/test/java/com/navercorp/pinpoint/grpc/ChannelFactoryTest.java index 8a378289bd12..4e549fa36936 100644 --- a/grpc/src/test/java/com/navercorp/pinpoint/grpc/ChannelFactoryTest.java +++ b/grpc/src/test/java/com/navercorp/pinpoint/grpc/ChannelFactoryTest.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.grpc; import com.google.protobuf.Empty; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.concurrent.PinpointThreadFactory; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.client.ChannelFactory; @@ -104,7 +105,8 @@ public static void tearDown() throws Exception { @Test public void build() throws InterruptedException { - HeaderFactory headerFactory = new AgentHeaderFactory("agentId", "agentName", "appName", ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); + HeaderFactory headerFactory = new AgentHeaderFactory(AgentId.of("agentId"), "agentName", "appName", "serviceName", + ServiceType.UNDEFINED.getCode(), System.currentTimeMillis()); CountRecordClientInterceptor countRecordClientInterceptor = new CountRecordClientInterceptor(); @@ -140,7 +142,9 @@ public void build() throws InterruptedException { Assertions.assertEquals(1, countRecordClientInterceptor.getExecutedInterceptCallCount()); logger.debug("state:{}", managedChannel.getState(true)); - spanService.awaitOnCompleted(); + if (!spanService.awaitOnCompleted()) { + Assertions.fail("awaitOnCompleted"); + } logger.debug("managedChannel shutdown"); managedChannel.shutdown(); managedChannel.awaitTermination(1000, TimeUnit.MILLISECONDS); @@ -171,8 +175,7 @@ private static Server serverStart(ExecutorService executorService) serverFactory.addService(spanService); addFilter(serverFactory); - Server server = serverFactory.build(); - return server; + return serverFactory.build(); } private static void addFilter(ServerFactory serverFactory) { diff --git a/grpc/src/test/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReaderTest.java b/grpc/src/test/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReaderTest.java index 85102522e7ff..fa997827f749 100644 --- a/grpc/src/test/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReaderTest.java +++ b/grpc/src/test/java/com/navercorp/pinpoint/grpc/server/AgentHeaderReaderTest.java @@ -43,7 +43,7 @@ public void extract() { Metadata metadata = newMetadata(); Header header = reader.extract(metadata); - Assertions.assertEquals(header.getAgentId(), AGENT_ID); + Assertions.assertEquals(header.getAgentId().value(), AGENT_ID); Assertions.assertEquals(header.getAgentName(), AGENT_NAME); Assertions.assertEquals(header.getApplicationName(), APPLICATION_NAME); Assertions.assertEquals(header.getAgentStartTime(), AGENT_START_TIME); diff --git a/hbase/scripts/hbase-create.hbase b/hbase/scripts/hbase-create.hbase index d8abbdb0a0d5..9390dff511da 100644 --- a/hbase/scripts/hbase-create.hbase +++ b/hbase/scripts/hbase-create.hbase @@ -22,6 +22,12 @@ create 'ApplicationMapStatisticsSelf_Ver2', { NAME => 'C', TTL => 5184000, VERSI create 'HostApplicationMap_Ver2', { NAME => 'M', TTL => 5184000, VERSIONS => 1, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]} +create 'ApplicationIndex_Ver2', { NAME => 'Agents', TTL => 31536000, DATA_BLOCK_ENCODING => 'PREFIX' } +create 'ApplicationId', { NAME => 'F', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'I', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]} +create 'ApplicationTraceIndex_Ver2', { NAME => 'I', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'M', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]} + +create 'ServiceId', { NAME => 'F', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, { NAME => 'I', TTL => 5184000, DATA_BLOCK_ENCODING => 'PREFIX' }, {SPLITS=>["\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00","\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"]} + list exit diff --git a/hbase/scripts/hbase-drop.hbase b/hbase/scripts/hbase-drop.hbase index a2a3bcb9c928..849ffb2ab2a2 100644 --- a/hbase/scripts/hbase-drop.hbase +++ b/hbase/scripts/hbase-drop.hbase @@ -20,6 +20,12 @@ disable 'ApplicationMapStatisticsSelf_Ver2' disable 'HostApplicationMap_Ver2' +disable 'ApplicationIndex_Ver2' +disable 'ApplicationId' +disable 'ApplicationTraceIndex_Ver2' + +disable 'ServiceId' + drop 'AgentInfo' drop 'AgentStatV2' @@ -43,4 +49,11 @@ drop 'ApplicationMapStatisticsSelf_Ver2' drop 'HostApplicationMap_Ver2' +drop 'ApplicationIndex_Ver2' +drop 'ApplicationId' +drop 'ApplicationTraceIndex_Ver2' + +drop 'ServiceId' + + exit diff --git a/realtime/realtime-collector/src/test/java/com/navercorp/pinpoint/realtime/collector/receiver/grpc/GrpcCommandServiceTest.java b/realtime/realtime-collector/src/test/java/com/navercorp/pinpoint/realtime/collector/receiver/grpc/GrpcCommandServiceTest.java index 9ae391b88a9b..7f8f0fbaeecc 100644 --- a/realtime/realtime-collector/src/test/java/com/navercorp/pinpoint/realtime/collector/receiver/grpc/GrpcCommandServiceTest.java +++ b/realtime/realtime-collector/src/test/java/com/navercorp/pinpoint/realtime/collector/receiver/grpc/GrpcCommandServiceTest.java @@ -17,6 +17,7 @@ import com.google.protobuf.Empty; import com.google.protobuf.StringValue; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.server.DefaultTransportMetadata; @@ -324,9 +325,10 @@ public ServerCall.Listener interceptCall(ServerCall getNodeHistogramFuture(Range range, Node node, LinkList linkList, AtomicBoolean stopSign) { CompletableFuture nodeHistogramFuture; final Application application = node.getApplication(); - final ServiceType serviceType = application.getServiceType(); + final ServiceType serviceType = application.serviceType(); if (serviceType.isWas()) { // for WAS nodes, set their own response time histogram diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/DefaultNodeHistogramFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/DefaultNodeHistogramFactory.java index cbbecaf6cc2f..f345365c7bc8 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/DefaultNodeHistogramFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/DefaultNodeHistogramFactory.java @@ -63,7 +63,7 @@ public NodeHistogram createTerminalNodeHistogram(Application terminalApplication // create applicationHistogram final List toLinkList = linkList.findToLink(terminalApplication); - final Histogram applicationHistogram = new Histogram(terminalApplication.getServiceType()); + final Histogram applicationHistogram = new Histogram(terminalApplication.serviceType()); for (Link link : toLinkList) { applicationHistogram.add(link.getHistogram()); } @@ -80,7 +80,7 @@ public NodeHistogram createTerminalNodeHistogram(Application terminalApplication nodeBuilder.setApplicationTimeHistogram(applicationTimeHistogram); // for Terminal nodes, create AgentLevel histogram - if (terminalApplication.getServiceType().isTerminal() || terminalApplication.getServiceType().isAlias()) { + if (terminalApplication.serviceType().isTerminal() || terminalApplication.serviceType().isAlias()) { LinkCallDataMap mergeSource = new LinkCallDataMap(); final Map agentHistogramMap = new HashMap<>(); for (Link link : toLinkList) { @@ -137,7 +137,7 @@ public NodeHistogram createQueueNodeHistogram(Application queueApplication, Rang final NodeHistogram.Builder nodeBuilder = NodeHistogram.newBuilder(queueApplication, range); // create applicationHistogram - final Histogram applicationHistogram = new Histogram(queueApplication.getServiceType()); + final Histogram applicationHistogram = new Histogram(queueApplication.serviceType()); for (Link link : toLinkList) { applicationHistogram.add(link.getHistogram()); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/SimplifiedNodeHistogramFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/SimplifiedNodeHistogramFactory.java index 9d4713a015e0..1477e718522b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/SimplifiedNodeHistogramFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/histogram/SimplifiedNodeHistogramFactory.java @@ -42,7 +42,7 @@ public NodeHistogram createTerminalNodeHistogram(Application terminalApplication // create applicationHistogram final List toLinkList = linkList.findToLink(terminalApplication); - final ServiceType terminalService = terminalApplication.getServiceType(); + final ServiceType terminalService = terminalApplication.serviceType(); final Histogram applicationHistogram = new Histogram(terminalService); for (Link link : toLinkList) { applicationHistogram.add(link.getHistogram()); @@ -101,7 +101,7 @@ public NodeHistogram createQueueNodeHistogram(Application queueApplication, Rang } // create applicationHistogram - final Histogram applicationHistogram = new Histogram(queueApplication.getServiceType()); + final Histogram applicationHistogram = new Histogram(queueApplication.serviceType()); for (Link link : toLinkList) { applicationHistogram.add(link.getHistogram()); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/DefaultServerInfoAppender.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/DefaultServerInfoAppender.java index 1603957907d5..48f8ac338747 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/DefaultServerInfoAppender.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/DefaultServerInfoAppender.java @@ -98,7 +98,7 @@ private record ServerGroupRequest(Node node, CompletableFuture private CompletableFuture getServerGroupListFuture(Range range, Node node, LinkDataDuplexMap linkDataDuplexMap) { final Application application = node.getApplication(); - final ServiceType nodeServiceType = application.getServiceType(); + final ServiceType nodeServiceType = application.serviceType(); if (nodeServiceType.isWas()) { return CompletableFuture.supplyAsync(new Supplier<>() { @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/StatisticsServerGroupListFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/StatisticsServerGroupListFactory.java index d41e98694a9d..29f87a7bc290 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/StatisticsServerGroupListFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/StatisticsServerGroupListFactory.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.applicationmap.appender.server; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.web.applicationmap.appender.server.datasource.ServerGroupListDataSource; import com.navercorp.pinpoint.web.applicationmap.histogram.NodeHistogram; import com.navercorp.pinpoint.web.applicationmap.nodes.Node; @@ -64,7 +65,7 @@ ServerGroupList createWasNodeInstanceListFromHistogram(Node wasNode, Instant tim if (nodeHistogram != null && nodeHistogram.getAgentHistogramMap() != null) { for (String agentId : nodeHistogram.getAgentHistogramMap().keySet()) { AgentInfo agentInfo = new AgentInfo(); - agentInfo.setAgentId(agentId); + agentInfo.setAgentId(AgentId.of(agentId)); agentInfo.setHostName(agentId); agentInfo.setIp(""); agentInfo.setAgentName(""); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/datasource/AgentInfoServerGroupListDataSource.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/datasource/AgentInfoServerGroupListDataSource.java index 6b8a9a7de3d1..54bccebaa719 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/datasource/AgentInfoServerGroupListDataSource.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/appender/server/datasource/AgentInfoServerGroupListDataSource.java @@ -67,7 +67,7 @@ public ServerGroupList createServerGroupList(Node node, Instant timestamp) { } Application application = node.getApplication(); - Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(application.getName(), timestamp.toEpochMilli()); + Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(application.name(), application.getServiceTypeCode(), timestamp.toEpochMilli()); if (CollectionUtils.isEmpty(agentInfos)) { logger.warn("agentInfo not found. application:{}", application); return ServerGroupList.empty(); @@ -94,7 +94,7 @@ private Set filterAgentInfos(Set agentInfos, Instant times Set filteredAgentInfos = new HashSet<>(); List agentsToCheckStatus = new ArrayList<>(); for (AgentInfo agentInfo : agentInfos) { - String agentId = agentInfo.getAgentId(); + String agentId = agentInfo.getAgentId().value(); if (agentHistogramMap.containsKey(agentId)) { filteredAgentInfos.add(agentInfo); } else { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/hbase/MapScanFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/hbase/MapScanFactory.java index bc58e67b5b4d..21e6fe211e14 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/hbase/MapScanFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/hbase/MapScanFactory.java @@ -35,8 +35,8 @@ public Scan createScan(String id, Application application, Range range, byte[] f } // start key is replaced by end key because timestamp has been reversed - byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getTo()); - byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.getName(), application.getServiceTypeCode(), range.getFrom()); + byte[] startKey = ApplicationMapStatisticsUtils.makeRowKey(application.name(), application.getServiceTypeCode(), range.getTo()); + byte[] endKey = ApplicationMapStatisticsUtils.makeRowKey(application.name(), application.getServiceTypeCode(), range.getFrom()); final Scan scan = new Scan(); scan.setCaching(this.scanCacheSize); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/DefaultLinkFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/DefaultLinkFilter.java index 40f11c6962ef..7b8e99eeed47 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/DefaultLinkFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/DefaultLinkFilter.java @@ -40,7 +40,7 @@ public DefaultLinkFilter(Application outApplication, Application inApplication) public boolean filter(Application foundApplication) { Objects.requireNonNull(foundApplication, "foundApplication"); - if (this.inApplication.getServiceType().isWas() && this.outApplication.getServiceType().isWas()) { + if (this.inApplication.serviceType().isWas() && this.outApplication.serviceType().isWas()) { logger.debug("check was to was."); // if not from same source, drop if (!this.outApplication.equals(foundApplication)) { @@ -49,10 +49,10 @@ public boolean filter(Application foundApplication) { } return true; } - } else if (this.outApplication.getServiceType().isUser()) { + } else if (this.outApplication.serviceType().isUser()) { logger.debug("check client to was"); // if dest not equals to that WAS, drop - if (!this.inApplication.getName().equals(foundApplication.getName())) { + if (!this.inApplication.name().equals(foundApplication.name())) { if (logger.isDebugEnabled()) { logger.debug(" DROP THE ROW,2, DIFFERENT DEST. fetched={}, params={}", foundApplication, this.inApplication); } @@ -60,10 +60,10 @@ public boolean filter(Application foundApplication) { } } else { logger.debug("check any to any."); - if (this.inApplication.getServiceType().isUnknown()) { + if (this.inApplication.serviceType().isUnknown()) { // compare just only application name when dest is unknown. // TODO need more nice way to compare - if (!this.inApplication.getName().equals(foundApplication.getName())) { + if (!this.inApplication.name().equals(foundApplication.name())) { if (logger.isDebugEnabled()) { logger.debug(" DROP THE ROW,3, DIFFERENT DEST. fetched={}, params={}", foundApplication, inApplication); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCalleeMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCalleeMapper.java index 789bbf2e0267..417aaedb9f79 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCalleeMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCalleeMapper.java @@ -91,7 +91,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception { for (Cell cell : result.rawCells()) { final byte[] qualifier = CellUtil.cloneQualifier(cell); - final Application in = readInApplication(qualifier, calleeApplication.getServiceType()); + final Application in = readInApplication(qualifier, calleeApplication.serviceType()); if (filter.filter(in)) { continue; } @@ -103,7 +103,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception { // There may be no callerHost for virtual queue nodes from user-defined entry points. // Terminal nodes, such as httpclient will not have callerHost set as well, but since they're terminal // nodes, they would not have reached here in the first place. - if (calleeApplication.getServiceType().isQueue()) { + if (calleeApplication.serviceType().isQueue()) { callerHost = StringUtils.defaultString(callerHost); } boolean isError = histogramSlot == (short) -1; @@ -113,7 +113,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception { } final short slotTime = (isError) ? (short) -1 : histogramSlot; - linkDataMap.addLinkData(in, in.getName(), calleeApplication, callerHost, timestamp, slotTime, requestCount); + linkDataMap.addLinkData(in, in.name(), calleeApplication, callerHost, timestamp, slotTime, requestCount); if (logger.isDebugEnabled()) { logger.debug(" Fetched {}. statistics:{}", LinkDirection.IN_LINK, linkDataMap); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCallerMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCallerMapper.java index 942307e607ef..3d1a445572b5 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCallerMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/dao/mapper/MapStatisticsCallerMapper.java @@ -101,7 +101,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception { final short slotTime = (isError) ? (short) -1 : histogramSlot; if (StringUtils.isEmpty(calleeHost)) { - calleeHost = callee.getName(); + calleeHost = callee.name(); } linkDataMap.addLinkData(out, callerAgentId, callee, calleeHost, timestamp, slotTime, requestCount); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogram.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogram.java index daa921559964..246ae9d3b352 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogram.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogram.java @@ -85,7 +85,7 @@ public Map> getTimeHistogramMap() { Map> result = new HashMap<>(); for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) { List histogram = histogramOrdering.sortedCopy(agentHistogram.getTimeHistogram()); - result.put(agentHistogram.getAgentId().getName(), histogram); + result.put(agentHistogram.getAgentId().name(), histogram); } return result; } @@ -120,7 +120,7 @@ public List getSampledAgentApdexScoreList(String agentName) { private AgentHistogram selectAgentHistogram(String agentName) { for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) { Application agentId = agentHistogram.getAgentId(); - if (agentId.getName().equals(agentName)) { + if (agentId.name().equals(agentName)) { return agentHistogram; } } @@ -134,7 +134,7 @@ public List getApplicationApdexScoreList(TimeWindow List max = fillList(size, DEFAULT_MAX_APDEX_SCORE); List maxAgentId = fillList(size, DEFAULT_AGENT_ID); - List sumHistogram = getDefaultHistograms(window, application.getServiceType()); + List sumHistogram = getDefaultHistograms(window, application.serviceType()); for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) { for (TimeHistogram timeHistogram : agentHistogram.getTimeHistogram()) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramBuilder.java index fff5d000d142..86139054b6ac 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramBuilder.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramBuilder.java @@ -84,7 +84,7 @@ private AgentHistogramList interpolation(AgentHistogramList agentHistogramList, for (AgentHistogram agentHistogram : agentHistogramList.getAgentHistogramList()) { List timeHistogramList = new ArrayList<>(); for (Long time : window) { - timeHistogramList.add(new TimeHistogram(application.getServiceType(), time)); + timeHistogramList.add(new TimeHistogram(application.serviceType(), time)); } resultAgentHistogramList.addTimeHistogram(agentHistogram.getAgentId(), timeHistogramList); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramSummary.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramSummary.java new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramBuilder.java index 9244567cbb1c..83e3ced0d106 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramBuilder.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramBuilder.java @@ -58,7 +58,7 @@ public ApplicationTimeHistogram build(List responseHistogramList) final Long timeStamp = responseTime.getTimeStamp(); TimeHistogram timeHistogram = applicationLevelHistogram.get(timeStamp); if (timeHistogram == null) { - timeHistogram = new TimeHistogram(application.getServiceType(), timeStamp); + timeHistogram = new TimeHistogram(application.serviceType(), timeStamp); applicationLevelHistogram.put(timeStamp, timeHistogram); } // add each agent-level data @@ -106,14 +106,14 @@ private List interpolation(Collection histogramLis // Map resultMap = new HashMap<>(); for (Long time : window) { - resultMap.put(time, new TimeHistogram(application.getServiceType(), time)); + resultMap.put(time, new TimeHistogram(application.serviceType(), time)); } for (TimeHistogram timeHistogram : histogramList) { long time = window.refineTimestamp(timeHistogram.getTimeStamp()); - TimeHistogram windowHistogram = resultMap.computeIfAbsent(time, t -> new TimeHistogram(application.getServiceType(), t)); + TimeHistogram windowHistogram = resultMap.computeIfAbsent(time, t -> new TimeHistogram(application.serviceType(), t)); windowHistogram.add(timeHistogram); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/NodeHistogram.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/NodeHistogram.java index 0f02b6121825..c599e3bd9044 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/NodeHistogram.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/histogram/NodeHistogram.java @@ -60,7 +60,7 @@ public class NodeHistogram { this.application = Objects.requireNonNull(application, "application"); this.range = Objects.requireNonNull(range, "range"); - this.applicationHistogram = new Histogram(this.application.getServiceType()); + this.applicationHistogram = new Histogram(this.application.serviceType()); this.agentHistogramMap = Collections.emptyMap(); this.applicationTimeHistogram = new ApplicationTimeHistogram(this.application); @@ -74,7 +74,7 @@ public class NodeHistogram { this.range = builder.range; if (builder.applicationHistogram == null) { - this.applicationHistogram = new Histogram(this.application.getServiceType()); + this.applicationHistogram = new Histogram(this.application.serviceType()); } else { this.applicationHistogram = builder.applicationHistogram; } @@ -215,7 +215,7 @@ private AgentTimeHistogram createAgentLevelTimeSeriesResponseTime(List responseHistogram) { - final Histogram applicationHistogram = new Histogram(this.application.getServiceType()); + final Histogram applicationHistogram = new Histogram(this.application.serviceType()); for (ResponseTime responseTime : responseHistogram) { final Collection histogramList = responseTime.getAgentResponseHistogramList(); applicationHistogram.addAll(histogramList); @@ -236,7 +236,7 @@ private Map createAgentLevelResponseTime(List r private void addAgentLevelHistogram(Map agentHistogramMap, String agentId, TimeHistogram histogram) { Histogram agentHistogram = agentHistogramMap.get(agentId); if (agentHistogram == null) { - agentHistogram = new Histogram(application.getServiceType()); + agentHistogram = new Histogram(application.serviceType()); agentHistogramMap.put(agentId, agentHistogram); } agentHistogram.add(histogram); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/Link.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/Link.java index ab65b9dee950..bcc509ffbece 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/Link.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/Link.java @@ -245,7 +245,7 @@ public Boolean getLinkAlert() { } public boolean isWasToWasLink() { - return this.fromNode.getApplication().getServiceType().isWas() && this.toNode.getApplication().getServiceType().isWas(); + return this.fromNode.getApplication().serviceType().isWas() && this.toNode.getApplication().serviceType().isWas(); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/LinkName.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/LinkName.java index 332d172cb704..cefc7c7f8b06 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/LinkName.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/link/LinkName.java @@ -30,7 +30,7 @@ public String getName() { } private String toNodeName(Application node) { - return NodeName.toNodeName(node.getName(), node.getServiceType()); + return NodeName.toNodeName(node.name(), node.serviceType()); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/DefaultApplicationMapCreator.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/DefaultApplicationMapCreator.java index a478635c35ae..6835eb4df13e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/DefaultApplicationMapCreator.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/DefaultApplicationMapCreator.java @@ -66,7 +66,7 @@ public LinkDataDuplexMap createMap(Application application, LinkSelectContext li searchResult.addSourceLinkData(outLinkData); final Application toApplication = outLinkData.getToApplication(); // skip if nextApplication is a terminal or an unknown cloud - final ServiceType toServiceType = toApplication.getServiceType(); + final ServiceType toServiceType = toApplication.serviceType(); if (toServiceType.isTerminal() || toServiceType.isUnknown()) { continue; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/FilteredMapBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/FilteredMapBuilder.java index f9117a80dcef..bdac3ba8a370 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/FilteredMapBuilder.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/FilteredMapBuilder.java @@ -108,18 +108,18 @@ public FilteredMapBuilder addTransaction(List transaction) { for (SpanBo span : transaction) { final Application parentApplication = createParentApplication(span, transactionSpanMap, version); - final Application spanApplication = this.applicationFactory.createApplication(span.getApplicationId(), span.getApplicationServiceType()); + final Application spanApplication = this.applicationFactory.createApplication(span.getApplicationName(), span.getApplicationServiceType()); // records the Span's response time statistics responseHistogramsBuilder.addHistogram(spanApplication, span, span.getCollectorAcceptTime()); - if (!spanApplication.getServiceType().isRecordStatistics() || spanApplication.getServiceType().isRpcClient()) { + if (!spanApplication.serviceType().isRecordStatistics() || spanApplication.serviceType().isRpcClient()) { // span's serviceType is probably not set correctly logger.warn("invalid span application:{}", spanApplication); continue; } - if (parentApplication.getServiceType().isUser()) { + if (parentApplication.serviceType().isUser()) { // Outbound data if (logger.isTraceEnabled()) { logger.trace("span user:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId()); @@ -154,15 +154,15 @@ public FilteredMapBuilder addTransaction(List transaction) { } private void addLinkData(LinkDataMap linkDataMap, SpanBo span, Application parentApplication, Application spanApplication) { - final short slotTime = getHistogramSlotTime(span, spanApplication.getServiceType()); + final short slotTime = getHistogramSlotTime(span, spanApplication.serviceType()); // might need to reconsider using collector's accept time for link statistics. // we need to convert to time window's timestamp. If not, it may lead to OOM due to mismatch in timeslots. long timestamp = timeWindow.refineTimestamp(span.getCollectorAcceptTime()); - final String spanAgentId = span.getAgentId(); + final String spanAgentId = span.getAgentId().value(); linkDataMap.addLinkData(parentApplication, spanAgentId, spanApplication, spanAgentId, timestamp, slotTime, 1); - final HistogramSchema histogramSchema = spanApplication.getServiceType().getHistogramSchema(); + final HistogramSchema histogramSchema = spanApplication.serviceType().getHistogramSchema(); final short sumElapsedSlotTime = histogramSchema.getSumStatSlot().getSlotTime(); final short maxElapsedSlotTime = histogramSchema.getMaxStatSlot().getSlotTime(); final int elapsed = span.getElapsed(); @@ -201,9 +201,9 @@ private Application createParentApplication(SpanBo span, MultiValueMap= 4) { ServiceType applicationServiceType = this.registry.findServiceType(span.getApplicationServiceType()); - applicationName = span.getApplicationId() + "_" + applicationServiceType; + applicationName = span.getApplicationName() + "_" + applicationServiceType; } else { - applicationName = span.getApplicationId(); + applicationName = span.getApplicationName(); } ServiceType serviceType = this.registry.findServiceType(ServiceType.USER.getCode()); return this.applicationFactory.createApplication(applicationName, serviceType); @@ -225,7 +225,7 @@ private Application createParentApplication(SpanBo span, MultiValueMap transactionSpanMap destServiceType = ServiceType.UNKNOWN; } else { //replace with alias instead of Unkown when exists - logger.debug("replace with alias {}", replacedApplication.getServiceType()); - destServiceType = replacedApplication.getServiceType(); - dest = replacedApplication.getName(); + logger.debug("replace with alias {}", replacedApplication.serviceType()); + destServiceType = replacedApplication.serviceType(); + dest = replacedApplication.name(); } } } @@ -322,8 +322,8 @@ private void addNode(SpanBo span, MultiValueMap transactionSpanMap logger.trace("spanEvent src:{} {} -> dest:{} {}", srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint()); } // endPoint may be null - final String destinationAgentId = StringUtils.defaultString(spanEvent.getEndPoint(), destApplication.getName()); - sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId(), destApplication, destinationAgentId, spanEventTimeStamp, slotTime, 1); + final String destinationAgentId = StringUtils.defaultString(spanEvent.getEndPoint(), destApplication.name()); + sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId().value(), destApplication, destinationAgentId, spanEventTimeStamp, slotTime, 1); } public FilteredMap build() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkHandler.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkHandler.java index 6e6c6f068026..e6cd69262866 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkHandler.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkHandler.java @@ -94,7 +94,7 @@ private Collection getEmulatedNodeCalleeLinkData(LinkVisitChecker link for (LinkData calleeLinkData : calleeLinkDataMap.getLinkDataList()) { Application fromApplication = calleeLinkData.getFromApplication(); // filter callee link data from non-WAS nodes - if (!fromApplication.getServiceType().isWas()) { + if (!fromApplication.serviceType().isWas()) { logger.trace("filtered {} as {} is not a WAS node", calleeLinkData, fromApplication); continue; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkMarker.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkMarker.java index f9a3c00051d0..632dc32bc185 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkMarker.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/VirtualLinkMarker.java @@ -42,7 +42,7 @@ public Set getVirtualLinkData() { } public List createVirtualLink(LinkData linkData, Application toApplication, Set acceptApplicationList) { - logger.info("one to N replaced. node:{}->host:{} accept:{}", linkData.getFromApplication(), toApplication.getName(), acceptApplicationList); + logger.info("one to N replaced. node:{}->host:{} accept:{}", linkData.getFromApplication(), toApplication.name(), acceptApplicationList); List virtualLinkDataList = new ArrayList<>(); logger.debug("acceptApplicationList:{}", acceptApplicationList); for (AcceptApplication acceptApplication : acceptApplicationList) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/RpcCallProcessor.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/RpcCallProcessor.java index cbd359ab19a3..a857e839a162 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/RpcCallProcessor.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/RpcCallProcessor.java @@ -73,11 +73,11 @@ public LinkDataMap processLinkDataMap(LinkDirection direction, LinkDataMap linkD private List replaceLinkData(LinkDirection direction, LinkData linkData, Range range) { final Application toApplication = linkData.getToApplication(); - if (toApplication.getServiceType().isRpcClient() || toApplication.getServiceType().isQueue()) { + if (toApplication.serviceType().isRpcClient() || toApplication.serviceType().isQueue()) { // rpc client's destination could have an agent installed in which case the link data must be replaced to point // to the destination application. logger.debug("Finding {} accept applications for {}, {}", direction, toApplication, range); - final Set acceptApplicationList = findAcceptApplications(linkData.getFromApplication(), toApplication.getName(), range); + final Set acceptApplicationList = findAcceptApplications(linkData.getFromApplication(), toApplication.name(), range); logger.debug("Found {} accept applications: {}", direction, acceptApplicationList); if (CollectionUtils.hasLength(acceptApplicationList)) { if (acceptApplicationList.size() == 1) { @@ -93,10 +93,10 @@ private List replaceLinkData(LinkDirection direction, LinkData linkDat } } else { // for queues, accept application may not exist if no consumers have an agent installed - if (toApplication.getServiceType().isQueue()) { + if (toApplication.serviceType().isQueue()) { return Collections.singletonList(linkData); } else { - final Application unknown = new Application(toApplication.getName(), ServiceType.UNKNOWN); + final Application unknown = new Application(toApplication.name(), ServiceType.UNKNOWN); final LinkData unknownLinkData = new LinkData(linkData.getFromApplication(), unknown); unknownLinkData.setLinkCallDataMap(linkData.getLinkCallDataMap()); return Collections.singletonList(unknownLinkData); @@ -115,7 +115,7 @@ private Set filterAlias(Set acceptApplicat final Set resultSet = new HashSet<>(); for (AcceptApplication acceptApplication : acceptApplicationList) { - if (!acceptApplication.getApplication().getServiceType().isAlias()) { + if (!acceptApplication.getApplication().serviceType().isAlias()) { resultSet.add(acceptApplication); } else { logger.debug("deduct alias application {}", acceptApplication); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/WasOnlyProcessor.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/WasOnlyProcessor.java index dc993078ea76..10d9178fbe3a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/WasOnlyProcessor.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/map/processor/WasOnlyProcessor.java @@ -47,8 +47,8 @@ public LinkDataMap processLinkDataMap(LinkDirection linkDirection, LinkDataMap l private boolean accept(LinkData linkData) { final Application toApplication = linkData.getToApplication(); - boolean isDestinationTerminal = toApplication.getServiceType().isTerminal(); - boolean isDestinationUnknown = toApplication.getServiceType().isUnknown(); + boolean isDestinationTerminal = toApplication.serviceType().isTerminal(); + boolean isDestinationUnknown = toApplication.serviceType().isUnknown(); if (isDestinationTerminal || isDestinationUnknown) { logger.debug("Filtering linkData : {}", linkData); return false; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/Node.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/Node.java index f97514084f2e..a0af67e47377 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/Node.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/Node.java @@ -51,10 +51,10 @@ public Node(Application application) { } public String getApplicationTextName() { - if (application.getServiceType().isUser()) { + if (application.serviceType().isUser()) { return "USER"; } else { - return application.getName(); + return application.name(); } } @@ -78,7 +78,7 @@ public NodeName getNodeName() { } public ServiceType getServiceType() { - return application.getServiceType(); + return application.serviceType(); } public NodeHistogram getNodeHistogram() { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeListFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeListFactory.java index 763131d251d3..151f534447ec 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeListFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeListFactory.java @@ -72,17 +72,17 @@ private static void createNode(NodeList nodeList, LinkDataMap linkDataMap) { } private static boolean isFromNode(final Application fromApplication, final Application toApplication) { - if (fromApplication.getServiceType().isRpcClient()) { + if (fromApplication.serviceType().isRpcClient()) { return false; } return true; } private static boolean isToNode(final Application fromApplication, final Application toApplication) { - if (!toApplication.getServiceType().isRpcClient()) { + if (!toApplication.serviceType().isRpcClient()) { return true; } - if (toApplication.getServiceType().isAlias()) { + if (toApplication.serviceType().isAlias()) { return true; } return false; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeName.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeName.java index 275eacbd6dc2..82199dad851c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeName.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/NodeName.java @@ -17,7 +17,7 @@ public class NodeName { public static NodeName of(Application application) { Objects.requireNonNull(application, "application"); - return new NodeName(application.getName(), application.getServiceType()); + return new NodeName(application.name(), application.serviceType()); } public NodeName(String name, ServiceType serviceType) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/ServerInstance.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/ServerInstance.java index 99385da1dd98..61e942fb07f3 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/ServerInstance.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/nodes/ServerInstance.java @@ -51,7 +51,7 @@ public ServerInstance(AgentInfo agentInfo, AgentStatus agentStatus) { Objects.requireNonNull(agentInfo, "agentInfo"); this.hostName = agentInfo.getHostName(); this.ip = agentInfo.getIp(); - this.name = agentInfo.getAgentId(); + this.name = agentInfo.getAgentId().value(); this.agentName = agentInfo.getAgentName(); this.serviceType = agentInfo.getServiceType(); this.status = getAgentLifeCycleState(agentStatus); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java index 0614fdfc3247..936d9a968253 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogram.java @@ -58,7 +58,7 @@ public AgentHistogram(AgentHistogram copyAgentHistogram) { @JsonProperty("name") public String getId() { - return agentId.getName(); + return agentId.name(); } @JsonIgnore @@ -68,12 +68,12 @@ public Application getAgentId() { @JsonIgnore public ServiceType getServiceType() { - return agentId.getServiceType(); + return agentId.serviceType(); } @JsonProperty("histogram") public Histogram getHistogram() { - Histogram histogram = new Histogram(agentId.getServiceType()); + Histogram histogram = new Histogram(agentId.serviceType()); histogram.addAll(timeHistogramMap.values()); return histogram; } @@ -86,7 +86,7 @@ public Collection getTimeHistogram() { public void addTimeHistogram(TimeHistogram timeHistogram) { TimeHistogram find = this.timeHistogramMap.get(timeHistogram.getTimeStamp()); if (find == null) { - find = new TimeHistogram(agentId.getServiceType(), timeHistogram.getTimeStamp()); + find = new TimeHistogram(agentId.serviceType(), timeHistogram.getTimeStamp()); this.timeHistogramMap.put(timeHistogram.getTimeStamp(), find); } find.add(timeHistogram); @@ -105,8 +105,8 @@ public void addTimeHistogram(Collection histogramList) { @Override public String toString() { final StringBuilder sb = new StringBuilder("AgentHistogram{"); - sb.append("agent='").append(agentId.getName()).append('\''); - sb.append(", serviceType=").append(agentId.getServiceType()); + sb.append("agent='").append(agentId.name()).append('\''); + sb.append(", serviceType=").append(agentId.serviceType()); // FIXME temporarily hard-coded due to a change in the data structure sb.append(", ").append(timeHistogramMap); sb.append('}'); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogramList.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogramList.java index 5bfdef37fbc7..4bafb4a24aeb 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogramList.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/AgentHistogramList.java @@ -49,7 +49,7 @@ public AgentHistogramList(Application application, List responseHi for (ResponseTime responseTime : responseHistogramList) { for (Map.Entry agentEntry : responseTime.getAgentHistogram()) { TimeHistogram timeHistogram = agentEntry.getValue(); - this.addAgentHistogram(agentEntry.getKey(), application.getServiceType(), timeHistogram); + this.addAgentHistogram(agentEntry.getKey(), application.serviceType(), timeHistogram); } } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java index 75184a417aa3..59d5670e4d51 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallData.java @@ -99,7 +99,7 @@ private TimeHistogram getTimeHistogram(final Long timeStamp) { final Long refineTimestamp = timeWindow.refineTimestamp(timeStamp); TimeHistogram histogram = targetHistogramTimeMap.get(refineTimestamp); if (histogram == null) { - histogram = new TimeHistogram(target.getServiceType(), refineTimestamp); + histogram = new TimeHistogram(target.serviceType(), refineTimestamp); targetHistogramTimeMap.put(refineTimestamp, histogram); } return histogram; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallDataMap.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallDataMap.java index e5373b6117bf..4116e6ea0452 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallDataMap.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkCallDataMap.java @@ -118,7 +118,7 @@ public AgentHistogramList getInLinkList() { // need target (to) ServiceType // the definition of source is data from the source when the source sends a request to a target. // Thus ServiceType is the target's ServiceType - sourceList.addAgentHistogram(key.getFrom().getName(), key.getTo().getServiceType(), linkCallData.getTimeHistogram()); + sourceList.addAgentHistogram(key.getFrom().name(), key.getTo().serviceType(), linkCallData.getTimeHistogram()); } return sourceList; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java index 841083334763..a225ace90651 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/rawdata/LinkDataMap.java @@ -44,7 +44,7 @@ public Collection getLinkDataList() { public void addLinkData(Application sourceApplication, String sourceAgentId, Application destinationApplication, String destinationAgentId, long timestamp, short slotTime, long count) { final LinkData linkData = getLinkData(sourceApplication, destinationApplication); - linkData.addLinkData(sourceAgentId, sourceApplication.getServiceType(), destinationAgentId, destinationApplication.getServiceType(), timestamp, slotTime, count); + linkData.addLinkData(sourceAgentId, sourceApplication.serviceType(), destinationAgentId, destinationApplication.serviceType(), timestamp, slotTime, count); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImpl.java index 0de6085f396b..99be90522c1d 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImpl.java @@ -35,11 +35,11 @@ import com.navercorp.pinpoint.web.applicationmap.map.FilteredMap; import com.navercorp.pinpoint.web.applicationmap.map.FilteredMapBuilder; import com.navercorp.pinpoint.web.component.ApplicationFactory; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; import com.navercorp.pinpoint.web.dao.TraceDao; import com.navercorp.pinpoint.web.filter.Filter; import com.navercorp.pinpoint.web.scatter.ScatterData; import com.navercorp.pinpoint.web.security.ServerMapDataFilter; +import com.navercorp.pinpoint.web.service.ApplicationTraceIndexService; import com.navercorp.pinpoint.web.service.ServerInstanceDatasourceService; import com.navercorp.pinpoint.web.vo.Application; import com.navercorp.pinpoint.web.vo.LimitedScanResult; @@ -69,7 +69,7 @@ public class FilteredMapServiceImpl implements FilteredMapService { private final TraceDao traceDao; - private final ApplicationTraceIndexDao applicationTraceIndexDao; + private final ApplicationTraceIndexService applicationTraceIndexService; private final ServiceTypeRegistryService registry; @@ -87,14 +87,14 @@ public class FilteredMapServiceImpl implements FilteredMapService { private long buildTimeoutMillis; public FilteredMapServiceImpl(TraceDao traceDao, - ApplicationTraceIndexDao applicationTraceIndexDao, + ApplicationTraceIndexService applicationTraceIndexService, ServiceTypeRegistryService registry, ApplicationFactory applicationFactory, ServerInstanceDatasourceService serverInstanceDatasourceService, Optional serverMapDataFilter, ApplicationMapBuilderFactory applicationMapBuilderFactory) { this.traceDao = Objects.requireNonNull(traceDao, "traceDao"); - this.applicationTraceIndexDao = Objects.requireNonNull(applicationTraceIndexDao, "applicationTraceIndexDao"); + this.applicationTraceIndexService = Objects.requireNonNull(applicationTraceIndexService, "applicationTraceIndexService"); this.registry = Objects.requireNonNull(registry, "registry"); this.applicationFactory = Objects.requireNonNull(applicationFactory, "applicationFactory"); this.serverInstanceDatasourceService = Objects.requireNonNull(serverInstanceDatasourceService, "serverInstanceDatasourceService"); @@ -116,7 +116,7 @@ public LimitedScanResult> selectTraceIdsFromApplicationTrace logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, range); } - return this.applicationTraceIndexDao.scanTraceIndex(applicationName, range, limit, backwardDirection); + return this.applicationTraceIndexService.scanTraceIndex(applicationName, range, limit, backwardDirection); } private List> filterList2(List> transactionList, Filter> filter) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImpl.java index b53146590e09..23c8e8eba0fc 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImpl.java @@ -106,7 +106,7 @@ public AgentHistogramList selectResponseTimeHistogramData(Application applicatio public NodeHistogramSummary selectNodeHistogramData(ResponseTimeHistogramServiceOption option) { Application application = option.getApplication(); - ServiceType applicationServiceType = application.getServiceType(); + ServiceType applicationServiceType = application.serviceType(); if (applicationServiceType.isWas()) { return getWasNodeHistogramSummary(option); @@ -162,7 +162,7 @@ private NodeHistogramSummary getWasNodeHistogramSummary(ResponseTimeHistogramSer private NodeHistogramSummary getTerminalNodeHistogramSummary(ResponseTimeHistogramServiceOption option) { Application application = option.getApplication(); Range range = option.getRange(); - ServiceType applicationServiceType = application.getServiceType(); + ServiceType applicationServiceType = application.serviceType(); final ServerGroupListFactory serverGroupListFactory = createServerGroupListFactory(option.isUseStatisticsAgentState()); List sourceApplications = option.getFromApplications(); @@ -233,7 +233,7 @@ public LinkHistogramSummary selectLinkHistogramData(Application fromApplication, LinkDataDuplexMap linkDataDuplexMap; - ServiceType fromApplicationServiceType = fromApplication.getServiceType(); + ServiceType fromApplicationServiceType = fromApplication.serviceType(); LinkDirection linkDirection = LinkDirection.OUT_LINK; if (fromApplicationServiceType.isUser()) { //scan using toApplication to distinguish same applicationName with different serviceType diff --git a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AdminController.java b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AdminController.java index 8ceb1dddd994..adbbdb7c092e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AdminController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AdminController.java @@ -16,7 +16,12 @@ package com.navercorp.pinpoint.web.authorization.controller; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; import com.navercorp.pinpoint.web.service.AdminService; +import com.navercorp.pinpoint.web.service.ApplicationInfoService; +import com.navercorp.pinpoint.web.service.ServiceInfoService; import com.navercorp.pinpoint.web.vo.Application; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; @@ -46,16 +51,28 @@ public class AdminController { private final Logger logger = LogManager.getLogger(this.getClass()); private final AdminService adminService; + private final ServiceInfoService serviceInfoService; + private final ApplicationInfoService applicationInfoService; - public AdminController(AdminService adminService) { + public AdminController( + AdminService adminService, + ServiceInfoService serviceInfoService, + ApplicationInfoService applicationInfoService + ) { this.adminService = Objects.requireNonNull(adminService, "adminService"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); } @RequestMapping(value = "/removeApplicationName") - public String removeApplicationName(@RequestParam("applicationName") @NotBlank String applicationName) { - logger.info("Removing application - applicationName: [{}]", applicationName); + public String removeApplicationName( + @RequestParam(value = "serviceName", defaultValue = ServiceId.DEFAULT_SERVICE_NAME) String serviceName, + @RequestParam("applicationName") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeCode", defaultValue = "5004") short serviceTypeCode + ) { try { - this.adminService.removeApplicationName(applicationName); + ApplicationId applicationId = this.getApplicationId(serviceName, applicationName, serviceTypeCode); + this.adminService.removeApplicationName(applicationId); return "OK"; } catch (Exception e) { logger.error("error while removing applicationName", e); @@ -65,12 +82,15 @@ public String removeApplicationName(@RequestParam("applicationName") @NotBlank S @RequestMapping(value = "/removeAgentId") public String removeAgentId( + @RequestParam(value = "serviceName", defaultValue = ServiceId.DEFAULT_SERVICE_NAME) String serviceName, @RequestParam(value = "applicationName") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeCode", defaultValue = "5004") short serviceTypeCode, @RequestParam(value = "agentId") @NotBlank String agentId ) { logger.info("Removing agent - applicationName: [{}], agentId: [{}]", applicationName, agentId); try { - this.adminService.removeAgentId(applicationName, agentId); + ApplicationId applicationId = this.getApplicationId(serviceName, applicationName, serviceTypeCode); + this.adminService.removeAgentId(applicationId, agentId); return "OK"; } catch (Exception e) { logger.error("error while removing agentId", e); @@ -106,14 +126,31 @@ public Map> duplicateAgentIdMap() { @RequestMapping(value = "/getInactiveAgents") public Map> getInactiveAgents( + @RequestParam(value = "serviceName", defaultValue = ServiceId.DEFAULT_SERVICE_NAME) String serviceName, @RequestParam(value = "applicationName") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeCode", defaultValue = "5004") short serviceTypeCode, @RequestParam(value = "durationDays", defaultValue = AdminService.MIN_DURATION_DAYS_FOR_INACTIVITY_STR) @Min(AdminService.MIN_DURATION_DAYS_FOR_INACTIVITY) int durationDays ) { logger.info("Getting in-active agents - applicationName: [{}], duration: {} days.", applicationName, durationDays); - return this.adminService.getInactiveAgents(applicationName, durationDays); + ApplicationId applicationId = this.getApplicationId(serviceName, applicationName, serviceTypeCode); + return this.adminService.getInactiveAgents(applicationId, durationDays); + } + + private ApplicationId getApplicationId(String serviceName, String applicationName, short serviceTypeCode) { + ServiceId serviceId = this.serviceInfoService.getServiceId(serviceName); + if (serviceId == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Service [" + serviceName + "] not found"); + } + + ApplicationId applicationId = this.applicationInfoService.getApplicationId(new ApplicationSelector(serviceId, applicationName, serviceTypeCode)); + if (applicationId == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Application [" + applicationName + "] not found"); + } + + return applicationId; } } \ No newline at end of file diff --git a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentInfoController.java b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentInfoController.java index 5a2bfe328841..36161c747482 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentInfoController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentInfoController.java @@ -19,7 +19,9 @@ import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.server.util.AgentEventType; import com.navercorp.pinpoint.common.server.util.time.Range; +import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.IdValidateUtils; +import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; import com.navercorp.pinpoint.web.response.CodeResult; import com.navercorp.pinpoint.web.service.AgentEventService; import com.navercorp.pinpoint.web.service.AgentInfoService; @@ -28,6 +30,7 @@ import com.navercorp.pinpoint.web.view.tree.TreeView; import com.navercorp.pinpoint.web.vo.AgentEvent; import com.navercorp.pinpoint.web.vo.agent.AgentAndStatus; +import com.navercorp.pinpoint.web.vo.agent.AgentInfoFilters; import com.navercorp.pinpoint.web.vo.agent.AgentStatus; import com.navercorp.pinpoint.web.vo.agent.AgentStatusAndLink; import com.navercorp.pinpoint.web.vo.agent.AgentStatusFilter; @@ -60,15 +63,21 @@ @RequestMapping("/api") @Validated public class AgentInfoController { - private final AgentInfoService agentInfoService; + private final AgentInfoService agentInfoService; private final AgentEventService agentEventService; + private final ServiceTypeRegistryService serviceTypeRegistryService; private final SortByAgentInfo.Rules DEFAULT_SORT_BY = SortByAgentInfo.Rules.AGENT_ID_ASC; - public AgentInfoController(AgentInfoService agentInfoService, AgentEventService agentEventService) { + public AgentInfoController( + AgentInfoService agentInfoService, + AgentEventService agentEventService, + ServiceTypeRegistryService serviceTypeRegistryService + ) { this.agentInfoService = Objects.requireNonNull(agentInfoService, "agentInfoService"); this.agentEventService = Objects.requireNonNull(agentEventService, "agentEventService"); + this.serviceTypeRegistryService = Objects.requireNonNull(serviceTypeRegistryService, "serviceTypeRegistryService"); } @GetMapping(value = "/getAgentList", params = {"!application"}) @@ -103,21 +112,26 @@ private static TreeView> treeView(AgentsMapByApplicatio @GetMapping(value = "/getAgentList", params = {"application"}) public TreeView> getAgentList( - @RequestParam("application") @NotBlank String applicationName + @RequestParam("application") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeName", required = false) String serviceTypeName ) { final long timestamp = System.currentTimeMillis(); - return getAgentList(applicationName, timestamp); + return getAgentList(applicationName, serviceTypeName, timestamp); } @GetMapping(value = "/getAgentList", params = {"application", "from", "to"}) public TreeView> getAgentList( @RequestParam("application") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeName", required = false) String serviceTypeName, @RequestParam("from") @PositiveOrZero long from, @RequestParam("to") @PositiveOrZero long to) { final AgentStatusFilter currentRunFilter = AgentStatusFilters.recentRunning(from); + final ServiceType serviceType = findServiceTypeByName(serviceTypeName); final AgentsMapByHost list = this.agentInfoService.getAgentsListByApplicationName( currentRunFilter, + AgentInfoFilters.acceptAll(), applicationName, + serviceType.getCode(), Range.between(from, to), DEFAULT_SORT_BY ); @@ -127,10 +141,14 @@ public TreeView> getAgentList( @GetMapping(value = "/getAgentList", params = {"application", "timestamp"}) public TreeView> getAgentList( @RequestParam("application") @NotBlank String applicationName, + @RequestParam(value = "serviceTypeName", required = false) String serviceTypeName, @RequestParam("timestamp") @PositiveOrZero long timestamp) { + final ServiceType serviceType = findServiceTypeByName(serviceTypeName); final AgentsMapByHost list = this.agentInfoService.getAgentsListByApplicationName( AgentStatusFilters.running(), + AgentInfoFilters.acceptAll(), applicationName, + serviceType.getCode(), Range.between(timestamp, timestamp), DEFAULT_SORT_BY ); @@ -236,4 +254,11 @@ public CodeResult isAvailableAgentId(@RequestParam("agentId") @NotBlank return CodeResult.ok("OK"); } + private ServiceType findServiceTypeByName(String serviceTypeName) { + if (serviceTypeName == null) { + return PinpointConstants.DEFAULT_SERVICE_TYPE; + } + return this.serviceTypeRegistryService.findServiceTypeByName(serviceTypeName); + } + } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentListController.java b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentListController.java index e09bb212fa65..258e336819bb 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentListController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/AgentListController.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.authorization.controller; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; @@ -30,14 +31,14 @@ import com.navercorp.pinpoint.web.vo.tree.SortByAgentInfo; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.PositiveOrZero; +import org.springframework.http.HttpStatus; import org.springframework.util.CollectionUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; import java.util.ArrayList; import java.util.Collections; @@ -52,6 +53,7 @@ @RequestMapping(value = "/api/agents") @Validated public class AgentListController { + private final AgentInfoService agentInfoService; private final ServiceTypeRegistryService registry; private final ApplicationFactory applicationFactory; @@ -102,14 +104,21 @@ private static TreeView> treeView(AgentsMapByApplication public TreeView> getAgentsList( @RequestParam("application") @NotBlank String applicationName, @RequestParam(value = "serviceTypeCode", required = false) Short serviceTypeCode, - @RequestParam(value = "serviceTypeName", required = false) String serviceTypeName, + @RequestParam(value = "serviceTypeName") String serviceTypeName, @RequestParam(value = "sortBy") Optional sortBy) { final SortByAgentInfo.Rules paramSortBy = sortBy.orElse(DEFAULT_SORT_BY); final long timestamp = System.currentTimeMillis(); + + ServiceType serviceType = this.registry.findServiceTypeByName(serviceTypeName); + if (serviceType == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Service type not found: " + serviceTypeName); + } + final AgentsMapByHost list = this.agentInfoService.getAgentsListByApplicationName( AgentStatusFilters.running(), AgentInfoFilters.exactServiceType(serviceTypeCode, serviceTypeName), applicationName, + serviceType.getCode(), Range.between(timestamp, timestamp), paramSortBy ); @@ -120,16 +129,23 @@ public TreeView> getAgentsList( public TreeView> getAgentsList( @RequestParam("application") @NotBlank String applicationName, @RequestParam(value = "serviceTypeCode", required = false) Short serviceTypeCode, - @RequestParam(value = "serviceTypeName", required = false) String serviceTypeName, + @RequestParam(value = "serviceTypeName") String serviceTypeName, @RequestParam("from") @PositiveOrZero long from, @RequestParam("to") @PositiveOrZero long to, @RequestParam(value = "sortBy") Optional sortBy ) { final SortByAgentInfo.Rules paramSortBy = sortBy.orElse(DEFAULT_SORT_BY); + + ServiceType serviceType = this.registry.findServiceTypeByName(serviceTypeName); + if (serviceType == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Service type not found: " + serviceTypeName); + } + final AgentsMapByHost list = this.agentInfoService.getAgentsListByApplicationName( AgentStatusFilters.recentRunning(from), AgentInfoFilters.exactServiceType(serviceTypeCode, serviceTypeName), applicationName, + serviceType.getCode(), Range.between(from, to), paramSortBy ); @@ -193,7 +209,7 @@ private AgentsMapByHost extractVirtualNode(NodeHistogramSummary nodeHistogramSum List agents = new ArrayList<>(); for (ServerInstance instance : group.getInstanceList()) { AgentInfo agentInfo = new AgentInfo(); - agentInfo.setAgentId(instance.getName()); + agentInfo.setAgentId(AgentId.of(instance.getName())); agentInfo.setAgentName(instance.getAgentName()); agentInfo.setServiceType(instance.getServiceType()); @@ -211,7 +227,7 @@ private AgentsMapByHost extractVirtualNode(NodeHistogramSummary nodeHistogramSum listMap.add(instancesList); } - return new AgentsMapByHost(new InstancesListMap(listMap)); + return new AgentsMapByHost(new InstancesListMap<>(listMap)); } private static TreeView> treeView(AgentsMapByHost agentsMapByHost) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/ResponseTimeController.java b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/ResponseTimeController.java index 83431b01016b..d5c91b40cbca 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/ResponseTimeController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/authorization/controller/ResponseTimeController.java @@ -163,8 +163,8 @@ public HistogramView getWasHistogramData( } private ResponseTimeHistogramServiceOption.Builder createWasOptionBuilder(Application application, Range range) { - if (!application.getServiceType().isWas()) { - throw new IllegalArgumentException("application is not WAS. application:" + application + ", serviceTypeCode:" + application.getServiceType()); + if (!application.serviceType().isWas()) { + throw new IllegalArgumentException("application is not WAS. application:" + application + ", serviceTypeCode:" + application.serviceType()); } return new ResponseTimeHistogramServiceOption.Builder(application, range, Collections.emptyList(), Collections.emptyList()); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/cache/CacheConfiguration.java b/web/src/main/java/com/navercorp/pinpoint/web/cache/CacheConfiguration.java index 026a626aa2d7..1d421ba81628 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/cache/CacheConfiguration.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/cache/CacheConfiguration.java @@ -16,8 +16,11 @@ package com.navercorp.pinpoint.web.cache; +import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.navercorp.pinpoint.common.server.config.CommonCacheManagerConfiguration; +import com.navercorp.pinpoint.common.server.config.CustomCacheRegistration; +import com.navercorp.pinpoint.common.server.config.DefaultCustomCacheRegistration; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurer; import org.springframework.cache.annotation.EnableCaching; @@ -46,6 +49,16 @@ public CacheManager apiMetaData() { return caffeineCacheManager; } + @Bean + public CustomCacheRegistration apiMetadataCache() { + Cache cache = Caffeine.newBuilder() + .expireAfterWrite(600, TimeUnit.SECONDS) + .initialCapacity(500) + .maximumSize(10000) + .build(); + return new DefaultCustomCacheRegistration(API_METADATA_CACHE_NAME, cache); + } + @Bean public CacheManager applicationNameList() { CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(APPLICATION_LIST_CACHE_NAME); @@ -56,4 +69,14 @@ public CacheManager applicationNameList() { return caffeineCacheManager; } + @Bean + public CustomCacheRegistration applicationNameListCache() { + Cache cache = Caffeine.newBuilder() + .expireAfterWrite(120, TimeUnit.SECONDS) + .initialCapacity(10) + .maximumSize(200) + .build(); + return new DefaultCustomCacheRegistration(APPLICATION_LIST_CACHE_NAME, cache); + } + } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/MetaSpanCallTreeFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/MetaSpanCallTreeFactory.java index a662e42c7bf1..5a238c5547c6 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/MetaSpanCallTreeFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/MetaSpanCallTreeFactory.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.calltree.span; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; import com.navercorp.pinpoint.common.server.bo.ApiMetaDataBo; @@ -33,24 +34,24 @@ * @author jaehong.kim */ public class MetaSpanCallTreeFactory { - private static final long DEFAULT_TIMEOUT_MILLISEC = 60 * 1000; + private static final long DEFAULT_TIMEOUT_MILLI = 60 * 1000; - private static final String UNKNOWN_AGENT_ID = "UNKNOWN"; - private static final String CORRUPTED_AGENT_ID = "CORRUPTED"; + private static final AgentId UNKNOWN_AGENT_ID = AgentId.of("UNKNOWN"); + private static final AgentId CORRUPTED_AGENT_ID = AgentId.of("CORRUPTED"); private static final long AGENT_START_TIME = 0; - private long timeoutMillisec = DEFAULT_TIMEOUT_MILLISEC; + private final long timeoutMilli = DEFAULT_TIMEOUT_MILLI; public CallTree unknown(final long startTimeMillis) { final SpanBo rootSpan = new SpanBo(); rootSpan.setTransactionId(new TransactionId(UNKNOWN_AGENT_ID, AGENT_START_TIME, 0)); rootSpan.setAgentId(UNKNOWN_AGENT_ID); - rootSpan.setApplicationId("UNKNOWN"); + rootSpan.setApplicationName("UNKNOWN"); rootSpan.setStartTime(startTimeMillis); rootSpan.setServiceType(ServiceType.UNKNOWN.getCode()); List annotations = new ArrayList<>(); - ApiMetaDataBo apiMetaData = new ApiMetaDataBo(UNKNOWN_AGENT_ID, AGENT_START_TIME, 0, LineNumber.NO_LINE_NUMBER, + ApiMetaDataBo apiMetaData = new ApiMetaDataBo(UNKNOWN_AGENT_ID.value(), AGENT_START_TIME, 0, LineNumber.NO_LINE_NUMBER, MethodTypeEnum.WEB_REQUEST, "Unknown"); final AnnotationBo apiMetaDataAnnotation = AnnotationBo.of(AnnotationKey.API_METADATA.getCode(), apiMetaData); @@ -71,12 +72,12 @@ public SpanCallTree corrupted(final String title, final long parentSpanId, final rootSpan.setTransactionId(new TransactionId(CORRUPTED_AGENT_ID, AGENT_START_TIME, 0)); rootSpan.setAgentId(CORRUPTED_AGENT_ID); - rootSpan.setApplicationId("CORRUPTED"); + rootSpan.setApplicationName("CORRUPTED"); rootSpan.setServiceType(ServiceType.UNKNOWN.getCode()); List annotations = new ArrayList<>(); - ApiMetaDataBo apiMetaData = new ApiMetaDataBo(CORRUPTED_AGENT_ID, AGENT_START_TIME, 0, LineNumber.NO_LINE_NUMBER, + ApiMetaDataBo apiMetaData = new ApiMetaDataBo(CORRUPTED_AGENT_ID.value(), AGENT_START_TIME, 0, LineNumber.NO_LINE_NUMBER, MethodTypeEnum.CORRUPTED, "..."); final AnnotationBo apiMetaDataAnnotation = AnnotationBo.of(AnnotationKey.API_METADATA.getCode(), apiMetaData); @@ -92,7 +93,7 @@ public SpanCallTree corrupted(final String title, final long parentSpanId, final } private String getErrorMessage(String title, long startTimeMillis) { - if (System.currentTimeMillis() - startTimeMillis < timeoutMillisec) { + if (System.currentTimeMillis() - startTimeMillis < timeoutMilli) { return "Corrupted(waiting for packet) "; } else { if (title != null) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/Node.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/Node.java index 5666f1e935e3..c3ea983e93f4 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/Node.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/Node.java @@ -76,7 +76,7 @@ public void setCorrupted(boolean corrupted) { @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); - sb.append("applicationId").append(span.getApplicationId()); + sb.append("applicationId").append(span.getApplicationName()); sb.append(", agentId=").append(span.getAgentId()); sb.append(", parentSpanId=").append(span.getParentSpanId()); sb.append(", spanId=").append(span.getSpanId()); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java index 48e8a8434bbf..7a7a8c599cb0 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanAlign.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.calltree.span; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanChunkBo; @@ -168,10 +169,10 @@ public long getElapsed() { @Override public String getAgentId() { if (isMeta()) { - return " "; + return AgentId.of(" ").value(); } - return spanBo.getAgentId(); + return AgentId.unwrap(spanBo.getAgentId()); } @Override @@ -190,7 +191,7 @@ public String getApplicationId() { if (isMeta()) { return " "; } - return spanBo.getApplicationId(); + return spanBo.getApplicationName(); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanEventAlign.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanEventAlign.java index 4d39850ae0c9..b3df4f236b6c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanEventAlign.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanEventAlign.java @@ -144,7 +144,7 @@ public long getElapsed() { @Override public String getAgentId() { - return spanBo.getAgentId(); + return spanBo.getAgentId().value(); } @Override @@ -154,7 +154,7 @@ public String getAgentName() { @Override public String getApplicationId() { - return spanBo.getApplicationId(); + return spanBo.getApplicationName(); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanFilters.java b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanFilters.java index 19e976ce68ce..7127e5ea9e50 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanFilters.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/calltree/span/SpanFilters.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.calltree.span; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.util.StringUtils; @@ -142,7 +143,7 @@ public SpanAgentIdPredicate(String agentId) { @Override public boolean test(SpanBo spanBo) { - return agentId.equals(spanBo.getAgentId()); + return agentId.equals(AgentId.unwrap(spanBo.getAgentId())); } @Override @@ -173,7 +174,7 @@ public static Predicate applicationIdFilter(String applicationId) { return new Predicate<>() { @Override public boolean test(SpanBo spanBo) { - return applicationId.equals(spanBo.getApplicationId()); + return applicationId.equals(spanBo.getApplicationName()); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/component/ApplicationFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/component/ApplicationFactory.java index 26e3f83a8c8b..5e89b5f97991 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/component/ApplicationFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/component/ApplicationFactory.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.web.component; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.vo.Application; @@ -25,6 +26,8 @@ */ public interface ApplicationFactory { + Application createApplication(ApplicationId applicationId, String applicationName, short serviceTypeCode); + Application createApplication(String applicationName, short serviceTypeCode); Application createApplication(String applicationName, ServiceType serviceType); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/component/DefaultApplicationFactory.java b/web/src/main/java/com/navercorp/pinpoint/web/component/DefaultApplicationFactory.java index 40eac63b499a..c6292285107a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/component/DefaultApplicationFactory.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/component/DefaultApplicationFactory.java @@ -17,6 +17,7 @@ package com.navercorp.pinpoint.web.component; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; import com.navercorp.pinpoint.web.vo.Application; @@ -36,6 +37,12 @@ public DefaultApplicationFactory(ServiceTypeRegistryService registry) { this.registry = Objects.requireNonNull(registry, "registry"); } + @Override + public Application createApplication(ApplicationId applicationId, String applicationName, short serviceTypeCode) { + final ServiceType serviceType = registry.findServiceType(serviceTypeCode); + return new Application(applicationId, applicationName, serviceType); + } + @Override public Application createApplication(String applicationName, short serviceTypeCode) { Objects.requireNonNull(applicationName, "applicationName"); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/controller/ApplicationController.java b/web/src/main/java/com/navercorp/pinpoint/web/controller/ApplicationController.java index e0685fc28a32..4945c672cc41 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/controller/ApplicationController.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/controller/ApplicationController.java @@ -16,10 +16,15 @@ package com.navercorp.pinpoint.web.controller; import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; import com.navercorp.pinpoint.common.util.IdValidateUtils; import com.navercorp.pinpoint.web.response.CodeResult; import com.navercorp.pinpoint.web.service.AgentInfoService; +import com.navercorp.pinpoint.web.service.ApplicationInfoService; import com.navercorp.pinpoint.web.service.ApplicationService; +import com.navercorp.pinpoint.web.service.ServiceInfoService; import com.navercorp.pinpoint.web.vo.tree.ApplicationAgentHostList; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Positive; @@ -46,11 +51,19 @@ public class ApplicationController { public static final int MAX_PAGING_LIMIT = 100; + private final ServiceInfoService serviceInfoService; + private final ApplicationInfoService applicationInfoService; private final AgentInfoService agentInfoService; - private final ApplicationService applicationService; - public ApplicationController(AgentInfoService agentInfoService, ApplicationService applicationService) { + public ApplicationController( + ServiceInfoService serviceInfoService, + ApplicationInfoService applicationInfoService, + AgentInfoService agentInfoService, + ApplicationService applicationService + ) { + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); this.agentInfoService = Objects.requireNonNull(agentInfoService, "agentInfoService"); this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); } @@ -70,7 +83,9 @@ public ApplicationAgentHostList getApplicationHostInfo ( @RequestMapping(value = "/isAvailableApplicationName") public CodeResult isAvailableApplicationName( - @RequestParam("applicationName") @NotBlank String applicationName + @RequestParam(value = "serviceName", defaultValue = ServiceId.DEFAULT_SERVICE_NAME) String serviceName, + @RequestParam("applicationName") @NotBlank String applicationName, + @RequestParam("serviceTypeCode") short serviceTypeCode ) { final IdValidateUtils.CheckResult result = IdValidateUtils.checkId(applicationName, PinpointConstants.APPLICATION_NAME_MAX_LEN); @@ -84,7 +99,15 @@ public CodeResult isAvailableApplicationName( ); } - if (applicationService.isExistApplicationName(applicationName)) { + ServiceId serviceId = this.serviceInfoService.getServiceId(serviceName); + if (serviceId == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "serviceName not found"); + } + + ApplicationId applicationId = this.applicationInfoService.getApplicationId(new ApplicationSelector(serviceId, applicationName, serviceTypeCode)); + + + if (applicationService.isExistApplicationName(applicationId)) { throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "applicationName already exists"); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java index 9fcc58ec3a1d..b9e86cddecb2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/AgentLifeCycleDao.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.dao; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.web.vo.agent.AgentStatus; import com.navercorp.pinpoint.web.vo.agent.AgentStatusQuery; @@ -29,7 +30,7 @@ public interface AgentLifeCycleDao { AgentStatus getAgentStatus(String agentId, long timestamp); - Optional getAgentStatus(String agentId, long agentStartTimestamp, long timestamp); + Optional getAgentStatus(AgentId agentId, long agentStartTimestamp, long timestamp); List> getAgentStatus(AgentStatusQuery agentStatusQuery); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java index 640d40b96976..d09ffa4017a8 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDao.java @@ -16,20 +16,20 @@ package com.navercorp.pinpoint.web.dao; +import com.navercorp.pinpoint.web.vo.Application; + import java.util.List; import java.util.Map; -import com.navercorp.pinpoint.web.vo.Application; - /** * * @author netspider * */ public interface ApplicationIndexDao { - List selectAllApplicationNames(); + List selectAllApplications(); - List selectApplicationName(String applicationName); + List selectApplicationByName(String applicationName); List selectAgentIds(String applicationName); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDaoV2.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDaoV2.java new file mode 100644 index 000000000000..f08ddec401f0 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationIndexDaoV2.java @@ -0,0 +1,44 @@ +/* + * Copyright 2014 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.dao; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.web.vo.Application; + +import java.util.List; +import java.util.Map; + +/** + * + * @author netspider + * + */ +public interface ApplicationIndexDaoV2 { + + List selectAllApplications(); + + List selectApplicationName(ApplicationId applicationId); + + List selectAgentIds(ApplicationId applicationId); + + void deleteApplication(ApplicationId applicationId); + + void deleteAgentIds(Map> applicationAgentIdMap); + + void deleteAgentId(ApplicationId applicationId, String agentId); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationInfoDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationInfoDao.java new file mode 100644 index 000000000000..31148a1e5c34 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationInfoDao.java @@ -0,0 +1,41 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.dao; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import com.navercorp.pinpoint.web.vo.Application; + +import java.util.List; + +/** + * @author youngjin.kim2 + */ +public interface ApplicationInfoDao { + + ApplicationId getApplicationId(ApplicationSelector application); + + Application getApplication(ApplicationId application); + + ApplicationId putApplicationIdIfAbsent(ApplicationInfo application); + + List getApplications(); + + List getApplications(ServiceId serviceId); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDaoV2.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDaoV2.java new file mode 100644 index 000000000000..af815d71b771 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ApplicationTraceIndexDaoV2.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.dao; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.profiler.util.TransactionId; +import com.navercorp.pinpoint.common.server.util.time.Range; +import com.navercorp.pinpoint.web.scatter.DragArea; +import com.navercorp.pinpoint.web.scatter.DragAreaQuery; +import com.navercorp.pinpoint.web.vo.LimitedScanResult; +import com.navercorp.pinpoint.web.vo.scatter.Dot; +import com.navercorp.pinpoint.web.vo.scatter.DotMetaData; + +import java.util.List; + +/** + * @author emeroad + * @author netspider + */ +public interface ApplicationTraceIndexDaoV2 { + + boolean hasTraceIndex(ApplicationId applicationId, Range range, boolean backwardDirection); + + LimitedScanResult> scanTraceIndex(ApplicationId applicationId, Range range, int limit, boolean backwardDirection); + + LimitedScanResult> scanTraceScatterData(ApplicationId applicationId, Range range, int limit, boolean scanBackward); + + + LimitedScanResult> scanTraceIndex(ApplicationId applicationId, DragArea dragArea, int limit); + + + @Deprecated + LimitedScanResult> scanScatterData(ApplicationId applicationId, DragAreaQuery dragAreaQuery, int limit); + + LimitedScanResult> scanScatterDataV2(ApplicationId applicationId, DragAreaQuery dragAreaQuery, int limit); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/ServiceInfoDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/ServiceInfoDao.java new file mode 100644 index 000000000000..a0cf92976379 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/ServiceInfoDao.java @@ -0,0 +1,34 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.dao; + +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; + +import java.util.List; + +/** + * @author youngjin.kim2 + */ +public interface ServiceInfoDao { + + ServiceId getServiceId(String serviceName); + + ServiceInfo getServiceInfo(ServiceId serviceId); + + List getServiceInfos(); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java index ea7d0daedcbc..fe8d23c64db4 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDao.java @@ -21,6 +21,7 @@ import com.navercorp.pinpoint.common.hbase.ResultsExtractor; import com.navercorp.pinpoint.common.hbase.RowMapper; import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentLifeCycleBo; import com.navercorp.pinpoint.common.server.bo.SimpleAgentKey; import com.navercorp.pinpoint.common.server.bo.serializer.agent.AgentIdRowKeyEncoder; @@ -83,7 +84,7 @@ public AgentStatus getAgentStatus(String agentId, long timestamp) { } @Override - public Optional getAgentStatus(String agentId, long agentStartTimestamp, long timestamp) { + public Optional getAgentStatus(AgentId agentId, long agentStartTimestamp, long timestamp) { if (agentId == null) { return Optional.empty(); } @@ -91,11 +92,11 @@ public Optional getAgentStatus(String agentId, long agentStartTimes // startTimestamp is stored in reverse order final long toTimestamp = agentStartTimestamp; final long fromTimestamp = toTimestamp - 1; - Scan scan = createScan(agentId, fromTimestamp, toTimestamp); + Scan scan = createScan(AgentId.unwrap(agentId), fromTimestamp, toTimestamp); TableName agentLifeCycleTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); AgentLifeCycleBo agentLifeCycleBo = this.hbaseOperations.find(agentLifeCycleTableName, scan, new MostRecentAgentLifeCycleResultsExtractor(this.agentLifeCycleMapper, timestamp)); - AgentStatus agentStatus = createAgentStatus(agentId, agentLifeCycleBo); + AgentStatus agentStatus = createAgentStatus(agentId.value(), agentLifeCycleBo); return Optional.of(agentStatus); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java index a36c5dd26986..4723f6b640d2 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDao.java @@ -32,7 +32,7 @@ import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.ArrayList; @@ -44,7 +44,7 @@ * @author netspider * @author emeroad */ -@Repository +@Component public class HbaseApplicationIndexDao implements ApplicationIndexDao { private static final HbaseColumnFamily.ApplicationIndex DESCRIPTOR = HbaseColumnFamily.APPLICATION_INDEX_AGENTS; @@ -68,7 +68,7 @@ public HbaseApplicationIndexDao(HbaseOperations hbaseOperations, } @Override - public List selectAllApplicationNames() { + public List selectAllApplications() { Scan scan = new Scan(); scan.setCaching(30); scan.addFamily(DESCRIPTOR.getName()); @@ -80,7 +80,7 @@ public List selectAllApplicationNames() { } @Override - public List selectApplicationName(String applicationName) { + public List selectApplicationByName(String applicationName) { return selectApplicationIndex0(applicationName, applicationNameMapper); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDaoV2.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDaoV2.java new file mode 100644 index 000000000000..eed255c53ab2 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationIndexDaoV2.java @@ -0,0 +1,160 @@ +/* + * Copyright 2014 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.dao.hbase; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.util.StringUtils; +import com.navercorp.pinpoint.web.dao.ApplicationIndexDaoV2; +import com.navercorp.pinpoint.web.util.ListListUtils; +import com.navercorp.pinpoint.web.vo.Application; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.util.Bytes; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * @author netspider + * @author emeroad + * @author smilu97 + */ +@Component +public class HbaseApplicationIndexDaoV2 implements ApplicationIndexDaoV2 { + + private static final HbaseColumnFamily.ApplicationIndex DESCRIPTOR = HbaseColumnFamily.APPLICATION_INDEX_AGENTS_VER2; + + private final HbaseOperations hbaseOperations; + private final TableNameProvider tableNameProvider; + private final RowMapper> applicationNameMapper; + private final RowMapper> agentIdMapper; + + + public HbaseApplicationIndexDaoV2(HbaseOperations hbaseOperations, + TableNameProvider tableNameProvider, + @Qualifier("applicationNameMapperV2") RowMapper> applicationNameMapper, + @Qualifier("agentIdMapper") RowMapper> agentIdMapper) { + this.hbaseOperations = Objects.requireNonNull(hbaseOperations, "hbaseOperations"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.applicationNameMapper = Objects.requireNonNull(applicationNameMapper, "applicationNameMapper"); + this.agentIdMapper = Objects.requireNonNull(agentIdMapper, "agentIdMapper"); + } + + @Override + public List selectAllApplications() { + Scan scan = new Scan(); + scan.setCaching(30); + scan.addFamily(DESCRIPTOR.getName()); + + TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); + List> results = hbaseOperations.find(applicationIndexTableName, scan, applicationNameMapper); + + return ListListUtils.toList(results); + } + + @Override + public List selectApplicationName(ApplicationId applicationId) { + return selectApplicationIndex0(applicationId, applicationNameMapper); + } + + @Override + public List selectAgentIds(ApplicationId applicationId) { + return selectApplicationIndex0(applicationId, agentIdMapper); + } + + private List selectApplicationIndex0(ApplicationId applicationId, RowMapper> rowMapper) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(rowMapper, "rowMapper"); + + byte[] rowKey = applicationId.toBytes(); + + Get get = new Get(rowKey); + get.addFamily(DESCRIPTOR.getName()); + + TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); + return hbaseOperations.get(applicationIndexTableName, get, rowMapper); + } + + @Override + public void deleteApplication(ApplicationId applicationId) { + Objects.requireNonNull(applicationId, "applicationName"); + + byte[] rowKey = applicationId.toBytes(); + Delete delete = new Delete(rowKey); + + TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); + hbaseOperations.delete(applicationIndexTableName, delete); + } + + @Override + public void deleteAgentIds(Map> applicationAgentIdMap) { + if (MapUtils.isEmpty(applicationAgentIdMap)) { + return; + } + + List deletes = new ArrayList<>(applicationAgentIdMap.size()); + + for (Map.Entry> entry : applicationAgentIdMap.entrySet()) { + ApplicationId applicationId = entry.getKey(); + List agentIds = entry.getValue(); + if (applicationId == null || CollectionUtils.isEmpty(agentIds)) { + continue; + } + Delete delete = new Delete(applicationId.toBytes()); + for (String agentId : agentIds) { + if (StringUtils.hasLength(agentId)) { + delete.addColumns(DESCRIPTOR.getName(), Bytes.toBytes(agentId)); + } + } + // don't delete if nothing has been specified except row + if (!delete.getFamilyCellMap().isEmpty()) { + deletes.add(delete); + } + } + + TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); + hbaseOperations.delete(applicationIndexTableName, deletes); + } + + @Override + public void deleteAgentId(ApplicationId applicationId, String agentId) { + Objects.requireNonNull(applicationId, "applicationId"); + Assert.hasLength(agentId, "agentId"); + + byte[] rowKey = applicationId.toBytes(); + Delete delete = new Delete(rowKey); + byte[] qualifier = Bytes.toBytes(agentId); + delete.addColumns(DESCRIPTOR.getName(), qualifier); + + TableName applicationIndexTableName = tableNameProvider.getTableName(DESCRIPTOR.getTable()); + hbaseOperations.delete(applicationIndexTableName, delete); + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationInfoDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationInfoDao.java new file mode 100644 index 000000000000..c8b57c160745 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationInfoDao.java @@ -0,0 +1,215 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.dao.hbase; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import com.navercorp.pinpoint.common.trace.ServiceType; +import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; +import com.navercorp.pinpoint.web.dao.ApplicationInfoDao; +import com.navercorp.pinpoint.web.vo.Application; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.CheckAndMutate; +import org.apache.hadoop.hbase.client.CheckAndMutateResult; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Repository +public class HbaseApplicationInfoDao implements ApplicationInfoDao { + private final Logger logger = LogManager.getLogger(this.getClass()); + + + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR_FORWARD = HbaseColumnFamily.APPLICATION_ID_FORWARD; + private static final HbaseColumnFamily.ApplicationId DESCRIPTOR_INVERSE = HbaseColumnFamily.APPLICATION_ID_INVERSE; + + private final HbaseOperations hbaseTemplate; + private final TableNameProvider tableNameProvider; + private final RowMapper forwardRowMapper; + private final RowMapper inverseRowMapper; + private final ServiceTypeRegistryService serviceTypeRegistryService; + + public HbaseApplicationInfoDao( + HbaseOperations hbaseTemplate, + TableNameProvider tableNameProvider, + @Qualifier("applicationIdForwardMapper") RowMapper forwardRowMapper, + @Qualifier("applicationIdInverseMapper") RowMapper inverseRowMapper, + ServiceTypeRegistryService serviceTypeRegistryService + ) { + this.hbaseTemplate = Objects.requireNonNull(hbaseTemplate, "hbaseTemplate"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.forwardRowMapper = Objects.requireNonNull(forwardRowMapper, "forwardRowMapper"); + this.inverseRowMapper = Objects.requireNonNull(inverseRowMapper, "inverseRowMapper"); + this.serviceTypeRegistryService = Objects.requireNonNull(serviceTypeRegistryService, "serviceTypeRegistryService"); + } + + @Override + public ApplicationId getApplicationId(ApplicationSelector selector) { + Objects.requireNonNull(selector, "selector"); + Objects.requireNonNull(selector.serviceId(), "selector.serviceId"); + Objects.requireNonNull(selector.name(), "selector.applicationName"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplicationId() serviceId: {}, applicationName: {}", selector.serviceId(), selector.name()); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = selector.toBytes(); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.inverseRowMapper); + } + + @Override + public Application getApplication(ApplicationId applicationId) { + Objects.requireNonNull(applicationId, "applicationId"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplication() applicationId:{}", applicationId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = applicationId.toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + ApplicationInfo info = hbaseTemplate.get(tableName, get, this.forwardRowMapper); + if (info == null) { + return null; + } + + return new Application(info.id(), info.name(), getServiceType(info.serviceTypeCode())); + } + + @Override + public List getApplications() { + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Scan scan = new Scan(); + scan.setCaching(30); + scan.addColumn(family, qualifier); + + List infos = hbaseTemplate.find(tableName, scan, this.forwardRowMapper); + return mapApplicationInfos(infos); + } + + @Override + public ApplicationId putApplicationIdIfAbsent(ApplicationInfo application) { + Objects.requireNonNull(application, "application"); + + if (logger.isDebugEnabled()) { + logger.debug("putApplicationIdIfAbsent() serviceId: {}, applicationName:{}, applicationId:{}", + application.serviceId(), application.name(), application.id()); + } + + CheckAndMutateResult camResult = putInverse(application); + if (camResult.isSuccess()) { + putForward(application); + } + + return getApplicationId(new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode())); + } + + @Override + public List getApplications(ServiceId serviceId) { + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("getApplications() serviceId:{}", serviceId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + + Scan scan = new Scan(); + scan.setStartStopRowForPrefixScan(serviceId.toBytes()); + + return hbaseTemplate.find(tableName, scan, this.inverseRowMapper); + } + + private CheckAndMutateResult putInverse(ApplicationInfo application) { + ApplicationSelector selector = new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode()); + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = selector.toBytes(); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + byte[] value = application.id().toBytes(); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + CheckAndMutate checkAndMutate = CheckAndMutate.newBuilder(rowKey) + .ifNotExists(family, qualifier) + .build(put); + + return hbaseTemplate.checkAndMutate(tableName, checkAndMutate); + } + + private void putForward(ApplicationInfo application) { + ApplicationSelector selector = new ApplicationSelector(application.serviceId(), application.name(), application.serviceTypeCode()); + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = application.id().toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + byte[] value = selector.toBytes(); + + Put put = new Put(rowKey); + put.addColumn(family, qualifier, value); + + hbaseTemplate.put(tableName, put); + } + + private List mapApplicationInfos(List infos) { + List applications = new ArrayList<>(infos.size()); + for (ApplicationInfo info : infos) { + applications.add(new Application(info.id(), info.name(), getServiceType(info.serviceTypeCode()))); + } + return applications; + } + + private ServiceType getServiceType(short serviceTypeCode) { + return this.serviceTypeRegistryService.findServiceType(serviceTypeCode); + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java index 959148e71838..2a278029159e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDao.java @@ -369,9 +369,7 @@ public boolean test(Dot dot) { } } if (this.dotStatus != null) { - if (!(this.dotStatus == dot.getStatus())) { - return false; - } + return this.dotStatus == dot.getStatus(); } return true; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDaoV2.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDaoV2.java new file mode 100644 index 000000000000..e28ad5356adc --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseApplicationTraceIndexDaoV2.java @@ -0,0 +1,396 @@ +/* + * Copyright 2019 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.dao.hbase; + +import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.LimitEventHandler; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.hbase.util.CellUtils; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.profiler.util.TransactionId; +import com.navercorp.pinpoint.common.server.bo.serializer.agent.ApplicationNameRowKeyEncoder; +import com.navercorp.pinpoint.common.server.scatter.FuzzyRowKeyBuilder; +import com.navercorp.pinpoint.common.server.util.DateTimeFormatUtils; +import com.navercorp.pinpoint.common.server.util.time.Range; +import com.navercorp.pinpoint.common.util.BytesUtils; +import com.navercorp.pinpoint.common.util.TimeUtils; +import com.navercorp.pinpoint.web.config.ScatterChartProperties; +import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDaoV2; +import com.navercorp.pinpoint.web.mapper.TraceIndexMetaScatterMapper; +import com.navercorp.pinpoint.web.mapper.TraceIndexScatterMapper; +import com.navercorp.pinpoint.web.mapper.TransactionIdMapper; +import com.navercorp.pinpoint.web.scatter.DragArea; +import com.navercorp.pinpoint.web.scatter.DragAreaQuery; +import com.navercorp.pinpoint.web.scatter.ElpasedTimeDotPredicate; +import com.navercorp.pinpoint.web.util.ListListUtils; +import com.navercorp.pinpoint.web.vo.LimitedScanResult; +import com.navercorp.pinpoint.web.vo.scatter.Dot; +import com.navercorp.pinpoint.web.vo.scatter.DotMetaData; +import com.sematext.hbase.wd.AbstractRowKeyDistributor; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellUtil; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.filter.Filter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +/** + * @author emeroad + * @author netspider + */ +@Repository +public class HbaseApplicationTraceIndexDaoV2 implements ApplicationTraceIndexDaoV2 { + + private static final int APPLICATION_TRACE_INDEX_NUM_PARTITIONS = 32; + + private final Logger logger = LogManager.getLogger(this.getClass()); + + private static final HbaseColumnFamily.ApplicationTraceIndexTrace INDEX = HbaseColumnFamily.APPLICATION_TRACE_INDEX_TRACE_VER2; + private static final HbaseColumnFamily.ApplicationTraceIndexTrace META = HbaseColumnFamily.APPLICATION_TRACE_INDEX_META_VER2; + + private final ScatterChartProperties scatterChartProperties; + + private final HbaseOperations hbaseOperations; + private final TableNameProvider tableNameProvider; + + private final FuzzyRowKeyBuilder fuzzyRowKeyBuilder = new FuzzyRowKeyBuilder(); + + private final RowMapper> traceIndexMapper; + + private final RowMapper> traceIndexScatterMapper; + + private final AbstractRowKeyDistributor traceIdRowKeyDistributor; + + private int scanCacheSize = 256; + + private final ApplicationNameRowKeyEncoder rowKeyEncoder = new ApplicationNameRowKeyEncoder(); + + public HbaseApplicationTraceIndexDaoV2(ScatterChartProperties scatterChartProperties, + HbaseOperations hbaseOperations, + TableNameProvider tableNameProvider, + @Qualifier("transactionIdMapper") RowMapper> traceIndexMapper, + @Qualifier("traceIndexScatterMapper") RowMapper> traceIndexScatterMapper, + @Qualifier("applicationTraceIndexDistributor") AbstractRowKeyDistributor traceIdRowKeyDistributor) { + this.scatterChartProperties = Objects.requireNonNull(scatterChartProperties, "scatterChartProperties"); + this.hbaseOperations = Objects.requireNonNull(hbaseOperations, "hbaseOperations"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.traceIndexMapper = Objects.requireNonNull(traceIndexMapper, "traceIndexMapper"); + this.traceIndexScatterMapper = Objects.requireNonNull(traceIndexScatterMapper, "traceIndexScatterMapper"); + this.traceIdRowKeyDistributor = Objects.requireNonNull(traceIdRowKeyDistributor, "traceIdRowKeyDistributor"); + } + + @SuppressWarnings("unused") // used by spring + public void setScanCacheSize(int scanCacheSize) { + this.scanCacheSize = scanCacheSize; + } + + @Override + public boolean hasTraceIndex(ApplicationId applicationId, Range range, boolean backwardDirection) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(range, "range"); + logger.debug("hasTraceIndex {}", range); + Scan scan = createScan(applicationId, range, backwardDirection, 1); + + LastRowAccessor lastRowAccessor = new LastRowAccessor(); + TableName applicationTraceIndexTableName = tableNameProvider.getTableName(INDEX.getTable()); + List> traceIndexList = hbaseOperations.findParallel(applicationTraceIndexTableName, + scan, traceIdRowKeyDistributor, 1, traceIndexMapper, lastRowAccessor, APPLICATION_TRACE_INDEX_NUM_PARTITIONS); + + List transactionIdSum = ListListUtils.toList(traceIndexList); + return !transactionIdSum.isEmpty(); + } + + @Override + public LimitedScanResult> scanTraceIndex(ApplicationId applicationId, Range range, int limit, boolean scanBackward) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(range, "range"); + if (limit < 0) { + throw new IllegalArgumentException("negative limit:" + limit); + } + logger.debug("scanTraceIndex {}", range); + Scan scan = createScan(applicationId, range, scanBackward, -1); + + LastRowAccessor lastRowAccessor = new LastRowAccessor(); + TableName applicationTraceIndexTableName = tableNameProvider.getTableName(INDEX.getTable()); + List> traceIndexList = hbaseOperations.findParallel(applicationTraceIndexTableName, + scan, traceIdRowKeyDistributor, limit, traceIndexMapper, lastRowAccessor, APPLICATION_TRACE_INDEX_NUM_PARTITIONS); + + List transactionIdSum = ListListUtils.toList(traceIndexList); + final long lastTime = getLastTime(range, limit, lastRowAccessor, transactionIdSum); + + return new LimitedScanResult<>(lastTime, transactionIdSum); + } + + private long getLastTime(Range range, int limit, LastRowAccessor lastRowAccessor, List list) { + if (list.size() >= limit) { + Long lastRowTimestamp = lastRowAccessor.getLastRowTimestamp(); + if (logger.isDebugEnabled()) { + logger.debug("lastRowTimestamp lastTime:{}", DateTimeFormatUtils.format(lastRowTimestamp)); + } + return lastRowTimestamp; + } else { + long from = range.getFrom(); + if (logger.isDebugEnabled()) { + logger.debug("scanner start lastTime:{}", DateTimeFormatUtils.format(from)); + } + return from; + } + } + + + private class LastRowAccessor implements LimitEventHandler { + private Long lastRowTimestamp = -1L; + private TransactionId lastTransactionId = null; + private int lastTransactionElapsed = -1; + + @Override + public void handleLastResult(Result lastResult) { + if (lastResult == null) { + return; + } + + final Cell last = CellUtils.lastCell(lastResult.rawCells(), HbaseColumnFamily.APPLICATION_TRACE_INDEX_TRACE.getName()); + byte[] row = CellUtil.cloneRow(last); + byte[] originalRow = traceIdRowKeyDistributor.getOriginalKey(row); + long reverseStartTime = BytesUtils.bytesToLong(originalRow, PinpointConstants.APPLICATION_NAME_MAX_LEN); + this.lastRowTimestamp = TimeUtils.recoveryTimeMillis(reverseStartTime); + + byte[] qualifier = CellUtil.cloneQualifier(last); + this.lastTransactionId = TransactionIdMapper.parseVarTransactionId(qualifier, 0, qualifier.length); + this.lastTransactionElapsed = BytesUtils.bytesToInt(qualifier, 0); + + if (logger.isDebugEnabled()) { + logger.debug("lastRowTimestamp={}, lastTransactionId={}, lastTransactionElapsed={}", DateTimeFormatUtils.format(lastRowTimestamp), lastTransactionId, lastTransactionElapsed); + } + } + + private Long getLastRowTimestamp() { + return lastRowTimestamp; + } + + public TransactionId getLastTransactionId() { + return lastTransactionId; + } + + public int getLastTransactionElapsed() { + return lastTransactionElapsed; + } + } + + + private Scan createScan(ApplicationId applicationId, Range range, boolean scanBackward, int limit) { + Scan scan = new Scan(); + scan.setCaching(this.scanCacheSize); + applyLimitForScan(scan, limit); + + byte[] traceIndexStartKey = rowKeyEncoder.encodeRowKey(applicationId.value(), range.getFrom()); + byte[] traceIndexEndKey = rowKeyEncoder.encodeRowKey(applicationId.value(), range.getTo()); + + if (scanBackward) { + // start key is replaced by end key because key has been reversed + scan.withStartRow(traceIndexEndKey); + scan.withStopRow(traceIndexStartKey); + } else { + scan.setReversed(true); + scan.withStartRow(traceIndexStartKey); + scan.withStopRow(traceIndexEndKey); + } + + scan.addFamily(INDEX.getName()); + scan.setId("ApplicationTraceIndexScan"); + + // toString() method of Scan converts a message to json format so it is slow for the first time. + logger.trace("create scan:{}", scan); + return scan; + } + + private void applyLimitForScan(Scan scan, int limit) { + if (limit == 1) { + scan.setOneRowLimit(); + } else if (limit > 1) { + scan.setLimit(limit); + } + } + + @Override + public LimitedScanResult> scanTraceScatterData(ApplicationId applicationId, Range range, int limit, boolean scanBackward) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(range, "range"); + if (limit < 0) { + throw new IllegalArgumentException("negative limit:" + limit); + } + logger.debug("scanTraceScatterDataMadeOfDotGroup"); + LastRowAccessor lastRowAccessor = new LastRowAccessor(); + + Scan scan = createScan(applicationId, range, scanBackward, -1); + + TableName applicationTraceIndexTableName = tableNameProvider.getTableName(INDEX.getTable()); + List> listList = hbaseOperations.findParallel(applicationTraceIndexTableName, scan, + traceIdRowKeyDistributor, limit, this.traceIndexScatterMapper, APPLICATION_TRACE_INDEX_NUM_PARTITIONS); + List dots = ListListUtils.toList(listList); + + final long lastTime = getLastTime(range, limit, lastRowAccessor, dots); + return new LimitedScanResult<>(lastTime, dots); + } + + @Override + public LimitedScanResult> scanTraceIndex(ApplicationId applicationId, DragArea dragArea, int limit) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(dragArea, "dragArea"); + + LastRowAccessor lastRowAccessor = new LastRowAccessor(); + + final Range range = Range.newUncheckedRange(dragArea.getXLow(), dragArea.getXHigh()); + logger.debug("scanTraceIndex range:{}", range); + final Scan scan = newFuzzyScanner(applicationId, dragArea, range); + + + // TODO +// Predicate filter = ElpasedTimeDotPredicate.newDragAreaDotPredicate(dragArea); + + final TableName applicationTraceIndexTableName = tableNameProvider.getTableName(INDEX.getTable()); + List> listList = this.hbaseOperations.findParallel(applicationTraceIndexTableName, + scan, traceIdRowKeyDistributor, limit, traceIndexMapper, lastRowAccessor, APPLICATION_TRACE_INDEX_NUM_PARTITIONS); + + List transactionIdSum = ListListUtils.toList(listList); + + final long lastTime = getLastTime(range, limit, lastRowAccessor, transactionIdSum); + + return new LimitedScanResult<>(lastTime, transactionIdSum); + } + + @Deprecated + @Override + public LimitedScanResult> scanScatterData(ApplicationId applicationId, DragAreaQuery dragAreaQuery, int limit) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(dragAreaQuery, "dragAreaQuery"); + + Predicate filter = buildDotPredicate(dragAreaQuery); + + RowMapper> mapper = new TraceIndexScatterMapper(filter); + + return scanScatterData0(applicationId, dragAreaQuery, limit, false, mapper); + } + + private Predicate buildDotPredicate(DragAreaQuery dragAreaQuery) { + DragArea dragArea = dragAreaQuery.getDragArea(); + Predicate filter = ElpasedTimeDotPredicate.newDragAreaDotPredicate(dragArea); + Predicate dotStatusPredicate = buildDotStatusFilter(dragAreaQuery); + if (dotStatusPredicate != null) { + filter = filter.and(dotStatusPredicate); + } + return filter; + } + + @Override + public LimitedScanResult> scanScatterDataV2(ApplicationId applicationId, DragAreaQuery dragAreaQuery, int limit) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(dragAreaQuery, "dragAreaQuery"); + + Predicate filter = buildDotPredicate(dragAreaQuery); + + RowMapper> mapper = new TraceIndexMetaScatterMapper(filter); + + return scanScatterData0(applicationId, dragAreaQuery, limit, true, mapper); + } + + private LimitedScanResult> scanScatterData0(ApplicationId applicationId, DragAreaQuery dragAreaQuery, int limit, + boolean metadataScan, RowMapper> mapper) { + Objects.requireNonNull(applicationId, "applicationId"); + Objects.requireNonNull(dragAreaQuery, "dragAreaQuery"); + + DragArea dragArea = dragAreaQuery.getDragArea(); + Range range = Range.newUncheckedRange(dragArea.getXLow(), dragArea.getXHigh()); + logger.debug("scanTraceScatterData-range:{}", range); + + LastRowAccessor lastRowAccessor = new LastRowAccessor(); + + Scan scan = newFuzzyScanner(applicationId, dragArea, range); + if (metadataScan) { + scan.addFamily(META.getName()); + } + + TableName applicationTraceIndexTableName = tableNameProvider.getTableName(INDEX.getTable()); + List> dotListList = hbaseOperations.findParallel(applicationTraceIndexTableName, scan, + traceIdRowKeyDistributor, limit, mapper, lastRowAccessor, APPLICATION_TRACE_INDEX_NUM_PARTITIONS); + List dots = ListListUtils.toList(dotListList); + + final long lastTime = getLastTime(range, limit, lastRowAccessor, dots); + + return new LimitedScanResult<>(lastTime, dots); + } + + private Predicate buildDotStatusFilter(DragAreaQuery dragAreaQuery) { + if (dragAreaQuery.getAgentId() != null || dragAreaQuery.getDotStatus() != null) { + return new DotStatusFilter(dragAreaQuery.getAgentId(), dragAreaQuery.getDotStatus()); + } + return null; + } + + static class DotStatusFilter implements Predicate { + // @Nullable + private final String agentId; + // @Nullable + private final Dot.Status dotStatus; + + public DotStatusFilter(String agentId, Dot.Status dotStatus) { + this.agentId = agentId; + this.dotStatus = dotStatus; + } + + @Override + public boolean test(Dot dot) { + if (agentId != null) { + if (!agentId.equals(dot.getAgentId())) { + return false; + } + } + if (this.dotStatus != null) { + return this.dotStatus == dot.getStatus(); + } + return true; + } + } + + private Scan newFuzzyScanner(ApplicationId applicationId, DragArea dragArea, Range range) { + final Scan scan = createScan(applicationId, range, true, -1); + if (scatterChartProperties.isEnableFuzzyRowFilter()) { + Filter filter = newFuzzyFilter(dragArea); + scan.setFilter(filter); + } + return scan; + } + + private Filter newFuzzyFilter(DragArea dragArea) { + long yHigh = dragArea.getYHigh(); + long yLow = dragArea.getYLow(); + return this.fuzzyRowKeyBuilder.build(yHigh, yLow); + } + + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java index ca4943200918..c421f2c7750a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseHostApplicationMapDao.java @@ -56,7 +56,6 @@ public class HbaseHostApplicationMapDao implements HostApplicationMapDao { private static final int HOST_APPLICATION_MAP_VER2_NUM_PARTITIONS = 4; private final Logger logger = LogManager.getLogger(this.getClass()); - private int scanCacheSize = 10; private final HbaseOperations hbaseOperations; @@ -109,15 +108,16 @@ private Scan createScan(Application parentApplication, Range range) { logger.debug("scan parentApplication:{}, range:{}", parentApplication, range); } - // TODO need common logic for creating scanner + // TODO: need common logic for creating scanner final long startTime = TimeUtils.reverseTimeMillis(timeSlot.getTimeSlot(range.getFrom())); final long endTime = TimeUtils.reverseTimeMillis(timeSlot.getTimeSlot(range.getTo()) + 1); + // start key is replaced by end key because timestamp has been reversed final byte[] startKey = createKey(parentApplication, endTime); final byte[] endKey = createKey(parentApplication, startTime); Scan scan = new Scan(); - scan.setCaching(this.scanCacheSize); + scan.setCaching(10); scan.withStartRow(startKey); scan.withStopRow(endKey); scan.setId("HostApplicationScan_Ver2"); @@ -127,7 +127,7 @@ private Scan createScan(Application parentApplication, Range range) { private byte[] createKey(Application parentApplication, long time) { Buffer buffer = new AutomaticBuffer(); - buffer.putPadString(parentApplication.getName(), HbaseTableConstants.APPLICATION_NAME_MAX_LEN); + buffer.putPadString(parentApplication.name(), HbaseTableConstants.APPLICATION_NAME_MAX_LEN); buffer.putShort(parentApplication.getServiceTypeCode()); buffer.putLong(time); return buffer.getBuffer(); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseServiceInfoDao.java b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseServiceInfoDao.java new file mode 100644 index 000000000000..cc7166f64d26 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/dao/hbase/HbaseServiceInfoDao.java @@ -0,0 +1,120 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.dao.hbase; + +import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; +import com.navercorp.pinpoint.common.hbase.HbaseOperations; +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import com.navercorp.pinpoint.common.util.BytesUtils; +import com.navercorp.pinpoint.web.dao.ServiceInfoDao; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Repository +public class HbaseServiceInfoDao implements ServiceInfoDao { + + private final Logger logger = LogManager.getLogger(this.getClass()); + + private static final HbaseColumnFamily.ServiceId DESCRIPTOR_FORWARD = HbaseColumnFamily.SERVICE_ID_FORWARD; + private static final HbaseColumnFamily.ServiceId DESCRIPTOR_INVERSE = HbaseColumnFamily.SERVICE_ID_INVERSE; + + private final HbaseOperations hbaseTemplate; + private final TableNameProvider tableNameProvider; + private final RowMapper forwardRowMapper; + private final RowMapper inverseRowMapper; + + public HbaseServiceInfoDao( + HbaseOperations hbaseTemplate, + TableNameProvider tableNameProvider, + @Qualifier("serviceIdForwardMapper") RowMapper forwardRowMapper, + @Qualifier("serviceIdInverseMapper") RowMapper inverseRowMapper + ) { + this.hbaseTemplate = Objects.requireNonNull(hbaseTemplate, "hbaseTemplate"); + this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); + this.forwardRowMapper = Objects.requireNonNull(forwardRowMapper, "forwardRowMapper"); + this.inverseRowMapper = Objects.requireNonNull(inverseRowMapper, "inverseRowMapper"); + } + + @Override + public ServiceId getServiceId(String serviceName) { + Objects.requireNonNull(serviceName, "serviceName"); + + if (logger.isDebugEnabled()) { + logger.debug("getServiceId() serviceName:{}", serviceName); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_INVERSE.getTable()); + byte[] rowKey = encodeStringAsRowKey(serviceName); + byte[] family = DESCRIPTOR_INVERSE.getName(); + byte[] qualifier = DESCRIPTOR_INVERSE.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.inverseRowMapper); + } + + @Override + public ServiceInfo getServiceInfo(ServiceId serviceId) { + Objects.requireNonNull(serviceId, "serviceId"); + + if (logger.isDebugEnabled()) { + logger.debug("getServiceInfo() serviceId:{}", serviceId); + } + + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] rowKey = serviceId.toBytes(); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Get get = new Get(rowKey); + get.addColumn(family, qualifier); + + return hbaseTemplate.get(tableName, get, this.forwardRowMapper); + } + + @Override + public List getServiceInfos() { + TableName tableName = this.tableNameProvider.getTableName(DESCRIPTOR_FORWARD.getTable()); + byte[] family = DESCRIPTOR_FORWARD.getName(); + byte[] qualifier = DESCRIPTOR_FORWARD.getName(); + + Scan scan = new Scan(); + scan.setCaching(30); + scan.addColumn(family, qualifier); + + return this.hbaseTemplate.find(tableName, scan, this.forwardRowMapper); + } + + private static byte[] encodeStringAsRowKey(String str) { + return BytesUtils.toBytes(str); + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/ApplicationFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/ApplicationFilter.java index 1564fa713ef4..b19d7acfb3ac 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/ApplicationFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/ApplicationFilter.java @@ -18,7 +18,6 @@ import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.trace.ServiceType; - import com.navercorp.pinpoint.common.util.StringUtils; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; import com.navercorp.pinpoint.web.filter.agent.AgentFilter; @@ -30,8 +29,8 @@ import com.navercorp.pinpoint.web.filter.responsetime.SpanResponseConditionFilter; import com.navercorp.pinpoint.web.filter.transaction.NodeContext; import com.navercorp.pinpoint.web.filter.transaction.SpanContext; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.List; import java.util.Objects; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java index 7a0bba7d3708..64bd4c7b3339 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/LinkFilter.java @@ -16,16 +16,12 @@ package com.navercorp.pinpoint.web.filter; -import java.util.List; -import java.util.Objects; - - import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanEventBo; +import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.util.StringUtils; import com.navercorp.pinpoint.loader.service.AnnotationKeyRegistryService; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; -import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.filter.agent.AgentFilter; import com.navercorp.pinpoint.web.filter.agent.AgentFilterFactory; import com.navercorp.pinpoint.web.filter.responsetime.DefaultExecutionTypeFilter; @@ -42,9 +38,11 @@ import com.navercorp.pinpoint.web.filter.transaction.WasToQueueFilter; import com.navercorp.pinpoint.web.filter.transaction.WasToUnknownFilter; import com.navercorp.pinpoint.web.filter.transaction.WasToWasFilter; - -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; +import java.util.Objects; /** * @author netspider diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/SpanContext.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/SpanContext.java index 195fb855e372..c3f3bdd25075 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/SpanContext.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/SpanContext.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.filter.transaction; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; @@ -44,9 +45,9 @@ public List findNode(String findApplicationName, List findS List findList = null; for (SpanBo span : nodeList) { final ServiceType applicationServiceType = serviceTypeRegistryService.findServiceType(span.getApplicationServiceType()); - if (findApplicationName.equals(span.getApplicationId()) && includeServiceType(findServiceCode, applicationServiceType)) { + if (findApplicationName.equals(span.getApplicationName()) && includeServiceType(findServiceCode, applicationServiceType)) { // apply preAgentFilter - if (agentFilter.accept(span.getAgentId())) { + if (agentFilter.accept(AgentId.unwrap(span.getAgentId()))) { if (findList == null) { findList = new ArrayList<>(); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java index 9c5ef00a4de1..db864384f8d7 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapper.java @@ -18,6 +18,7 @@ import com.navercorp.pinpoint.common.hbase.RowMapper; import com.navercorp.pinpoint.common.hbase.util.CellUtils; +import com.navercorp.pinpoint.common.util.BytesUtils; import com.navercorp.pinpoint.web.component.ApplicationFactory; import com.navercorp.pinpoint.web.vo.Application; import org.apache.hadoop.hbase.Cell; @@ -49,7 +50,7 @@ public List mapRow(Result result, int rowNum) throws Exception { return Collections.emptyList(); } Set uniqueTypeCodes = new HashSet<>(); - String applicationName = CellUtils.rowToString(result); + String applicationName = BytesUtils.toString(result.getRow()); Cell[] rawCells = result.rawCells(); for (Cell cell : rawCells) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapperV2.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapperV2.java new file mode 100644 index 000000000000..c95f996c726e --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/ApplicationNameMapperV2.java @@ -0,0 +1,68 @@ +/* + * Copyright 2014 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.navercorp.pinpoint.web.mapper; + +import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.hbase.util.CellUtils; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.util.UuidUtils; +import com.navercorp.pinpoint.web.component.ApplicationFactory; +import com.navercorp.pinpoint.web.vo.Application; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.client.Result; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * + */ +@Component +public class ApplicationNameMapperV2 implements RowMapper> { + + private final ApplicationFactory applicationFactory; + + public ApplicationNameMapperV2(ApplicationFactory applicationFactory) { + this.applicationFactory = Objects.requireNonNull(applicationFactory, "applicationFactory"); + } + + @Override + public List mapRow(Result result, int rowNum) throws Exception { + if (result.isEmpty()) { + return Collections.emptyList(); + } + Set uniqueTypeCodes = new HashSet<>(); + ApplicationId applicationId = ApplicationId.of(UuidUtils.fromBytes(result.getRow())); + + Cell[] rawCells = result.rawCells(); + for (Cell cell : rawCells) { + short serviceTypeCode = CellUtils.valueToShort(cell); + uniqueTypeCodes.add(serviceTypeCode); + } + List applicationList = new ArrayList<>(); + for (short serviceTypeCode : uniqueTypeCodes) { + final Application application = applicationFactory.createApplication(applicationId, null, serviceTypeCode); + applicationList.add(application); + } + return applicationList; + } +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/SpanMapperV2.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/SpanMapperV2.java index ac7daed30408..964df746e33a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/SpanMapperV2.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/SpanMapperV2.java @@ -25,6 +25,7 @@ import com.navercorp.pinpoint.common.buffer.StringCacheableBuffer; import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily; import com.navercorp.pinpoint.common.hbase.RowMapper; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.BasicSpan; import com.navercorp.pinpoint.common.server.bo.SpanBo; @@ -242,17 +243,17 @@ private boolean isChildSpanChunk(SpanBo spanBo, SpanChunkBo spanChunkBo) { if (spanBo.getAgentStartTime() != spanChunkBo.getAgentStartTime()) { return false; } - if (!StringUtils.equals(spanBo.getAgentId(), spanChunkBo.getAgentId())) { + if (!StringUtils.equals(AgentId.unwrap(spanBo.getAgentId()), AgentId.unwrap(spanChunkBo.getAgentId()))) { return false; } - if (!StringUtils.equals(spanBo.getApplicationId(), spanChunkBo.getApplicationId())) { + if (!StringUtils.equals(spanBo.getApplicationName(), spanChunkBo.getApplicationName())) { return false; } return true; } private AgentKey newAgentKey(BasicSpan basicSpan) { - return new AgentKey(basicSpan.getApplicationId(), basicSpan.getAgentId(), basicSpan.getAgentStartTime(), basicSpan.getSpanId()); + return new AgentKey(basicSpan.getApplicationName(), basicSpan.getAgentId().value(), basicSpan.getAgentStartTime(), basicSpan.getSpanId()); } private record AgentKey(String applicationId, String agentId, long agentStartTime, long spanId) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/realtime/AgentLookupServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/realtime/AgentLookupServiceImpl.java index 493bf1cfc0b2..c40316e51a98 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/realtime/AgentLookupServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/realtime/AgentLookupServiceImpl.java @@ -15,11 +15,13 @@ */ package com.navercorp.pinpoint.web.realtime; +import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.server.cluster.ClusterKey; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.web.realtime.service.AgentLookupService; import com.navercorp.pinpoint.web.service.AgentInfoService; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; +import com.navercorp.pinpoint.web.vo.agent.AgentInfoFilters; import com.navercorp.pinpoint.web.vo.agent.AgentStatusAndLink; import com.navercorp.pinpoint.web.vo.agent.AgentStatusFilters; import com.navercorp.pinpoint.web.vo.tree.AgentsMapByHost; @@ -36,6 +38,8 @@ */ class AgentLookupServiceImpl implements AgentLookupService { + private static final short DEFAULT_SERVICE_TYPE_CODE = PinpointConstants.DEFAULT_SERVICE_TYPE_CODE; + private final AgentInfoService agentInfoService; private final Duration recentness; @@ -50,7 +54,9 @@ public List getRecentAgents(String applicationName) { long from = now - recentness.toMillis(); return intoClusterKeyList(this.agentInfoService.getAgentsListByApplicationName( AgentStatusFilters.recentRunning(from), + AgentInfoFilters.acceptAll(), applicationName, + DEFAULT_SERVICE_TYPE_CODE, Range.between(from, now), SortByAgentInfo.Rules.AGENT_NAME_ASC )); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java index 347f7d3cabc2..d949a3f585e7 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminService.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.web.vo.Application; import java.util.List; @@ -30,20 +31,20 @@ public interface AdminService { int MIN_DURATION_DAYS_FOR_INACTIVITY = 30; String MIN_DURATION_DAYS_FOR_INACTIVITY_STR = "" + MIN_DURATION_DAYS_FOR_INACTIVITY; - void removeApplicationName(String applicationName); + void removeApplicationName(ApplicationId applicationId); - void removeAgentId(String applicationName, String agentId); + void removeAgentId(ApplicationId applicationId, String agentId); @Deprecated void removeInactiveAgents(int durationDays); @Deprecated - int removeInactiveAgentInApplication(String applicationName, int durationDays); + int removeInactiveAgentInApplication(ApplicationId applicationId, int durationDays); Map> getAgentIdMap(); Map> getDuplicateAgentIdMap(); - Map> getInactiveAgents(String applicationName, int durationDays); + Map> getInactiveAgents(ApplicationId applicationId, int durationDays); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java index 2bbdac4ff2c8..d18818055b9d 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AdminServiceImpl.java @@ -16,9 +16,10 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.util.CollectionUtils; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.vo.Application; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -42,23 +43,25 @@ public class AdminServiceImpl implements AdminService { private final Logger logger = LogManager.getLogger(this.getClass()); - private final ApplicationIndexDao applicationIndexDao; - + private final ApplicationService applicationService; private final AgentInfoService agentInfoService; - public AdminServiceImpl(ApplicationIndexDao applicationIndexDao, AgentInfoService agentInfoService) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + public AdminServiceImpl( + ApplicationService applicationService, + AgentInfoService agentInfoService + ) { + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.agentInfoService = Objects.requireNonNull(agentInfoService, "agentInfoService"); } @Override - public void removeApplicationName(String applicationName) { - applicationIndexDao.deleteApplicationName(applicationName); + public void removeApplicationName(ApplicationId applicationId) { + this.applicationService.deleteApplication(applicationId); } @Override - public void removeAgentId(String applicationName, String agentId) { - applicationIndexDao.deleteAgentId(applicationName, agentId); + public void removeAgentId(ApplicationId applicationId, String agentId) { + this.applicationService.deleteAgent(applicationId, agentId); } @Override @@ -68,37 +71,37 @@ public void removeInactiveAgents(int durationDays) { throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days"); } - List applicationNames = this.applicationIndexDao.selectAllApplicationNames() + List applicationIds = this.applicationService.getApplications() .stream() - .map(Application::getName) + .map(Application::id) .distinct() .collect(Collectors.toList()); - Collections.shuffle(applicationNames); + Collections.shuffle(applicationIds); int index = 1; - for (String applicationName: applicationNames) { - logger.info("Cleaning {} ({}/{})", applicationName, index++, applicationNames.size()); - removeInactiveAgentInApplication(applicationName, durationDays); + for (ApplicationId applicationId: applicationIds) { + logger.info("Cleaning {} ({}/{})", applicationId, index++, applicationIds.size()); + removeInactiveAgentInApplication(applicationId, durationDays); } } @Override - public int removeInactiveAgentInApplication(String applicationName, int durationDays) { + public int removeInactiveAgentInApplication(ApplicationId applicationId, int durationDays) { try { - return removeInactiveAgentInApplication0(applicationName, durationDays); + return removeInactiveAgentInApplication0(applicationId, durationDays); } catch (Exception e) { - logger.error("Backoff to remove inactive agents in application {}", applicationName, e); + logger.error("Backoff to remove inactive agents in application {}", applicationId, e); } return 0; } - private int removeInactiveAgentInApplication0(String applicationName, int durationDays) { + private int removeInactiveAgentInApplication0(ApplicationId applicationId, int durationDays) { final List agentsToDelete = new ArrayList<>(100); int deleteCount = 0; - final List agentIds = this.applicationIndexDao.selectAgentIds(applicationName); + final List agentIds = this.applicationService.getAgents(applicationId); for (String agentId: agentIds) { - if (!isInactiveAgent(agentId, durationDays)) { + if (!isInactiveAgent(AgentId.of(agentId), durationDays)) { continue; } @@ -106,27 +109,27 @@ private int removeInactiveAgentInApplication0(String applicationName, int durati deleteCount++; if (agentsToDelete.size() >= 100) { - logger.info("Delete {} of {}", agentsToDelete, applicationName); - applicationIndexDao.deleteAgentIds(Map.of(applicationName, agentsToDelete)); + logger.info("Delete {} of {}", agentsToDelete, applicationId); + this.applicationService.deleteAgents(Map.of(applicationId, agentsToDelete)); agentsToDelete.clear(); } } if (!agentsToDelete.isEmpty()) { - logger.info("Delete {} of {}", agentsToDelete, applicationName); - applicationIndexDao.deleteAgentIds(Map.of(applicationName, agentsToDelete)); + logger.info("Delete {} of {}", agentsToDelete, applicationId); + this.applicationService.deleteAgents(Map.of(applicationId, agentsToDelete)); } - logger.info("({}/{}) agents of {} had been cleaned up", deleteCount, agentIds.size(), applicationName); + logger.info("({}/{}) agents of {} had been cleaned up", deleteCount, agentIds.size(), applicationId); return deleteCount; } @Override public Map> getAgentIdMap() { Map> agentIdMap = new TreeMap<>(); - List applications = this.applicationIndexDao.selectAllApplicationNames(); + List applications = this.applicationService.getApplications(); for (Application application : applications) { - List agentIds = this.applicationIndexDao.selectAgentIds(application.getName()); + List agentIds = this.applicationService.getAgents(application.id()); for (String agentId : agentIds) { List applicationList = agentIdMap.computeIfAbsent(agentId, k -> new ArrayList<>()); applicationList.add(application); @@ -150,13 +153,14 @@ public Map> getDuplicateAgentIdMap() { } @Override - public Map> getInactiveAgents(String applicationName, int durationDays) { - Objects.requireNonNull(applicationName, "applicationName"); + public Map> getInactiveAgents(ApplicationId applicationId, int durationDays) { + Objects.requireNonNull(applicationId, "applicationId"); if (durationDays < MIN_DURATION_DAYS_FOR_INACTIVITY) { throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days"); } - List agentIds = this.applicationIndexDao.selectAgentIds(applicationName); + + List agentIds = this.applicationService.getAgents(applicationId); if (CollectionUtils.isEmpty(agentIds)) { return Collections.emptyMap(); } @@ -176,11 +180,11 @@ private List filterInactiveAgents(List agentIds, int durationDay } return agentIds.stream() - .filter(agentId -> isInactiveAgent(agentId, durationDays)) + .filter(agentId -> isInactiveAgent(AgentId.of(agentId), durationDays)) .collect(Collectors.toList()); } - private boolean isInactiveAgent(String agentId, int durationDays) { + private boolean isInactiveAgent(AgentId agentId, int durationDays) { long now = System.currentTimeMillis(); Range range = Range.between(now - TimeUnit.DAYS.toMillis(durationDays), now); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentIdStartTimeKey.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentIdStartTimeKey.java index 01f841d46dc0..67f18ae2ef55 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentIdStartTimeKey.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentIdStartTimeKey.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import java.util.Objects; @@ -13,6 +14,10 @@ public AgentIdStartTimeKey(String agentId, long agentStartTime) { this.agentStartTime = agentStartTime; } + public AgentIdStartTimeKey(AgentId agentId, long agentStartTime) { + this(agentId.value(), agentStartTime); + } + public String getAgentId() { return agentId; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java index 7e5c7c5a3c6b..57a7aefb2860 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoService.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.web.vo.agent.AgentAndStatus; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; @@ -48,14 +49,19 @@ public interface AgentInfoService { AgentsMapByApplication getAllAgentsStatisticsList(AgentStatusFilter filter, Range range); - AgentsMapByHost getAgentsListByApplicationName(AgentStatusFilter agentStatusFilter, AgentInfoFilter agentInfoPredicate, String applicationName, Range range, SortByAgentInfo.Rules sortBy); - AgentsMapByHost getAgentsListByApplicationName(AgentStatusFilter agentStatusFilter, String applicationName, Range range, SortByAgentInfo.Rules sortBy); + AgentsMapByHost getAgentsListByApplicationName( + AgentStatusFilter agentStatusFilter, + AgentInfoFilter agentInfoPredicate, + String applicationName, + short serviceTypeCode, + Range range, + SortByAgentInfo.Rules sortBy); ApplicationAgentHostList getApplicationAgentHostList(int offset, int limit, Period durationDays); - Set getAgentsByApplicationName(String applicationName, long timestamp); + Set getAgentsByApplicationName(String applicationName, short serviceTypeCode, long timestamp); - Set getAgentsByApplicationNameWithoutStatus(String applicationName, long timestamp); + Set getAgentsByApplicationNameWithoutStatus(String applicationName, short serviceTypeCode, long timestamp); AgentAndStatus getAgentInfo(String agentId, long timestamp); @@ -69,7 +75,7 @@ public interface AgentInfoService { List> getAgentStatus(AgentStatusQuery query); - boolean isActiveAgent(String agentId, Range range); + boolean isActiveAgent(AgentId agentId, Range range); InspectorTimeline getAgentStatusTimeline(String agentId, Range range, int... excludeAgentEventTypeCodes); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java index 38dc94b4ee52..c3bffd9b1a99 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentInfoServiceImpl.java @@ -17,13 +17,16 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; import com.navercorp.pinpoint.common.server.bo.stat.JvmGcBo; import com.navercorp.pinpoint.common.server.util.AgentEventType; import com.navercorp.pinpoint.common.server.util.time.DateTimeUtils; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.web.dao.AgentInfoDao; import com.navercorp.pinpoint.web.dao.AgentLifeCycleDao; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.dao.stat.AgentStatDao; import com.navercorp.pinpoint.web.filter.agent.AgentEventFilter; import com.navercorp.pinpoint.web.hyperlink.HyperLinkFactory; @@ -33,7 +36,6 @@ import com.navercorp.pinpoint.web.vo.agent.AgentAndStatus; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; import com.navercorp.pinpoint.web.vo.agent.AgentInfoFilter; -import com.navercorp.pinpoint.web.vo.agent.AgentInfoFilters; import com.navercorp.pinpoint.web.vo.agent.AgentStatus; import com.navercorp.pinpoint.web.vo.agent.AgentStatusAndLink; import com.navercorp.pinpoint.web.vo.agent.AgentStatusFilter; @@ -66,6 +68,8 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -82,28 +86,31 @@ public class AgentInfoServiceImpl implements AgentInfoService { private final AgentWarningStatService agentWarningStatService; - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; private final AgentInfoDao agentInfoDao; private final AgentLifeCycleDao agentLifeCycleDao; private final AgentStatDao jvmGcDao; + private final ApplicationInfoService applicationInfoService; private final HyperLinkFactory hyperLinkFactory; public AgentInfoServiceImpl(AgentEventService agentEventService, AgentWarningStatService agentWarningStatService, - ApplicationIndexDao applicationIndexDao, + ApplicationService applicationService, AgentInfoDao agentInfoDao, AgentLifeCycleDao agentLifeCycleDao, AgentStatDao jvmGcDao, + ApplicationInfoService applicationInfoService, HyperLinkFactory hyperLinkFactory) { this.agentEventService = Objects.requireNonNull(agentEventService, "agentEventService"); this.agentWarningStatService = Objects.requireNonNull(agentWarningStatService, "agentWarningStatService"); - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); this.agentInfoDao = Objects.requireNonNull(agentInfoDao, "agentInfoDao"); this.agentLifeCycleDao = Objects.requireNonNull(agentLifeCycleDao, "agentLifeCycleDao"); this.jvmGcDao = Objects.requireNonNull(jvmGcDao, "jvmGcDao"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); this.hyperLinkFactory = Objects.requireNonNull(hyperLinkFactory, "hyperLinkFactory"); } @@ -111,10 +118,10 @@ public AgentInfoServiceImpl(AgentEventService agentEventService, public AgentsMapByApplication getAllAgentsList(AgentStatusFilter filter, Range range) { Objects.requireNonNull(filter, "filter"); - List applications = applicationIndexDao.selectAllApplicationNames(); + List applications = applicationService.getApplications(); List agents = new ArrayList<>(); for (Application application : applications) { - agents.addAll(getAgentsByApplicationName(application.getName(), range.getTo())); + agents.addAll(getAgentsByApplicationName(application.name(), application.getServiceTypeCode(), range.getTo())); } return AgentsMapByApplication.newAgentAndStatusMap( @@ -127,10 +134,10 @@ public AgentsMapByApplication getAllAgentsList(AgentStatusFilter public AgentsMapByApplication getAllAgentsStatisticsList(AgentStatusFilter filter, Range range) { Objects.requireNonNull(filter, "filter"); - List applications = applicationIndexDao.selectAllApplicationNames(); + List applications = this.applicationService.getApplications(); List agents = new ArrayList<>(); for (Application application : applications) { - agents.addAll(getDetailedAgentsByApplicationName(application.getName(), range.getTo())); + agents.addAll(getDetailedAgentsByApplicationName(application.name(), application.getServiceTypeCode(), range.getTo())); } return AgentsMapByApplication.newDetailedAgentInfoMap( @@ -139,29 +146,22 @@ public AgentsMapByApplication getAllAgentsStatisticsList(Agen ); } - @Override - public AgentsMapByHost getAgentsListByApplicationName(AgentStatusFilter agentStatusFilter, - String applicationName, - Range range, - SortByAgentInfo.Rules sortBy) { - return getAgentsListByApplicationName(agentStatusFilter, AgentInfoFilters.acceptAll(), applicationName, range, sortBy); - } - @Override public AgentsMapByHost getAgentsListByApplicationName(AgentStatusFilter agentStatusFilter, AgentInfoFilter agentInfoPredicate, String applicationName, + short serviceTypeCode, Range range, SortByAgentInfo.Rules sortBy) { Objects.requireNonNull(agentStatusFilter, "agentStatusFilter"); Objects.requireNonNull(agentInfoPredicate, "agentInfoPredicate"); Objects.requireNonNull(applicationName, "applicationName"); - Set agentInfoAndStatuses = getAgentsByApplicationName(applicationName, range.getTo()); Predicate agentStatusFilter0 = agentStatusFilter.and(x -> isActiveAgent(x.getAgentId(), range)); + Set agentInfoAndStatuses = getAgentsByApplicationName(applicationName, serviceTypeCode, range.getTo()); if (agentInfoAndStatuses.isEmpty()) { - logger.warn("agent list is empty for application:{}", applicationName); + logger.warn("agent list is empty for application: {}", applicationName); } AgentsMapByHost agentsMapByHost = AgentsMapByHost.newAgentsMapByHost( @@ -189,22 +189,23 @@ public ApplicationAgentHostList getApplicationAgentHostList(int offset, int limi } private ApplicationAgentHostList getApplicationAgentHostList0(int offset, int limit, Period durationDays) { - List applicationNameList = getApplicationNameList(applicationIndexDao.selectAllApplicationNames()); - if (offset > applicationNameList.size()) { - ApplicationAgentHostList.Builder builder = newBuilder(offset, offset, applicationNameList.size()); + List applications0 = this.applicationService.getApplications(); + List applications = getSortedApplicationList(applications0); + if (offset > applications.size()) { + ApplicationAgentHostList.Builder builder = newBuilder(offset, offset, applications.size()); return builder.build(); } final long timeStamp = System.currentTimeMillis(); final int startIndex = offset - 1; - final int endIndex = Math.min(startIndex + limit, applicationNameList.size()); + final int endIndex = Math.min(startIndex + limit, applications.size()); - ApplicationAgentHostList.Builder builder = newBuilder(offset, endIndex, applicationNameList.size()); + ApplicationAgentHostList.Builder builder = newBuilder(offset, endIndex, applications.size()); for (int i = startIndex; i < endIndex; i++) { - String applicationName = applicationNameList.get(i); - - List agentIdList = getAgentIdList(applicationName, durationDays); + Application application = applications.get(i); + String applicationName = application.name(); + List agentIdList = getAgentIdList(application.id(), durationDays); List agentInfoList = this.agentInfoDao.getSimpleAgentInfos(agentIdList, timeStamp); builder.addAgentInfo(applicationName, agentInfoList); } @@ -215,8 +216,8 @@ private ApplicationAgentHostList.Builder newBuilder(int offset, int endIndex, in return ApplicationAgentHostList.newBuilder(offset, endIndex, totalApplications); } - private List getAgentIdList(String applicationName, Period durationDays) { - List agentIds = this.applicationIndexDao.selectAgentIds(applicationName); + private List getAgentIdList(ApplicationId applicationId, Period durationDays) { + List agentIds = this.applicationService.getAgents(applicationId); if (CollectionUtils.isEmpty(agentIds)) { return Collections.emptyList(); } @@ -237,13 +238,13 @@ private List getAgentIdList(String applicationName, Period durationDays) // FIXME This needs to be done with a more accurate information. // If at any time a non-java agent is introduced, or an agent that does not collect jvm data, // this will fail - boolean dataExists = isActiveAgent(agentId, fastRange); + boolean dataExists = isActiveAgent(AgentId.of(agentId), fastRange); if (dataExists) { activeAgentIdList.add(agentId); continue; } - dataExists = isActiveAgent(agentId, queryRange); + dataExists = isActiveAgent(AgentId.of(agentId), queryRange); if (dataExists) { activeAgentIdList.add(agentId); } @@ -251,17 +252,17 @@ private List getAgentIdList(String applicationName, Period durationDays) return activeAgentIdList; } - private List getApplicationNameList(List applications) { + private List getSortedApplicationList(List applications) { return applications.stream() - .map(Application::getName) - .distinct() - .sorted(Comparator.naturalOrder()) + .sorted(Comparator.comparing(Application::name)) .collect(Collectors.toList()); } @Override - public Set getAgentsByApplicationName(String applicationName, long timestamp) { - List agentInfos = this.getAgentsByApplicationNameWithoutStatus0(applicationName, timestamp); + public Set getAgentsByApplicationName(String applicationName, short serviceTypeCode, long timestamp) { + ApplicationId applicationId = this.applicationInfoService.getApplicationId( + new ApplicationSelector(ServiceId.DEFAULT_ID, applicationName, serviceTypeCode)); + List agentInfos = this.getAgentsByApplicationNameWithoutStatus0(applicationId, timestamp); List result = new ArrayList<>(agentInfos.size()); @@ -278,28 +279,28 @@ public Set getAgentsByApplicationName(String applicationName, lo @Override - public Set getAgentsByApplicationNameWithoutStatus(String applicationName, long timestamp) { - List agentInfos = getAgentsByApplicationNameWithoutStatus0(applicationName, timestamp); + public Set getAgentsByApplicationNameWithoutStatus(String applicationName, short serviceTypeCode, long timestamp) { + ApplicationId applicationId = this.applicationInfoService.getApplicationId(new ApplicationSelector(ServiceId.DEFAULT_ID, applicationName, serviceTypeCode)); + List agentInfos = getAgentsByApplicationNameWithoutStatus0(applicationId, timestamp); return new HashSet<>(agentInfos); } - public List getAgentsByApplicationNameWithoutStatus0(String applicationName, long timestamp) { - Objects.requireNonNull(applicationName, "applicationName"); + public List getAgentsByApplicationNameWithoutStatus0(ApplicationId applicationId, long timestamp) { + Objects.requireNonNull(applicationId, "applicationId"); if (timestamp < 0) { throw new IllegalArgumentException("timestamp must not be less than 0"); } - List agentIds = this.applicationIndexDao.selectAgentIds(applicationName); + List agentIds = this.applicationService.getAgents(applicationId); List agentInfos = this.agentInfoDao.getSimpleAgentInfos(agentIds, timestamp); return agentInfos.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); - } - public Set getDetailedAgentsByApplicationName(String applicationName, long timestamp) { - List agentInfos = this.getDetailedAgentsByApplicationNameWithoutStatus0(applicationName, timestamp); + public Set getDetailedAgentsByApplicationName(String applicationName, short serviceTypeCode, long timestamp) { + List agentInfos = this.getDetailedAgentsByApplicationNameWithoutStatus0(applicationName, serviceTypeCode, timestamp); List result = new ArrayList<>(agentInfos.size()); @@ -315,13 +316,14 @@ public Set getDetailedAgentsByApplicationName(String app return new HashSet<>(result); } - public List getDetailedAgentsByApplicationNameWithoutStatus0(String applicationName, long timestamp) { + public List getDetailedAgentsByApplicationNameWithoutStatus0(String applicationName, short serviceTypeCode, long timestamp) { Objects.requireNonNull(applicationName, "applicationName"); if (timestamp < 0) { throw new IllegalArgumentException("timestamp must not be less than 0"); } - List agentIds = this.applicationIndexDao.selectAgentIds(applicationName); + ApplicationId applicationId = this.applicationInfoService.getApplicationId(new ApplicationSelector(ServiceId.DEFAULT_ID, applicationName, serviceTypeCode)); + List agentIds = this.applicationService.getAgents(applicationId); List agentInfos = this.agentInfoDao.getDetailedAgentInfos(agentIds, timestamp, false, true); return agentInfos.stream() @@ -396,18 +398,18 @@ public List> getAgentStatus(AgentStatusQuery query) { } @Override - public boolean isActiveAgent(String agentId, Range range) { + public boolean isActiveAgent(AgentId agentId, Range range) { Objects.requireNonNull(agentId, "agentId"); return isActiveAgentByGcStat(agentId, range) || isActiveAgentByPing(agentId, range); } - private boolean isActiveAgentByGcStat(String agentId, Range range) { - return this.jvmGcDao.agentStatExists(agentId, range); + private boolean isActiveAgentByGcStat(AgentId agentId, Range range) { + return this.jvmGcDao.agentStatExists(agentId.value(), range); } - private boolean isActiveAgentByPing(String agentId, Range range) { - return this.agentEventService.getAgentEvents(agentId, range) + private boolean isActiveAgentByPing(AgentId agentId, Range range) { + return this.agentEventService.getAgentEvents(agentId.value(), range) .stream() .anyMatch(e -> e.getEventTypeCode() == AgentEventType.AGENT_PING.getCode()); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java index 281376114b35..4bd8829799b5 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AgentServiceImpl.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.server.cluster.ClusterKey; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; import org.springframework.stereotype.Service; @@ -30,6 +31,8 @@ @Service public class AgentServiceImpl implements AgentService { + private static final short DEFAULT_SERVICE_TYPE_CODE = PinpointConstants.DEFAULT_SERVICE_TYPE_CODE; + private final AgentInfoService agentInfoService; public AgentServiceImpl(AgentInfoService agentInfoService) { @@ -40,7 +43,7 @@ public AgentServiceImpl(AgentInfoService agentInfoService) { public ClusterKey getClusterKey(String applicationName, String agentId) { long currentTime = System.currentTimeMillis(); - Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(applicationName, currentTime); + Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(applicationName, DEFAULT_SERVICE_TYPE_CODE, currentTime); for (AgentInfo agentInfo : agentInfos) { if (agentInfo == null) { continue; @@ -48,7 +51,7 @@ public ClusterKey getClusterKey(String applicationName, String agentId) { if (!agentInfo.getApplicationName().equals(applicationName)) { continue; } - if (!agentInfo.getAgentId().equals(agentId)) { + if (!agentInfo.getAgentId().value().equals(agentId)) { continue; } @@ -68,7 +71,7 @@ public ClusterKey getClusterKey(String applicationName, String agentId, long sta if (checkDB) { long currentTime = System.currentTimeMillis(); - Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(applicationName, currentTime); + Set agentInfos = agentInfoService.getAgentsByApplicationNameWithoutStatus(applicationName, DEFAULT_SERVICE_TYPE_CODE, currentTime); for (AgentInfo agentInfo : agentInfos) { if (agentInfo == null) { continue; @@ -76,7 +79,7 @@ public ClusterKey getClusterKey(String applicationName, String agentId, long sta if (!agentInfo.getApplicationName().equals(applicationName)) { continue; } - if (!agentInfo.getAgentId().equals(agentId)) { + if (!agentInfo.getAgentId().value().equals(agentId)) { continue; } if (agentInfo.getStartTimestamp() != startTimeStamp) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/AlarmServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/AlarmServiceImpl.java index 8d2a3f620303..6ad90263cf0e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/AlarmServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/AlarmServiceImpl.java @@ -15,7 +15,7 @@ */ package com.navercorp.pinpoint.web.service; -import com.navercorp.pinpoint.common.server.alram.event.DeleteRuleEvent; +import com.navercorp.pinpoint.common.server.alarm.event.DeleteRuleEvent; import com.navercorp.pinpoint.web.alarm.vo.Rule; import com.navercorp.pinpoint.web.dao.AlarmDao; import com.navercorp.pinpoint.web.vo.UserGroup; @@ -66,11 +66,11 @@ public List selectRuleByUserGroupId(String userGroupId) { @Override @Transactional(readOnly = true) - public List selectRuleByApplicationId(String applicationId) { - List rules = alarmDao.selectRuleByApplicationId(applicationId); + public List selectRuleByApplicationId(String applicationName) { + List rules = alarmDao.selectRuleByApplicationId(applicationName); List result = new ArrayList<>(rules.size()); for (Rule rule : rules) { - if (rule.getApplicationId().equals(applicationId)) { + if (rule.getApplicationName().equals(applicationName)) { result.add(rule); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImpl.java index 976f78d59ef3..52e94f07e0c7 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImpl.java @@ -36,7 +36,7 @@ public ApdexScoreServiceImpl(MapResponseDao mapResponseDao) { @Override public ApdexScore selectApdexScoreData(Application application, Range range) { - ServiceType applicationServiceType = application.getServiceType(); + ServiceType applicationServiceType = application.serviceType(); if (applicationServiceType.isWas()) { List responseTimeList = mapResponseDao.selectResponseTime(application, range); @@ -51,7 +51,7 @@ public ApdexScore selectApdexScoreData(Application application, Range range) { @Override public ApdexScore selectApdexScoreData(Application application, String agentId, Range range) { - ServiceType applicationServiceType = application.getServiceType(); + ServiceType applicationServiceType = application.serviceType(); if (applicationServiceType.isWas()) { List responseTimeList = mapResponseDao.selectResponseTime(application, range); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationInfoService.java new file mode 100644 index 000000000000..d63a00c4075e --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationInfoService.java @@ -0,0 +1,59 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.service; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.server.bo.ApplicationInfo; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import com.navercorp.pinpoint.common.util.UuidUtils; +import com.navercorp.pinpoint.web.dao.ApplicationInfoDao; +import com.navercorp.pinpoint.web.vo.Application; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Component +public class ApplicationInfoService { + + private final ApplicationInfoDao applicationInfoDao; + + public ApplicationInfoService(ApplicationInfoDao applicationInfoDao) { + this.applicationInfoDao = Objects.requireNonNull(applicationInfoDao, "applicationInfoDao"); + } + + @Cacheable(value = "applicationById", key = "#applicationId") + public Application getApplication(ApplicationId applicationId) { + return this.applicationInfoDao.getApplication(applicationId); + } + + @Cacheable(value = "applicationIdBySelector", key = "#application") + public ApplicationId getApplicationId(ApplicationSelector application) { + ApplicationId applicationId = this.applicationInfoDao.getApplicationId(application); + if (applicationId != null) { + return applicationId; + } + + ApplicationId newApplicationId = ApplicationId.of(UuidUtils.createV4()); + ApplicationInfo newApplication = new ApplicationInfo(newApplicationId, application.serviceId(), + application.name(), application.serviceTypeCode()); + return this.applicationInfoDao.putApplicationIdIfAbsent(newApplication); + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationService.java index 8c5e7204d7b3..633595fc66ba 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationService.java @@ -16,14 +16,32 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.web.vo.Application; import org.springframework.stereotype.Service; +import java.util.List; +import java.util.Map; + /** * @author Taejin Koo */ @Service public interface ApplicationService { - boolean isExistApplicationName(String applicationName); + boolean isExistApplicationName(ApplicationId applicationId); + + List getApplications(ServiceId serviceId); + + List getApplications(); + + List getAgents(ApplicationId applicationId); + + void deleteApplication(ApplicationId applicationId); + + void deleteAgents(Map> applicationAgentIdMap); + + void deleteAgent(ApplicationId applicationId, String agentId); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationServiceImpl.java index 3464f1da0517..2c55d89df68b 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationServiceImpl.java @@ -16,11 +16,18 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; +import com.navercorp.pinpoint.web.dao.ApplicationIndexDaoV2; import com.navercorp.pinpoint.web.vo.Application; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; /** @@ -30,25 +37,127 @@ public class ApplicationServiceImpl implements ApplicationService { private final ApplicationIndexDao applicationIndexDao; + private final ApplicationIndexDaoV2 applicationIndexDaoV2; + private final ApplicationInfoService applicationInfoService; + private final ServiceInfoService serviceInfoService; - public ApplicationServiceImpl(ApplicationIndexDao applicationIndexDao) { + public ApplicationServiceImpl( + ApplicationIndexDao applicationIndexDao, + ApplicationIndexDaoV2 applicationIndexDaoV2, + ApplicationInfoService applicationInfoService, + ServiceInfoService serviceInfoService + ) { this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + this.applicationIndexDaoV2 = Objects.requireNonNull(applicationIndexDaoV2, "applicationIndexDaoV2"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); + this.serviceInfoService = Objects.requireNonNull(serviceInfoService, "serviceInfoService"); } @Override - public boolean isExistApplicationName(String applicationName) { - if (applicationName == null) { - return false; + public boolean isExistApplicationName(ApplicationId applicationId) { + String applicationName = this.applicationInfoService.getApplication(applicationId).name(); + List applicationsV2 = this.applicationIndexDaoV2.selectApplicationName(applicationId); + List applications = this.applicationIndexDao.selectApplicationByName(applicationName); + return applicationsV2.size() > 0 || applications.size() > 0; + } + @Override + public List getApplications() { + List applications1Origin = this.applicationIndexDao.selectAllApplications(); + List applications1 = augmentApplicationId(applications1Origin); + + List applications2Origin = applicationIndexDaoV2.selectAllApplications(); + List applications2 = augmentApplicationName(applications2Origin); + + List applications = new ArrayList<>(applications1.size() + applications2.size()); + applications.addAll(applications1); + applications.addAll(applications2); + + return applications.stream() + .distinct() + .toList(); + } + + @Override + public List getApplications(ServiceId serviceId) { + List applications = new ArrayList<>(); + if (serviceId.equals(ServiceId.DEFAULT_ID)) { + List legacyApplications = this.applicationIndexDao.selectAllApplications(); + applications.addAll(augmentApplicationId(legacyApplications)); + } + List applicationIds = this.serviceInfoService.getApplicationIds(serviceId); + for (ApplicationId applicationId : applicationIds) { + Application application = this.applicationInfoService.getApplication(applicationId); + if (application != null) { + applications.add(application); + } + } + return applications.stream().distinct().toList(); + } + + @Override + public List getAgents(ApplicationId applicationId) { + Application application = this.applicationInfoService.getApplication(applicationId); + + List agents1 = this.applicationIndexDao.selectAgentIds(application.name()); + List agents2 = this.applicationIndexDaoV2.selectAgentIds(applicationId); + + List agents = new ArrayList<>(agents1.size() + agents2.size()); + agents.addAll(agents1); + agents.addAll(agents2); + + return agents.stream() + .distinct() + .toList(); + } + + @Override + public void deleteApplication(ApplicationId applicationId) { + Application application = this.applicationInfoService.getApplication(applicationId); + this.applicationIndexDao.deleteApplicationName(application.name()); + this.applicationIndexDaoV2.deleteApplication(applicationId); + } + + @Override + public void deleteAgents(Map> applicationAgentIdMap) { + Map> applicationAgentIdMap2 = new HashMap<>(); + for (Map.Entry> entry : applicationAgentIdMap.entrySet()) { + ApplicationId applicationId = entry.getKey(); + Application application = this.applicationInfoService.getApplication(applicationId); + applicationAgentIdMap2.put(application.name(), entry.getValue()); } - List applications = applicationIndexDao.selectApplicationName(applicationName); + this.applicationIndexDao.deleteAgentIds(applicationAgentIdMap2); + this.applicationIndexDaoV2.deleteAgentIds(applicationAgentIdMap); + } + + @Override + public void deleteAgent(ApplicationId applicationId, String agentId) { + Application application = this.applicationInfoService.getApplication(applicationId); + + this.applicationIndexDao.deleteAgentId(application.name(), agentId); + this.applicationIndexDaoV2.deleteAgentId(applicationId, agentId); + } + + private List augmentApplicationName(List applications) { + List result = new ArrayList<>(applications.size()); for (Application application : applications) { - if (applicationName.equals(application.getName())) { - return true; + Application helper = this.applicationInfoService.getApplication(application.id()); + if (helper != null) { + result.add(new Application(helper.id(), helper.name(), helper.serviceType())); } } + return result; + } - return false; + private List augmentApplicationId(List applications) { + List result = new ArrayList<>(applications.size()); + for (Application application : applications) { + ApplicationSelector appSelector = new ApplicationSelector( + ServiceId.DEFAULT_ID, application.name(), application.getServiceTypeCode()); + ApplicationId applicationId = this.applicationInfoService.getApplicationId(appSelector); + result.add(new Application(applicationId, application.name(), application.serviceType())); + } + return result; } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexService.java new file mode 100644 index 000000000000..3a8fcb48899f --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexService.java @@ -0,0 +1,46 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.service; + +import com.navercorp.pinpoint.common.profiler.util.TransactionId; +import com.navercorp.pinpoint.common.server.util.time.Range; +import com.navercorp.pinpoint.web.scatter.DragArea; +import com.navercorp.pinpoint.web.scatter.DragAreaQuery; +import com.navercorp.pinpoint.web.vo.LimitedScanResult; +import com.navercorp.pinpoint.web.vo.scatter.Dot; +import com.navercorp.pinpoint.web.vo.scatter.DotMetaData; + +import java.util.List; + +/** + * @author youngjin.kim2 + */ +public interface ApplicationTraceIndexService { + boolean hasTraceIndex(String applicationName, Range range, boolean backwardDirection); + + LimitedScanResult> scanTraceIndex(String applicationName, Range range, int limit, boolean backwardDirection); + + LimitedScanResult> scanTraceScatterData(String applicationName, Range range, int limit, boolean scanBackward); + + + LimitedScanResult> scanTraceIndex(String applicationName, DragArea dragArea, int limit); + + @Deprecated + LimitedScanResult> scanScatterData(String applicationName, DragAreaQuery dragAreaQuery, int limit); + + LimitedScanResult> scanScatterDataV2(String applicationName, DragAreaQuery dragAreaQuery, int limit); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexServiceImpl.java new file mode 100644 index 000000000000..31afcb4f30a2 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ApplicationTraceIndexServiceImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.service; + +import com.navercorp.pinpoint.common.PinpointConstants; +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.profiler.util.TransactionId; +import com.navercorp.pinpoint.common.server.bo.ApplicationSelector; +import com.navercorp.pinpoint.common.server.util.time.Range; +import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; +import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDaoV2; +import com.navercorp.pinpoint.web.scatter.DragArea; +import com.navercorp.pinpoint.web.scatter.DragAreaQuery; +import com.navercorp.pinpoint.web.vo.LimitedScanResult; +import com.navercorp.pinpoint.web.vo.scatter.Dot; +import com.navercorp.pinpoint.web.vo.scatter.DotMetaData; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Component +public class ApplicationTraceIndexServiceImpl implements ApplicationTraceIndexService { + + private static final short DEFAULT_SERVICE_TYPE_CODE = PinpointConstants.DEFAULT_SERVICE_TYPE_CODE; + + private final ApplicationTraceIndexDao applicationTraceIndexDao; + private final ApplicationTraceIndexDaoV2 applicationTraceIndexDaoV2; + private final ApplicationInfoService applicationInfoService; + + public ApplicationTraceIndexServiceImpl( + ApplicationTraceIndexDao applicationTraceIndexDao, + ApplicationTraceIndexDaoV2 applicationTraceIndexDaoV2, + ApplicationInfoService applicationInfoService + ) { + this.applicationTraceIndexDao = Objects.requireNonNull(applicationTraceIndexDao, "applicationTraceIndexDao"); + this.applicationTraceIndexDaoV2 = Objects.requireNonNull(applicationTraceIndexDaoV2, "applicationTraceIndexDaoV2"); + this.applicationInfoService = Objects.requireNonNull(applicationInfoService, "applicationInfoService"); + } + + @Override + public boolean hasTraceIndex(String applicationName, Range range, boolean backwardDirection) { + ApplicationId applicationId = getApplicationId(applicationName); + return applicationTraceIndexDao.hasTraceIndex(applicationName, range, backwardDirection) || applicationTraceIndexDaoV2.hasTraceIndex(applicationId, range, backwardDirection); + } + + @Override + public LimitedScanResult> scanTraceIndex(String applicationName, Range range, int limit, boolean backwardDirection) { + ApplicationId applicationId = getApplicationId(applicationName); + LimitedScanResult> r1 = applicationTraceIndexDao.scanTraceIndex(applicationName, range, limit, backwardDirection); + LimitedScanResult> r2 = applicationTraceIndexDaoV2.scanTraceIndex(applicationId, range, limit, backwardDirection); + return merge(r1, r2); + } + + @Override + public LimitedScanResult> scanTraceScatterData(String applicationName, Range range, int limit, boolean scanBackward) { + ApplicationId applicationId = getApplicationId(applicationName); + LimitedScanResult> r1 = applicationTraceIndexDao.scanTraceScatterData(applicationName, range, limit, scanBackward); + LimitedScanResult> r2 = applicationTraceIndexDaoV2.scanTraceScatterData(applicationId, range, limit, scanBackward); + return merge(r1, r2); + } + + @Override + public LimitedScanResult> scanTraceIndex(String applicationName, DragArea dragArea, int limit) { + ApplicationId applicationId = getApplicationId(applicationName); + LimitedScanResult> r1 = applicationTraceIndexDao.scanTraceIndex(applicationName, dragArea, limit); + LimitedScanResult> r2 = applicationTraceIndexDaoV2.scanTraceIndex(applicationId, dragArea, limit); + return merge(r1, r2); + } + + @Override + public LimitedScanResult> scanScatterData(String applicationName, DragAreaQuery dragAreaQuery, int limit) { + ApplicationId applicationId = getApplicationId(applicationName); + LimitedScanResult> r1 = applicationTraceIndexDao.scanScatterData(applicationName, dragAreaQuery, limit); + LimitedScanResult> r2 = applicationTraceIndexDaoV2.scanScatterData(applicationId, dragAreaQuery, limit); + return merge(r1, r2); + } + + @Override + public LimitedScanResult> scanScatterDataV2(String applicationName, DragAreaQuery dragAreaQuery, int limit) { + ApplicationId applicationId = getApplicationId(applicationName); + LimitedScanResult> r1 = applicationTraceIndexDao.scanScatterDataV2(applicationName, dragAreaQuery, limit); + LimitedScanResult> r2 = applicationTraceIndexDaoV2.scanScatterDataV2(applicationId, dragAreaQuery, limit); + return merge(r1, r2); + } + + private ApplicationId getApplicationId(String applicationName) { + return applicationInfoService.getApplicationId(new ApplicationSelector(ServiceId.DEFAULT_ID, applicationName, DEFAULT_SERVICE_TYPE_CODE)); + } + + private LimitedScanResult> merge(LimitedScanResult> r1, LimitedScanResult> r2) { + long limitedTime = Math.max(r1.limitedTime(), r2.limitedTime()); + List scanData = mergeList(r1.scanData(), r2.scanData()); + return new LimitedScanResult<>(limitedTime, scanData); + } + + private List mergeList(List l1, List l2) { + List result = new ArrayList<>(l1.size() + l2.size()); + result.addAll(l1); + result.addAll(l2); + return result; + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonService.java index 0b32080bee3b..ea20cd74b57c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonService.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonService.java @@ -16,10 +16,10 @@ package com.navercorp.pinpoint.web.service; -import java.util.List; - import com.navercorp.pinpoint.web.vo.Application; +import java.util.List; + /** * @author netspider */ diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java index c6925c457cc2..90206d442b25 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/CommonServiceImpl.java @@ -16,13 +16,12 @@ package com.navercorp.pinpoint.web.service; -import java.util.List; -import java.util.Objects; - +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.web.vo.Application; import org.springframework.stereotype.Service; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; -import com.navercorp.pinpoint.web.vo.Application; +import java.util.List; +import java.util.Objects; /** * @author netspider @@ -31,15 +30,15 @@ @Service public class CommonServiceImpl implements CommonService { - private final ApplicationIndexDao applicationIndexDao; + private final ApplicationService applicationService; - public CommonServiceImpl(ApplicationIndexDao applicationIndexDao) { - this.applicationIndexDao = Objects.requireNonNull(applicationIndexDao, "applicationIndexDao"); + public CommonServiceImpl(ApplicationService applicationService) { + this.applicationService = Objects.requireNonNull(applicationService, "applicationService"); } @Override public List selectAllApplicationNames() { - return applicationIndexDao.selectAllApplicationNames(); + return applicationService.getApplications(ServiceId.DEFAULT_ID); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/DotExtractor.java b/web/src/main/java/com/navercorp/pinpoint/web/service/DotExtractor.java index 42fd19de04d7..29e34164a51e 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/DotExtractor.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/DotExtractor.java @@ -60,12 +60,11 @@ public Dot newDot(SpanBo span) { Objects.requireNonNull(span, "span"); final TransactionId transactionId = span.getTransactionId(); - return new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId()); + return new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId().value()); } private List getDotList(Application spanApplication) { - List dotList = this.dotMap.computeIfAbsent(spanApplication, k -> new ArrayList<>()); - return dotList; + return this.dotMap.computeIfAbsent(spanApplication, k -> new ArrayList<>()); } public List getApplicationScatterScanResult(long from, long to) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/HeatMapServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/HeatMapServiceImpl.java index 35cc9ac38791..a0081db70f09 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/HeatMapServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/HeatMapServiceImpl.java @@ -4,7 +4,6 @@ import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.util.CollectionUtils; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; import com.navercorp.pinpoint.web.dao.TraceDao; import com.navercorp.pinpoint.web.scatter.DragAreaQuery; import com.navercorp.pinpoint.web.scatter.heatmap.HeatMap; @@ -33,15 +32,15 @@ public class HeatMapServiceImpl implements HeatMapService { private final Logger logger = LogManager.getLogger(this.getClass()); - private final ApplicationTraceIndexDao applicationTraceIndexDao; + private final ApplicationTraceIndexService applicationTraceIndexService; private final TraceDao traceDao; private final SpanService spanService; - public HeatMapServiceImpl(ApplicationTraceIndexDao applicationTraceIndexDao, + public HeatMapServiceImpl(ApplicationTraceIndexService applicationTraceIndexService, SpanService spanService, TraceDao traceDao) { - this.applicationTraceIndexDao = Objects.requireNonNull(applicationTraceIndexDao, "applicationTraceIndexDao"); + this.applicationTraceIndexService = Objects.requireNonNull(applicationTraceIndexService, "applicationTraceIndexService"); this.spanService = Objects.requireNonNull(spanService, "spanService"); this.traceDao = Objects.requireNonNull(traceDao, "traceDao"); } @@ -52,7 +51,7 @@ public LimitedScanResult> dragScatterData(String applicationName, D Objects.requireNonNull(dragAreaQuery, "dragAreaQuery"); - LimitedScanResult> scanResult = applicationTraceIndexDao.scanScatterData(applicationName, dragAreaQuery, limit); + LimitedScanResult> scanResult = applicationTraceIndexService.scanScatterData(applicationName, dragAreaQuery, limit); logger.debug("dragScatterArea applicationName:{} dots:{}", applicationName, scanResult); // boolean requestComplete = scatterData.getDotSize() < limit; @@ -73,7 +72,7 @@ public LimitedScanResult> dragScatterDataV2(String application Objects.requireNonNull(dragAreaQuery, "dragAreaQuery"); - LimitedScanResult> scanResult = applicationTraceIndexDao.scanScatterDataV2(applicationName, dragAreaQuery, limit); + LimitedScanResult> scanResult = applicationTraceIndexService.scanScatterDataV2(applicationName, dragAreaQuery, limit); scanResult = legacyCompatibilityCheck(applicationName, scanResult); logger.debug("dragScatterArea applicationName:{} dots:{}", applicationName, scanResult); @@ -146,7 +145,7 @@ public LimitedScanResult getHeatMap(String applicationName, Range range Objects.requireNonNull(range, "range"); - LimitedScanResult> scanResult = applicationTraceIndexDao.scanTraceScatterData(applicationName, range, limit, true); + LimitedScanResult> scanResult = applicationTraceIndexService.scanTraceScatterData(applicationName, range, limit, true); final int slotSize = 100; HeatMapBuilder builder = HeatMapBuilder.newBuilder(range.getFrom(), range.getTo(), slotSize, 0, maxY, slotSize); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java index 7bb2083680d6..190831be744d 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ScatterChartServiceImpl.java @@ -20,7 +20,6 @@ import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.util.CollectionUtils; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; import com.navercorp.pinpoint.web.dao.TraceDao; import com.navercorp.pinpoint.web.filter.Filter; import com.navercorp.pinpoint.web.scatter.ScatterData; @@ -48,16 +47,16 @@ public class ScatterChartServiceImpl implements ScatterChartService { private final Logger logger = LogManager.getLogger(this.getClass()); - private final ApplicationTraceIndexDao applicationTraceIndexDao; + private final ApplicationTraceIndexService applicationTraceIndexService; private final TraceDao traceDao; private final SpanService spanService; - public ScatterChartServiceImpl(ApplicationTraceIndexDao applicationTraceIndexDao, + public ScatterChartServiceImpl(ApplicationTraceIndexService applicationTraceIndexService, TraceDao traceDao, SpanService spanService) { - this.applicationTraceIndexDao = Objects.requireNonNull(applicationTraceIndexDao, "applicationTraceIndexDao"); + this.applicationTraceIndexService = Objects.requireNonNull(applicationTraceIndexService, "applicationTraceIndexService"); this.traceDao = Objects.requireNonNull(traceDao, "traceDao"); this.spanService = Objects.requireNonNull(spanService, "spanService"); } @@ -78,9 +77,9 @@ public List selectScatterData(List transactionIdList, String } for (SpanBo span : trace) { - if (applicationName.equals(span.getApplicationId())) { + if (applicationName.equals(span.getApplicationName())) { final TransactionId transactionId = span.getTransactionId(); - final Dot dot = new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId()); + final Dot dot = new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId().value()); result.add(dot); } } @@ -113,7 +112,7 @@ public List selectTransactionMetadata(TransactionId transactionId) { public ScatterData selectScatterData(String applicationName, Range range, int xGroupUnit, int yGroupUnit, int limit, boolean backwardDirection) { Objects.requireNonNull(applicationName, "applicationName"); Objects.requireNonNull(range, "range"); - LimitedScanResult> scanResult = applicationTraceIndexDao.scanTraceScatterData(applicationName, range, limit, backwardDirection); + LimitedScanResult> scanResult = applicationTraceIndexService.scanTraceScatterData(applicationName, range, limit, backwardDirection); ScatterDataBuilder builder = new ScatterDataBuilder(range.getFrom(), range.getTo(), xGroupUnit, yGroupUnit); builder.addDot(scanResult.scanData()); @@ -136,9 +135,9 @@ public ScatterData selectScatterData(List transactionIdList, Stri } for (SpanBo span : trace) { - if (applicationName.equals(span.getApplicationId())) { + if (applicationName.equals(span.getApplicationName())) { final TransactionId transactionId = span.getTransactionId(); - final Dot dot = new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId()); + final Dot dot = new Dot(transactionId, span.getCollectorAcceptTime(), span.getElapsed(), span.getErrCode(), span.getAgentId().value()); scatterData.addDot(dot); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoService.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoService.java new file mode 100644 index 000000000000..55b0fdcbb6fe --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoService.java @@ -0,0 +1,35 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.service; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; + +import java.util.List; + +/** + * @author youngjin.kim2 + */ +public interface ServiceInfoService { + + ServiceInfo getServiceInfo(ServiceId id); + + ServiceId getServiceId(String serviceName); + + List getApplicationIds(ServiceId serviceId); + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoServiceImpl.java new file mode 100644 index 000000000000..804516d14037 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/ServiceInfoServiceImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.service; + +import com.navercorp.pinpoint.common.id.ApplicationId; +import com.navercorp.pinpoint.common.id.ServiceId; +import com.navercorp.pinpoint.common.server.bo.ServiceInfo; +import com.navercorp.pinpoint.web.dao.ApplicationInfoDao; +import com.navercorp.pinpoint.web.dao.ServiceInfoDao; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Objects; + +/** + * @author youngjin.kim2 + */ +@Service +public class ServiceInfoServiceImpl implements ServiceInfoService { + + private final ServiceInfoDao serviceInfoDao; + private final ApplicationInfoDao applicationInfoDao; + + + public ServiceInfoServiceImpl( + ServiceInfoDao serviceInfoDao, + ApplicationInfoDao applicationInfoDao + ) { + this.serviceInfoDao = Objects.requireNonNull(serviceInfoDao, "serviceInfoDao"); + this.applicationInfoDao = Objects.requireNonNull(applicationInfoDao, "applicationInfoDao"); + } + + @Override + @Cacheable(value = "serviceInfoById", key = "#id") + public ServiceInfo getServiceInfo(ServiceId id) { + return this.serviceInfoDao.getServiceInfo(id); + } + + @Override + @Cacheable(value = "serviceIdByName", key = "#serviceName") + public ServiceId getServiceId(String serviceName) { + return this.serviceInfoDao.getServiceId(serviceName); + } + + @Override + public List getApplicationIds(ServiceId serviceId) { + return this.applicationInfoDao.getApplications(serviceId); + } + +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java index e86f4660fd72..61308180eab9 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/service/TransactionInfoServiceImpl.java @@ -113,7 +113,7 @@ public BusinessTransactions selectBusinessTransactions(List trans for (SpanBo spanBo : trace) { // show application's incoming requests - if (applicationName.equals(spanBo.getApplicationId())) { + if (applicationName.equals(spanBo.getApplicationName())) { businessTransactions.add(spanBo); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/AgentResponseTimeViewModel.java b/web/src/main/java/com/navercorp/pinpoint/web/view/AgentResponseTimeViewModel.java new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationScatterScanResultSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationScatterScanResultSerializer.java index e3cbf8044ec1..5462963e8945 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationScatterScanResultSerializer.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/ApplicationScatterScanResultSerializer.java @@ -32,7 +32,7 @@ public class ApplicationScatterScanResultSerializer extends JsonSerializer { @Override public void serialize(Application application, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); - jgen.writeStringField("applicationName", application.getName()); - jgen.writeStringField("serviceType", application.getServiceType().getDesc()); + if (application.id() != null) { + jgen.writeStringField("id", application.id().toString()); + } else { + jgen.writeNullField("id"); + } + jgen.writeStringField("applicationName", application.name()); + jgen.writeStringField("serviceType", application.serviceType().getDesc()); jgen.writeNumberField("code", application.getServiceTypeCode()); jgen.writeEndObject(); } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java index 07b32ed0ca59..cbfbe7c75c81 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/LinkSerializer.java @@ -64,9 +64,9 @@ public void serialize(Link link, JsonGenerator jgen, SerializerProvider provider writeSimpleNode("targetInfo", link.getTo(), jgen); Application filterApplication = link.getFilterApplication(); - jgen.writeStringField("filterApplicationName", filterApplication.getName()); + jgen.writeStringField("filterApplicationName", filterApplication.name()); jgen.writeNumberField("filterApplicationServiceTypeCode", filterApplication.getServiceTypeCode()); - jgen.writeStringField("filterApplicationServiceTypeName", filterApplication.getServiceType().getName()); + jgen.writeStringField("filterApplicationServiceTypeName", filterApplication.serviceType().getName()); if (link.isWasToWasLink()) { writeWasToWasTargetRpcList(link, jgen); } @@ -139,7 +139,7 @@ private void writeWasToWasTargetRpcList(Link link, JsonGenerator jgen) throws IO Collection sourceLinkTargetAgentList = link.getSourceLinkTargetAgentList(); for (Application application : sourceLinkTargetAgentList) { jgen.writeStartObject(); - jgen.writeStringField("rpc", application.getName()); + jgen.writeStringField("rpc", application.name()); jgen.writeNumberField("rpcServiceTypeCode", application.getServiceTypeCode()); jgen.writeEndObject(); } @@ -185,10 +185,10 @@ private void writeSimpleNode(String fieldName, Node node, JsonGenerator jgen) th jgen.writeStartObject(); Application application = node.getApplication(); - jgen.writeStringField("applicationName", application.getName()); - jgen.writeStringField("serviceType", application.getServiceType().toString()); + jgen.writeStringField("applicationName", application.name()); + jgen.writeStringField("serviceType", application.serviceType().toString()); jgen.writeNumberField("serviceTypeCode", application.getServiceTypeCode()); - jgen.writeBooleanField("isWas", application.getServiceType().isWas()); + jgen.writeBooleanField("isWas", application.serviceType().isWas()); jgen.writeEndObject(); } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/NodeSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/NodeSerializer.java index 29bc180b5a1c..e2216b48ae38 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/NodeSerializer.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/NodeSerializer.java @@ -58,7 +58,7 @@ public void serialize(Node node, JsonGenerator jgen, SerializerProvider provider jgen.writeStringField("category", node.getServiceType().toString()); // necessary for go.js jgen.writeStringField("serviceType", node.getServiceType().toString()); - final ServiceType serviceType = node.getApplication().getServiceType(); + final ServiceType serviceType = node.getApplication().serviceType(); // if (serviceType.isUser()) { // jgen.writeStringField("fig", "Ellipse"); // } else if(serviceType.isWas()) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/StringPinpointIdSerializer.java b/web/src/main/java/com/navercorp/pinpoint/web/view/StringPinpointIdSerializer.java new file mode 100644 index 000000000000..9f152d7d51d9 --- /dev/null +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/StringPinpointIdSerializer.java @@ -0,0 +1,33 @@ +/* + * Copyright 2024 NAVER Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.navercorp.pinpoint.web.view; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.navercorp.pinpoint.common.id.StringPinpointIdentifier; + +import java.io.IOException; + +/** + * @author youngjin.kim2 + */ +public class StringPinpointIdSerializer extends JsonSerializer { + @Override + public void serialize(StringPinpointIdentifier id, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeString(id.value()); + } +} diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/TimeViewModel.java b/web/src/main/java/com/navercorp/pinpoint/web/view/TimeViewModel.java index 4e1b808f8aa4..baf027bc8004 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/TimeViewModel.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/TimeViewModel.java @@ -61,7 +61,7 @@ public ResponseTimeViewModelList(Application application, List hi public List build() { final List result = new ArrayList<>(9); - ServiceType serviceType = application.getServiceType(); + ServiceType serviceType = application.serviceType(); HistogramSchema schema = serviceType.getHistogramSchema(); result.add(new ResponseTimeViewModel(schema.getFastSlot().getSlotName(), getColumnValue(histogramList, SlotType.FAST))); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/HistogramView.java b/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/HistogramView.java index 006198654d5c..39928a013457 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/HistogramView.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/HistogramView.java @@ -77,7 +77,7 @@ public TimeSeriesView getLoadStatisticsChart() { public static HistogramView view(NodeHistogramSummary summary) { Application application = summary.getApplication(); - String nodeName = NodeName.toNodeName(application.getName(), application.getServiceType()); + String nodeName = NodeName.toNodeName(application.name(), application.serviceType()); Histogram applicationHistogram = summary.getNodeHistogram().getApplicationHistogram(); List histogramList = summary.getNodeHistogram().getApplicationTimeHistogram().getHistogramList(); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/ServerHistogramView.java b/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/ServerHistogramView.java index 486e1757f655..8f8d1698ed76 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/ServerHistogramView.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/histogram/ServerHistogramView.java @@ -34,7 +34,7 @@ public class ServerHistogramView { public static ServerHistogramView view(NodeHistogramSummary summary) { Application application = summary.getApplication(); - String key = NodeName.toNodeName(application.getName(), application.getServiceType()); + String key = NodeName.toNodeName(application.name(), application.serviceType()); List agentHistogramList = summary.getNodeHistogram().createAgentHistogramViewList(); ServerGroupList serverGroupList = summary.getServerGroupList(); return new ServerHistogramView(key, agentHistogramList, serverGroupList); diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/id/AgentNameView.java b/web/src/main/java/com/navercorp/pinpoint/web/view/id/AgentNameView.java index 0021f5c11c96..58549910c3ae 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/id/AgentNameView.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/id/AgentNameView.java @@ -8,7 +8,7 @@ public record AgentNameView(String agentName) { public static AgentNameView of(Application application) { Objects.requireNonNull(application, "application"); - return new AgentNameView(application.getName()); + return new AgentNameView(application.name()); } public AgentNameView(String agentName) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/view/transactionlist/TransactionMetaDataViewModel.java b/web/src/main/java/com/navercorp/pinpoint/web/view/transactionlist/TransactionMetaDataViewModel.java index 1631d83e4928..361459c94b8a 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/view/transactionlist/TransactionMetaDataViewModel.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/view/transactionlist/TransactionMetaDataViewModel.java @@ -81,7 +81,7 @@ public String getApplication() { @Override public String getAgentId() { - return span.getAgentId(); + return span.getAgentId().value(); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java index 29dceca891cd..45bf290b09ba 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/Application.java @@ -17,35 +17,28 @@ package com.navercorp.pinpoint.web.vo; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.view.ApplicationSerializer; import java.util.Objects; /** - * * @author netspider * @author emeroad * @author jaehong.kim - * */ @JsonSerialize(using = ApplicationSerializer.class) -public final class Application { - private final String name; - private final ServiceType serviceType; +public record Application(ApplicationId id, String name, ServiceType serviceType) { - public Application(String name, ServiceType serviceType) { - this.name = Objects.requireNonNull(name, "name"); + public Application(ApplicationId id, String name, ServiceType serviceType) { + this.id = id; + this.name = name; this.serviceType = Objects.requireNonNull(serviceType, "serviceType"); } - - public String getName() { - return name; - } - - public ServiceType getServiceType() { - return serviceType; + public Application(String name, ServiceType serviceType) { + this(null, name, serviceType); } public short getServiceTypeCode() { @@ -56,18 +49,13 @@ public short getServiceTypeCode() { public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - Application that = (Application) o; - - if (!name.equals(that.name)) return false; - return serviceType.equals(that.serviceType); + return Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(serviceType, that.serviceType); } @Override public int hashCode() { - int result = name.hashCode(); - result = 31 * result + serviceType.hashCode(); - return result; + return Objects.hash(id, name, serviceType); } @Override diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseHistograms.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseHistograms.java index c00f927a1ab4..5c616acfa813 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseHistograms.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/ResponseHistograms.java @@ -72,7 +72,7 @@ public Builder addHistogram(Application application, SpanBo span, long timestamp if (span.getErrCode() != 0) { error = true; } - responseTime.addResponseTime(span.getAgentId(), span.getElapsed(), error); + responseTime.addResponseTime(span.getAgentId().value(), span.getElapsed(), error); return this; } @@ -87,7 +87,7 @@ private ResponseTime getResponseTime(Application application, Long timestamp) { Map responseTimeMap = responseTimeApplicationMap.computeIfAbsent(timestamp, (Long k) -> new HashMap<>()); ResponseTime responseTime = responseTimeMap.get(application); if (responseTime == null) { - responseTime = new ResponseTime(application.getName(), application.getServiceType(), timestamp); + responseTime = new ResponseTime(application.name(), application.serviceType(), timestamp); responseTimeMap.put(application, responseTime); } return responseTime; diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentInfo.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentInfo.java index 71a0ffff848c..cfa870adb9f6 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentInfo.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentInfo.java @@ -17,8 +17,10 @@ package com.navercorp.pinpoint.web.vo.agent; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.view.ServiceTypeDescView; +import com.navercorp.pinpoint.web.view.StringPinpointIdSerializer; import java.util.Objects; @@ -28,7 +30,8 @@ public class AgentInfo { private String applicationName; - private String agentId; + @JsonSerialize(using = StringPinpointIdSerializer.class) + private AgentId agentId; private String agentName; private long startTimestamp; private String hostName; @@ -51,11 +54,11 @@ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } - public String getAgentId() { + public AgentId getAgentId() { return agentId; } - public void setAgentId(String agentId) { + public void setAgentId(AgentId agentId) { this.agentId = agentId; } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatus.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatus.java index 62f6b394a94c..51b972c341c1 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatus.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatus.java @@ -16,7 +16,10 @@ package com.navercorp.pinpoint.web.vo.agent; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState; +import com.navercorp.pinpoint.web.view.StringPinpointIdSerializer; import java.util.Objects; @@ -27,19 +30,24 @@ */ public class AgentStatus { - private final String agentId; + @JsonSerialize(using = StringPinpointIdSerializer.class) + private final AgentId agentId; private long eventTimestamp; private final AgentLifeCycleState state; - public AgentStatus(String agentId, AgentLifeCycleState state, long eventTimestamp) { + public AgentStatus(AgentId agentId, AgentLifeCycleState state, long eventTimestamp) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.state = Objects.requireNonNull(state, "state"); this.eventTimestamp = eventTimestamp; } - public String getAgentId() { + public AgentStatus(String agentId, AgentLifeCycleState state, long eventTimestamp) { + this(AgentId.of(agentId), state, eventTimestamp); + } + + public AgentId getAgentId() { return agentId; } @@ -73,11 +81,9 @@ public int hashCode() { @Override public String toString() { - final StringBuilder sb = new StringBuilder("AgentStatus{"); - sb.append("agentId='").append(agentId).append('\''); - sb.append(", eventTimestamp=").append(eventTimestamp); - sb.append(", state=").append(state); - sb.append('}'); - return sb.toString(); + return "AgentStatus{" + "agentId='" + agentId + '\'' + + ", eventTimestamp=" + eventTimestamp + + ", state=" + state + + '}'; } } diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatusQuery.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatusQuery.java index 86d0fdbde31a..6a2fdeb4b21c 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatusQuery.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/agent/AgentStatusQuery.java @@ -64,7 +64,7 @@ private static SimpleAgentKey apply(AgentInfo agentInfo) { if (agentInfo == null) { return null; } - return new SimpleAgentKey(agentInfo.getAgentId(), agentInfo.getStartTimestamp()); + return new SimpleAgentKey(agentInfo.getAgentId().value(), agentInfo.getStartTimestamp()); } public static AgentStatusQuery buildQuery(Collection agentInfos, Function transform, Instant timestamp) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/DotAgentInfo.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/DotAgentInfo.java index 2e0e1b5cca08..6da6758b34e7 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/DotAgentInfo.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/scatter/DotAgentInfo.java @@ -25,7 +25,7 @@ public class DotAgentInfo { private final long transactionAgentStartTime; public DotAgentInfo(Dot dot) { - this(dot.getAgentId(), dot.getTransactionId().getAgentId(), dot.getTransactionId().getAgentStartTime()); + this(dot.getAgentId(), dot.getTransactionId().getAgentId().value(), dot.getTransactionId().getAgentStartTime()); } public DotAgentInfo(String agentId, String transactionAgentId, long transactionAgentStartTime) { diff --git a/web/src/main/java/com/navercorp/pinpoint/web/vo/tree/ApplicationAgentHostList.java b/web/src/main/java/com/navercorp/pinpoint/web/vo/tree/ApplicationAgentHostList.java index f3827c099834..68059afa4904 100644 --- a/web/src/main/java/com/navercorp/pinpoint/web/vo/tree/ApplicationAgentHostList.java +++ b/web/src/main/java/com/navercorp/pinpoint/web/vo/tree/ApplicationAgentHostList.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.vo.tree; import com.fasterxml.jackson.annotation.JsonProperty; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.util.StringUtils; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; @@ -112,7 +113,7 @@ public void addAgentInfo(String applicationName, List agentInfoList) } private AgentHost newAgentHost(AgentInfo agentInfo) { - String agentId = StringUtils.defaultString(agentInfo.getAgentId(), ""); + AgentId agentId = agentInfo.getAgentId(); String hostName = StringUtils.defaultString(agentInfo.getHostName(), ""); String ip = StringUtils.defaultString(agentInfo.getIp(), ""); String serviceType = agentInfo.getServiceType().getDesc(); @@ -121,17 +122,15 @@ private AgentHost newAgentHost(AgentInfo agentInfo) { public ApplicationAgentHostList build() { List applicationInfos = buildApplicationInfo(this.map); - ApplicationAgentHostList agents = new ApplicationAgentHostList(startApplicationIndex, endApplicationIndex, totalApplications, + return new ApplicationAgentHostList(startApplicationIndex, endApplicationIndex, totalApplications, applicationInfos); - return agents; } private List buildApplicationInfo(Map> map) { - List applications = map.entrySet().stream() + return map.entrySet().stream() .map(Builder::newApplication) .sorted(Comparator.comparing(ApplicationInfo::applicationName)) .collect(Collectors.toList()); - return applications; } @@ -139,7 +138,7 @@ private static ApplicationInfo newApplication(Map.Entry> String applicationName = entry.getKey(); List agentHosts = entry.getValue(); - agentHosts.sort(Comparator.comparing(AgentHost::agentId)); + agentHosts.sort(Comparator.comparing(AgentHost::getAgentId)); return new ApplicationInfo(applicationName, agentHosts); } @@ -148,7 +147,30 @@ private static ApplicationInfo newApplication(Map.Entry> public record ApplicationInfo(String applicationName, List agents) { } - public record AgentHost(String agentId, String hostName, String ip, String serviceType) { + public static class AgentHost { + private final AgentId agentId; + private final String hostName; + private final String ip; + private final String serviceType; + + public AgentHost(AgentId agentId, String hostName, String ip, String serviceType) { + this.agentId = Objects.requireNonNull(agentId, "agentId"); + this.hostName = Objects.requireNonNull(hostName, "hostName"); + this.ip = Objects.requireNonNull(ip, "ip"); + this.serviceType = Objects.requireNonNull(serviceType, "serviceType"); + } + + public AgentId getAgentId() { + return agentId; + } + + public String getHostName() { + return hostName; + } + + public String getIp() { + return ip; + } } } \ No newline at end of file diff --git a/web/src/test/java/com/navercorp/pinpoint/web/TestTraceUtils.java b/web/src/test/java/com/navercorp/pinpoint/web/TestTraceUtils.java index 972069386d90..dc80b467cdcf 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/TestTraceUtils.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/TestTraceUtils.java @@ -17,11 +17,12 @@ package com.navercorp.pinpoint.web; import com.navercorp.pinpoint.bootstrap.context.SpanId; +import com.navercorp.pinpoint.common.id.AgentId; +import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanEventBo; -import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; import com.navercorp.pinpoint.common.trace.ServiceType; -import com.navercorp.pinpoint.common.profiler.util.TransactionId; +import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; import com.navercorp.pinpoint.web.util.ServiceTypeRegistryMockFactory; import org.assertj.core.matcher.AssertionMatcher; @@ -158,8 +159,8 @@ public SpanBuilder parentSpan(SpanBo parentSpan) { public SpanBo build() { SpanBo spanBo = new SpanBo(); spanBo.setVersion(version); - spanBo.setApplicationId(applicationName); - spanBo.setAgentId(agentId); + spanBo.setApplicationName(applicationName); + spanBo.setAgentId(AgentId.of(agentId)); long spanId = this.spanId; if (spanId == SpanId.NULL) { spanId = random.nextLong(); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTest.java index 3fee26fce7a1..34e9a90a7a7b 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTest.java @@ -57,6 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyShort; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -99,10 +100,10 @@ public void setUp() { @Override public List answer(InvocationOnMock invocation) { Application application = invocation.getArgument(0); - String applicationName = application.getName(); - ServiceType applicationServiceType = application.getServiceType(); + String applicationName = application.name(); + ServiceType applicationServiceType = application.serviceType(); int depth = ApplicationMapBuilderTestHelper.getDepthFromApplicationName(applicationName); - ResponseTime responseTime = new ResponseTime(application.getName(), application.getServiceType(), timestamp); + ResponseTime responseTime = new ResponseTime(application.name(), application.serviceType(), timestamp); responseTime.addResponseTime(ApplicationMapBuilderTestHelper.createAgentIdFromDepth(depth), applicationServiceType.getHistogramSchema().getNormalSlot().getSlotTime(), 1); return List.of(responseTime); } @@ -110,7 +111,7 @@ public List answer(InvocationOnMock invocation) { when(mapResponseDao.selectResponseTime(any(Application.class), any(Range.class))).thenAnswer(responseTimeAnswer); when(responseHistograms.getResponseTimeList(any(Application.class))).thenAnswer(responseTimeAnswer); - when(agentInfoService.getAgentsByApplicationName(anyString(), anyLong())).thenAnswer(new Answer<>() { + when(agentInfoService.getAgentsByApplicationName(anyString(), anyShort(), anyLong())).thenAnswer(new Answer>() { @Override public Set answer(InvocationOnMock invocation) throws Throwable { String applicationName = invocation.getArgument(0); @@ -120,7 +121,7 @@ public Set answer(InvocationOnMock invocation) throws Throwable return Set.of(new AgentAndStatus(agentInfo, agentStatus)); } }); - when(agentInfoService.getAgentsByApplicationNameWithoutStatus(anyString(), anyLong())).thenAnswer(new Answer<>() { + when(agentInfoService.getAgentsByApplicationNameWithoutStatus(anyString(), anyShort(), anyLong())).thenAnswer(new Answer>() { @Override public Set answer(InvocationOnMock invocation) throws Throwable { String applicationName = invocation.getArgument(0); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTestHelper.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTestHelper.java index f7fce6a8670b..21e7da446cb0 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTestHelper.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ApplicationMapBuilderTestHelper.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.applicationmap; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.util.time.Range; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.trace.ServiceTypeFactory; @@ -97,7 +98,7 @@ public static LinkData createTargetLinkData(int depth) { Application toApplication = createApplicationFromDepth(toDepth); LinkData targetLinkData = new LinkData(fromApplication, toApplication); targetLinkData.addLinkData( - fromApplication.getName(), WAS_TYPE, + fromApplication.name(), WAS_TYPE, createAgentIdFromDepth(toDepth), WAS_TYPE, System.currentTimeMillis(), WAS_TYPE.getHistogramSchema().getNormalSlot().getSlotTime(), 1); return targetLinkData; @@ -109,7 +110,7 @@ public static LinkData createUserTargetLinkData(int depth) { Application fromApplication = createUserApplication(toApplication); LinkData targetLinkData = new LinkData(fromApplication, toApplication); targetLinkData.addLinkData( - fromApplication.getName(), USER_TYPE, + fromApplication.name(), USER_TYPE, createAgentIdFromDepth(toDepth), WAS_TYPE, System.currentTimeMillis(), WAS_TYPE.getHistogramSchema().getNormalSlot().getSlotTime(), 1); return targetLinkData; @@ -158,18 +159,18 @@ public static Application createApplicationFromDepth(int depth) { } public static Application createUserApplication(Application toApplication) { - String userApplicationName = toApplication.getName() + "_" + toApplication.getServiceType().getName(); + String userApplicationName = toApplication.name() + "_" + toApplication.serviceType().getName(); return new Application(userApplicationName, USER_TYPE); } public static Application createTerminalApplication(Application fromApplication) { - int depth = getDepthFromApplicationName(fromApplication.getName()); + int depth = getDepthFromApplicationName(fromApplication.name()); String terminalApplicationName = "destinationId_" + depth; return new Application(terminalApplicationName, TERMINAL_TYPE); } public static Application createUnknownApplication(Application fromApplication) { - int depth = getDepthFromApplicationName(fromApplication.getName()); + int depth = getDepthFromApplicationName(fromApplication.name()); return new Application(createHostnameFromDepth(depth), UNKNOWN_TYPE); } @@ -204,7 +205,7 @@ public static AgentInfo createAgentInfoFromApplicationName(String applicationNam String hostName = createHostnameFromDepth(depth); AgentInfo agentInfo = new AgentInfo(); agentInfo.setApplicationName(applicationName); - agentInfo.setAgentId(agentId); + agentInfo.setAgentId(AgentId.of(agentId)); agentInfo.setHostName(hostName); return agentInfo; } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerGroupListTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerGroupListTest.java index 8c098aacf6ba..dfdb58addb28 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerGroupListTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/ServerGroupListTest.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.applicationmap; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService; @@ -58,7 +59,7 @@ public void testGetAgentIdList() { public static AgentAndStatus createAgentInfo(String agentId, String hostName) { AgentInfoBo.Builder agentInfoBuilder = new AgentInfoBo.Builder(); - agentInfoBuilder.setAgentId(agentId); + agentInfoBuilder.setAgentId(AgentId.of(agentId)); ServiceType serviceType = ServiceType.TEST_STAND_ALONE; agentInfoBuilder.setServiceTypeCode(serviceType.getCode()); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramTest.java index af13f7546ea2..ddc2a08ae481 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/AgentTimeHistogramTest.java @@ -107,16 +107,16 @@ public void getApplicationApdexScoreListTest() { private List createResponseTime(Application app, String agentName1, String agentName2) { - ResponseTime one = new ResponseTime(app.getName(), app.getServiceType(), 0); + ResponseTime one = new ResponseTime(app.name(), app.serviceType(), 0); one.addResponseTime(agentName1, (short) 1000, 1); - ResponseTime two = new ResponseTime(app.getName(), app.getServiceType(), 1000 * 60); + ResponseTime two = new ResponseTime(app.name(), app.serviceType(), 1000 * 60); two.addResponseTime(agentName1, (short) 3000, 1); - ResponseTime three = new ResponseTime(app.getName(), app.getServiceType(), 0); + ResponseTime three = new ResponseTime(app.name(), app.serviceType(), 0); three.addResponseTime(agentName2, (short) 1000, 1); - ResponseTime four = new ResponseTime(app.getName(), app.getServiceType(), 1000 * 60); + ResponseTime four = new ResponseTime(app.name(), app.serviceType(), 1000 * 60); four.addResponseTime(agentName2, (short) 3000, 1); return List.of(one, two, three, four); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramTest.java index ce7277cdb305..98730374d81b 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramTest.java @@ -63,10 +63,10 @@ public void testViewModel() throws IOException { private List createResponseTime(Application app) { - ResponseTime one = new ResponseTime(app.getName(), app.getServiceType(), 0); + ResponseTime one = new ResponseTime(app.name(), app.serviceType(), 0); one.addResponseTime("test", (short) 1000, 1); - ResponseTime two = new ResponseTime(app.getName(), app.getServiceType(), 1000 * 60); + ResponseTime two = new ResponseTime(app.name(), app.serviceType(), 1000 * 60); two.addResponseTime("test", (short) 3000, 1); return List.of(one, two); @@ -80,7 +80,7 @@ public void testLoadViewModel() { ApplicationTimeHistogramBuilder builder = new ApplicationTimeHistogramBuilder(app, range); - ResponseTime responseTime = new ResponseTime(app.getName(), app.getServiceType(), timestamp); + ResponseTime responseTime = new ResponseTime(app.name(), app.serviceType(), timestamp); responseTime.addResponseTime("test", (short) 1000, 1); List responseHistogramList = List.of(responseTime); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/map/LinkSelectorTestBase.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/map/LinkSelectorTestBase.java index 76418e8c5cbb..0fa84c190b25 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/map/LinkSelectorTestBase.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/map/LinkSelectorTestBase.java @@ -260,8 +260,8 @@ public void testCaller_rpc() { List callDatas = List.copyOf(linkData_A_B.getLinkCallDataMap().getLinkDataList()); assertThat(callDatas).hasSize(1); LinkCallData callData = callDatas.get(0); - assertEquals(rpcUri, callData.getTarget().getName()); - assertEquals(testRpcServiceType, callData.getTarget().getServiceType()); + assertEquals(rpcUri, callData.getTarget().name()); + assertEquals(testRpcServiceType, callData.getTarget().serviceType()); } @Test @@ -394,14 +394,14 @@ public void testVirtual() { List callData_A_Bs = List.copyOf(linkData_A_B.getLinkCallDataMap().getLinkDataList()); assertThat(callData_A_Bs).hasSize(1); LinkCallData callData_A_B = callData_A_Bs.get(0); - assertEquals(rpcUri, callData_A_B.getTarget().getName()); - assertEquals(testRpcServiceType, callData_A_B.getTarget().getServiceType()); + assertEquals(rpcUri, callData_A_B.getTarget().name()); + assertEquals(testRpcServiceType, callData_A_B.getTarget().serviceType()); List callData_A_Cs = List.copyOf(linkData_A_C.getLinkCallDataMap().getLinkDataList()); assertThat(callData_A_Cs).hasSize(1); LinkCallData callData_A_C = callData_A_Cs.get(0); - assertEquals(rpcUri, callData_A_C.getTarget().getName()); - assertEquals(testRpcServiceType, callData_A_C.getTarget().getServiceType()); + assertEquals(rpcUri, callData_A_C.getTarget().name()); + assertEquals(testRpcServiceType, callData_A_C.getTarget().serviceType()); } @Test diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImplTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImplTest.java index d94e52114d83..ee6fec7cf333 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImplTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/FilteredMapServiceImplTest.java @@ -43,11 +43,11 @@ import com.navercorp.pinpoint.web.applicationmap.link.Link; import com.navercorp.pinpoint.web.applicationmap.nodes.Node; import com.navercorp.pinpoint.web.component.ApplicationFactory; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; import com.navercorp.pinpoint.web.dao.TraceDao; import com.navercorp.pinpoint.web.filter.Filter; import com.navercorp.pinpoint.web.hyperlink.HyperLinkFactory; import com.navercorp.pinpoint.web.service.AgentInfoService; +import com.navercorp.pinpoint.web.service.ApplicationTraceIndexService; import com.navercorp.pinpoint.web.service.ServerInstanceDatasourceService; import com.navercorp.pinpoint.web.view.ResponseTimeViewModel; import com.navercorp.pinpoint.web.view.TimeViewModel; @@ -99,7 +99,7 @@ public class FilteredMapServiceImplTest { private TraceDao traceDao; @Mock - private ApplicationTraceIndexDao applicationTraceIndexDao; + private ApplicationTraceIndexService applicationTraceIndexService; @Mock private ApplicationFactory applicationFactory; @@ -145,7 +145,7 @@ public void init() { return new AgentInfoServerGroupListDataSource(agentInfoService, HyperLinkFactory.empty()); }); - filteredMapService = new FilteredMapServiceImpl(traceDao, applicationTraceIndexDao, + filteredMapService = new FilteredMapServiceImpl(traceDao, applicationTraceIndexService, registry, applicationFactory, serverInstanceDatasourceService, Optional.empty(), applicationMapBuilderFactory); } @@ -219,7 +219,7 @@ public void twoTier() { assertThat(nodes).hasSize(4); for (Node node : nodes) { Application application = node.getApplication(); - if (application.getName().equals("ROOT_APP") && application.getServiceType().getCode() == TestTraceUtils.USER_TYPE_CODE) { + if (application.name().equals("ROOT_APP") && application.serviceType().getCode() == TestTraceUtils.USER_TYPE_CODE) { // USER node NodeHistogram nodeHistogram = node.getNodeHistogram(); // histogram @@ -238,7 +238,7 @@ public void twoTier() { JsonFields> agentTimeHistogram = getAgentTimeHistogram(nodeHistogram); // AgentResponseTimeViewModelList agentTimeHistogram = agentTimeHistogram; Assertions.assertTrue(agentTimeHistogram.isEmpty()); - } else if (application.getName().equals("ROOT_APP") && application.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) { + } else if (application.name().equals("ROOT_APP") && application.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) { // ROOT_APP node NodeHistogram nodeHistogram = node.getNodeHistogram(); // histogram @@ -256,7 +256,7 @@ public void twoTier() { JsonFields> agentTimeHistogram = getAgentTimeHistogram(nodeHistogram); // AgentResponseTimeViewModelList agentTimeHistogram = nodeHistogram.getAgentTimeHistogram(TimeHistogramFormat.V1); assertAgentTimeHistogram(agentTimeHistogram, "root-agent", histogramSchema.getFastSlot(), expectedTimeCounts); - } else if (application.getName().equals("APP_A") && application.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) { + } else if (application.name().equals("APP_A") && application.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) { // APP_A node NodeHistogram nodeHistogram = node.getNodeHistogram(); // histogram @@ -274,7 +274,7 @@ public void twoTier() { JsonFields> agentTimeHistogram = getAgentTimeHistogram(nodeHistogram); // AgentResponseTimeViewModelList agentTimeHistogram = nodeHistogram.getAgentTimeHistogram(TimeHistogramFormat.V1); assertAgentTimeHistogram(agentTimeHistogram, "app-a", histogramSchema.getFastSlot(), expectedTimeCounts); - } else if (application.getName().equals("CacheName") && application.getServiceType().getCode() == TestTraceUtils.CACHE_TYPE_CODE) { + } else if (application.name().equals("CacheName") && application.serviceType().getCode() == TestTraceUtils.CACHE_TYPE_CODE) { // CACHE node NodeHistogram nodeHistogram = node.getNodeHistogram(); // histogram @@ -302,39 +302,39 @@ public void twoTier() { for (Link link : links) { Application fromApplication = link.getFrom().getApplication(); Application toApplication = link.getTo().getApplication(); - if ((fromApplication.getName().equals("ROOT_APP") && fromApplication.getServiceType().getCode() == TestTraceUtils.USER_TYPE_CODE) && - (toApplication.getName().equals("ROOT_APP") && toApplication.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE)) { + if ((fromApplication.name().equals("ROOT_APP") && fromApplication.serviceType().getCode() == TestTraceUtils.USER_TYPE_CODE) && + (toApplication.name().equals("ROOT_APP") && toApplication.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE)) { // histogram Histogram histogram = link.getHistogram(); assertHistogram(histogram, 1, 0, 0, 0, 0); // time histogram List linkApplicationTimeSeriesHistogram = link.getLinkApplicationTimeSeriesHistogram(); - HistogramSchema targetHistogramSchema = toApplication.getServiceType().getHistogramSchema(); + HistogramSchema targetHistogramSchema = toApplication.serviceType().getHistogramSchema(); List expectedTimeCounts = List.of( new ResponseTimeViewModel.TimeCount(timeWindow.refineTimestamp(rootSpanCollectorAcceptTime), 1) ); assertTimeHistogram(linkApplicationTimeSeriesHistogram, targetHistogramSchema.getFastSlot(), expectedTimeCounts); - } else if ((fromApplication.getName().equals("ROOT_APP") && fromApplication.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) && - (toApplication.getName().equals("APP_A") && toApplication.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE)) { + } else if ((fromApplication.name().equals("ROOT_APP") && fromApplication.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) && + (toApplication.name().equals("APP_A") && toApplication.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE)) { // histogram Histogram histogram = link.getHistogram(); assertHistogram(histogram, 1, 0, 0, 0, 0); // time histogram List linkApplicationTimeSeriesHistogram = link.getLinkApplicationTimeSeriesHistogram(); - HistogramSchema targetHistogramSchema = toApplication.getServiceType().getHistogramSchema(); + HistogramSchema targetHistogramSchema = toApplication.serviceType().getHistogramSchema(); List expectedTimeCounts = List.of( new ResponseTimeViewModel.TimeCount(timeWindow.refineTimestamp(appASpanCollectorAcceptTime), 1) ); assertTimeHistogram(linkApplicationTimeSeriesHistogram, targetHistogramSchema.getFastSlot(), expectedTimeCounts); - } else if ((fromApplication.getName().equals("APP_A") && fromApplication.getServiceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) && - (toApplication.getName().equals("CacheName") && toApplication.getServiceType().getCode() == TestTraceUtils.CACHE_TYPE_CODE + } else if ((fromApplication.name().equals("APP_A") && fromApplication.serviceType().getCode() == TestTraceUtils.TEST_STAND_ALONE_TYPE_CODE) && + (toApplication.name().equals("CacheName") && toApplication.serviceType().getCode() == TestTraceUtils.CACHE_TYPE_CODE )) { // histogram Histogram histogram = link.getHistogram(); assertHistogram(histogram, 0, 1, 0, 0, 0); // time histogram List linkApplicationTimeSeriesHistogram = link.getLinkApplicationTimeSeriesHistogram(); - HistogramSchema targetHistogramSchema = toApplication.getServiceType().getHistogramSchema(); + HistogramSchema targetHistogramSchema = toApplication.serviceType().getHistogramSchema(); List expectedTimeCounts = List.of( new ResponseTimeViewModel.TimeCount(timeWindow.refineTimestamp(appASpanStartTime + cacheStartElapsed), 1) ); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImplTest.java b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImplTest.java index 577e4bce8146..dacca401e52c 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImplTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/applicationmap/service/ResponseTimeHistogramServiceImplTest.java @@ -137,8 +137,8 @@ public void selectNodeHistogramWASDataTest() { } private ResponseTime createResponseTime(Application application, long timestamp) { - ResponseTime responseTime = new ResponseTime(application.getName(), application.getServiceType(), timestamp); - HistogramSchema schema = application.getServiceType().getHistogramSchema(); + ResponseTime responseTime = new ResponseTime(application.name(), application.serviceType(), timestamp); + HistogramSchema schema = application.serviceType().getHistogramSchema(); responseTime.addResponseTime("agentId", schema.getFastSlot().getSlotTime(), 1L); responseTime.addResponseTime("agentId", schema.getNormalSlot().getSlotTime(), 2L); responseTime.addResponseTime("agentId", schema.getSlowSlot().getSlotTime(), 3L); @@ -581,8 +581,8 @@ public LinkDataDuplexMap select(List sourceApplications, Range rang private LinkData createLinkData(Application fromApplication, Application toApplication, long timestamp) { LinkData linkData = new LinkData(fromApplication, toApplication); - final ServiceType sourceServiceType = fromApplication.getServiceType(); - final ServiceType destinationServiceType = toApplication.getServiceType(); + final ServiceType sourceServiceType = fromApplication.serviceType(); + final ServiceType destinationServiceType = toApplication.serviceType(); final HistogramSchema schema = ServiceTypeCategory.findCategory(destinationServiceType.getCode()).getHistogramSchema(); linkData.addLinkData("sourceAgentId", sourceServiceType, "destinationAgentId", destinationServiceType, timestamp, schema.getFastSlot().getSlotTime(), 1L); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanCallTreeTest.java b/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanCallTreeTest.java index 4df2fe5d24e7..af3e80ddf3a5 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanCallTreeTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanCallTreeTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.calltree.span; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -12,7 +13,7 @@ public class SpanCallTreeTest { @Test public void hasFocusSpan1() { SpanBo root = new SpanBo(); - root.setAgentId("root"); + root.setAgentId(AgentId.of("root")); Align rootAlign = new SpanAlign(root); SpanCallTree callTreeNodes = new SpanCallTree(rootAlign); @@ -24,7 +25,7 @@ public void hasFocusSpan1() { @Test public void hasFocusSpan2() { SpanBo root = new SpanBo(); - root.setAgentId("root"); + root.setAgentId(AgentId.of("root")); Align rootAlign = new SpanAlign(root); SpanCallTree callTreeNodes = new SpanCallTree(rootAlign); @@ -58,14 +59,14 @@ public void hasFocusSpan_child_travel_not_found() { private SpanCallTree childTree(String parentAgentId, String childAgentId1, String childAgentId2) { SpanBo root = new SpanBo(); // root.setSpanId(100); - root.setAgentId(parentAgentId); + root.setAgentId(AgentId.of(parentAgentId)); Align rootAlign = new SpanAlign(root); SpanCallTree rootCallTreeNodes = new SpanCallTree(rootAlign); SpanBo childSpan1 = new SpanBo(); // childSpan1.setParentSpanId(100); // childSpan1.setSpanId(200); - childSpan1.setAgentId(childAgentId1); + childSpan1.setAgentId(AgentId.of(childAgentId1)); Align childAlign1 = new SpanAlign(childSpan1); SpanCallTree childCallTreeNodes1 = new SpanCallTree(childAlign1); rootCallTreeNodes.add(childCallTreeNodes1); @@ -73,7 +74,7 @@ private SpanCallTree childTree(String parentAgentId, String childAgentId1, Strin SpanBo childSpan2 = new SpanBo(); // childSpan2.setParentSpanId(200); // childSpan2.setSpanId(300); - childSpan2.setAgentId(childAgentId2); + childSpan2.setAgentId(AgentId.of(childAgentId2)); Align childAlign2 = new SpanAlign(childSpan2); SpanCallTree childCallTreeNodes2 = new SpanCallTree(childAlign2); rootCallTreeNodes.add(childCallTreeNodes2); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanFiltersTest.java b/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanFiltersTest.java index 34b3f99bf520..d5af074e69fe 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanFiltersTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/calltree/span/SpanFiltersTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.calltree.span; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -31,7 +32,7 @@ public void buildViewPointFilter() { Predicate filter = SpanFilters.spanFilter(spanId, agentId, collectorAcceptTime); SpanBo spanBo = new SpanBo(); spanBo.setCollectorAcceptTime(collectorAcceptTime); - spanBo.setAgentId(agentId); + spanBo.setAgentId(AgentId.of(agentId)); spanBo.setSpanId(spanId); Assertions.assertTrue(filter.test(spanBo)); } @@ -41,7 +42,7 @@ public void buildViewPointFilter_empty_spanId() { Predicate filter = SpanFilters.spanFilter(-1, agentId, collectorAcceptTime); SpanBo spanBo = new SpanBo(); spanBo.setCollectorAcceptTime(collectorAcceptTime); - spanBo.setAgentId(agentId); + spanBo.setAgentId(AgentId.of(agentId)); spanBo.setSpanId(1234); Assertions.assertTrue(filter.test(spanBo)); } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDaoTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDaoTest.java index e9723f08303f..da6b39ef0dcb 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDaoTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/HbaseAgentLifeCycleDaoTest.java @@ -21,6 +21,7 @@ import com.navercorp.pinpoint.common.hbase.ResultsExtractor; import com.navercorp.pinpoint.common.hbase.RowMapper; import com.navercorp.pinpoint.common.hbase.TableNameProvider; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AgentLifeCycleBo; import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState; import com.navercorp.pinpoint.web.dao.AgentLifeCycleDao; @@ -72,14 +73,14 @@ public void beforeEach() { @Test public void status_should_be_set_appropriately_if_status_is_known() { // Given - final String expectedAgentId = "test-agent"; + final AgentId expectedAgentId = AgentId.of("test-agent"); final long expectedTimestamp = 1000L; final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING; - final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); + final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(AgentId.unwrap(expectedAgentId), expectedTimestamp, expectedAgentLifeCycleState); when(this.hbaseOperations.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo); // When - AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(expectedAgentId, expectedTimestamp); + AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(AgentId.unwrap(expectedAgentId), expectedTimestamp); // Then assertStatus(agentStatus, expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); } @@ -87,14 +88,14 @@ public void status_should_be_set_appropriately_if_status_is_known() { @Test public void status_should_be_unknown_if_status_cannot_be_found() { // Given - final String expectedAgentId = "test-agent"; + final AgentId expectedAgentId = AgentId.of("test-agent"); final long expectedTimestamp = 0L; final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.UNKNOWN; final AgentLifeCycleBo scannedLifeCycleBo = null; when(this.hbaseOperations.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo); // When - AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(expectedAgentId, expectedTimestamp); + AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(AgentId.unwrap(expectedAgentId), expectedTimestamp); // Then assertStatus(agentStatus, expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); } @@ -102,11 +103,11 @@ public void status_should_be_unknown_if_status_cannot_be_found() { @Test public void agentInfo_should_be_populated_appropriately_if_status_is_known() { // Given - final String expectedAgentId = "test-agent"; + final AgentId expectedAgentId = AgentId.of("test-agent"); final long expectedTimestamp = 1000L; final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING; - final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); + final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(AgentId.unwrap(expectedAgentId), expectedTimestamp, expectedAgentLifeCycleState); when(this.hbaseOperations.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo); // When AgentInfo givenAgentInfo = new AgentInfo(); @@ -119,7 +120,7 @@ public void agentInfo_should_be_populated_appropriately_if_status_is_known() { assertStatus(givenStatus, expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); } - private void assertStatus(AgentStatus givenStatus, String expectedAgentId, long expectedTimestamp, AgentLifeCycleState expectedAgentLifeCycleState) { + private void assertStatus(AgentStatus givenStatus, AgentId expectedAgentId, long expectedTimestamp, AgentLifeCycleState expectedAgentLifeCycleState) { assertThat(givenStatus) .extracting(AgentStatus::getAgentId, AgentStatus::getEventTimestamp, AgentStatus::getState) .containsExactly(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); @@ -128,7 +129,7 @@ private void assertStatus(AgentStatus givenStatus, String expectedAgentId, long @Test public void agentInfo_should_be_populated_as_unknown_if_status_cannot_be_found() { // Given - final String expectedAgentId = "test-agent"; + final AgentId expectedAgentId = AgentId.of("test-agent"); final long expectedTimestamp = 0L; final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.UNKNOWN; @@ -149,11 +150,11 @@ public void agentInfo_should_be_populated_as_unknown_if_status_cannot_be_found() @Test public void agentInfos_should_be_populated_accordingly_even_with_nulls() { // Given - final String expectedAgentId = "test-agent"; + final AgentId expectedAgentId = AgentId.of("test-agent"); final long expectedTimestamp = 1000L; final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING; - final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState); + final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(AgentId.unwrap(expectedAgentId), expectedTimestamp, expectedAgentLifeCycleState); when(this.hbaseOperations.findParallel(any(TableName.class), anyList(), any(ResultsExtractor.class))).thenReturn(List.of(scannedLifeCycleBo, scannedLifeCycleBo)); AgentInfo nonNullAgentInfo = new AgentInfo(); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/SpanQueryBuilderTest.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/SpanQueryBuilderTest.java index 4a78670a1454..7a18020da00f 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/SpanQueryBuilderTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/hbase/SpanQueryBuilderTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.dao.hbase; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.web.calltree.span.SpanFilters; @@ -29,8 +30,8 @@ public void spanQuery_build() { span.setTransactionId(new TransactionId("agent", 1, 2)); span.setCollectorAcceptTime(100); span.setElapsed(200); - span.setApplicationId("appName"); - span.setAgentId("agentId"); + span.setApplicationName("appName"); + span.setAgentId(AgentId.of("agentId")); Assertions.assertEquals(spanQuery.getTransactionId(), span.getTransactionId()); Assertions.assertTrue(spanQuery.getSpanFilter().test(span)); @@ -48,7 +49,7 @@ public void spanFilter() { span.setTransactionId(txId); span.setCollectorAcceptTime(100); span.setElapsed(200); - span.setApplicationId("appName"); + span.setApplicationName("appName"); Assertions.assertTrue(filter.test(span)); } @@ -118,7 +119,7 @@ public void spanFilter_agentId() { Predicate filter = SpanFilters.agentIdFilter("agentId"); SpanBo span = new SpanBo(); - span.setAgentId("agentId"); + span.setAgentId(AgentId.of("agentId")); Assertions.assertTrue(filter.test(span)); } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/dao/memory/MemoryAlarmDao.java b/web/src/test/java/com/navercorp/pinpoint/web/dao/memory/MemoryAlarmDao.java index 506698eb83fd..f6ccfdb3fc03 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/dao/memory/MemoryAlarmDao.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/dao/memory/MemoryAlarmDao.java @@ -90,7 +90,7 @@ public List selectRuleByApplicationId(String applicationId) { List ruleList = new ArrayList<>(); for (Entry entry : alarmRule.entrySet()) { - if (entry.getValue().getApplicationId().equals(applicationId)) { + if (entry.getValue().getApplicationName().equals(applicationId)) { ruleList.add(entry.getValue()); } } @@ -103,7 +103,7 @@ public List selectApplicationId() { Set ids = new HashSet<>(); for (Entry entry : alarmRule.entrySet()) { - ids.add(entry.getValue().getApplicationId()); + ids.add(entry.getValue().getApplicationName()); } return new ArrayList<>(ids); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java index 54c02c4d8cc8..d3edd19b2171 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/filter/LinkFilterTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.filter; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.server.bo.AnnotationBo; import com.navercorp.pinpoint.common.server.bo.SpanBo; import com.navercorp.pinpoint.common.server.bo.SpanEventBo; @@ -74,22 +75,22 @@ public void fromToFilterTest() { logger.debug(linkFilter.toString()); SpanBo fromSpanBo = new SpanBo(); - fromSpanBo.setApplicationId("APP_A"); + fromSpanBo.setApplicationName("APP_A"); fromSpanBo.setServiceType(tomcatServiceType); - fromSpanBo.setAgentId("AGENT_A"); + fromSpanBo.setAgentId(AgentId.of("AGENT_A")); fromSpanBo.setSpanId(100); SpanBo toSpanBO = new SpanBo(); - toSpanBO.setApplicationId("APP_B"); + toSpanBO.setApplicationName("APP_B"); toSpanBO.setServiceType(tomcatServiceType); - toSpanBO.setAgentId("AGENT_B"); + toSpanBO.setAgentId(AgentId.of("AGENT_B")); toSpanBO.setParentSpanId(100); SpanBo spanBoC = new SpanBo(); - spanBoC.setApplicationId("APP_C"); + spanBoC.setApplicationName("APP_C"); spanBoC.setServiceType(tomcatServiceType); - spanBoC.setAgentId("AGENT_C"); + spanBoC.setAgentId(AgentId.of("AGENT_C")); Assertions.assertTrue(linkFilter.include(List.of(fromSpanBo, toSpanBO))); Assertions.assertFalse(linkFilter.include(List.of(fromSpanBo, spanBoC))); @@ -114,22 +115,22 @@ public void fromToFilterAgentTest() { logger.debug(linkFilter.toString()); SpanBo fromSpanBo = new SpanBo(); - fromSpanBo.setApplicationId("APP_A"); + fromSpanBo.setApplicationName("APP_A"); fromSpanBo.setServiceType(tomcatServiceType); - fromSpanBo.setAgentId("AGENT_A"); + fromSpanBo.setAgentId(AgentId.of("AGENT_A")); fromSpanBo.setSpanId(100); SpanBo toSpanBO = new SpanBo(); - toSpanBO.setApplicationId("APP_B"); + toSpanBO.setApplicationName("APP_B"); toSpanBO.setServiceType(tomcatServiceType); - toSpanBO.setAgentId("AGENT_B"); + toSpanBO.setAgentId(AgentId.of("AGENT_B")); toSpanBO.setParentSpanId(100); SpanBo spanBoC = new SpanBo(); - spanBoC.setApplicationId("APP_C"); + spanBoC.setApplicationName("APP_C"); spanBoC.setServiceType(tomcatServiceType); - spanBoC.setAgentId("AGENT_C"); + spanBoC.setAgentId(AgentId.of("AGENT_C")); Assertions.assertTrue(linkFilter.include(List.of(fromSpanBo, toSpanBO))); Assertions.assertFalse(linkFilter.include(List.of(fromSpanBo, spanBoC))); @@ -155,17 +156,17 @@ public void userToWasFilter() { SpanBo user_appA = new SpanBo(); user_appA.setSpanId(1); user_appA.setParentSpanId(-1); - user_appA.setApplicationId("APP_A"); + user_appA.setApplicationName("APP_A"); user_appA.setApplicationServiceType(tomcat.getCode()); SpanBo appA_appB = new SpanBo(); appA_appB.setSpanId(2); appA_appB.setParentSpanId(1); - appA_appB.setApplicationId("APP_B"); + appA_appB.setApplicationName("APP_B"); appA_appB.setApplicationServiceType(tomcat.getCode()); SpanBo appB_appA = new SpanBo(); appB_appA.setSpanId(3); appB_appA.setParentSpanId(2); - appB_appA.setApplicationId("APP_A"); + appB_appA.setApplicationName("APP_A"); appB_appA.setApplicationServiceType(tomcat.getCode()); Assertions.assertTrue(linkFilter.include(List.of(user_appA))); @@ -203,7 +204,7 @@ public void wasToUnknownFilter() { SpanBo spanBo = new SpanBo(); spanBo.setSpanId(1); spanBo.setParentSpanId(-1); - spanBo.setApplicationId("APP_A"); + spanBo.setApplicationName("APP_A"); spanBo.setApplicationServiceType(tomcat.getCode()); Assertions.assertFalse(linkFilter.include(List.of(spanBo))); @@ -237,12 +238,12 @@ public void wasToWasFilter_perfectMatch() { SpanBo user_appA = new SpanBo(); user_appA.setSpanId(1); user_appA.setParentSpanId(-1); - user_appA.setApplicationId("APP_A"); + user_appA.setApplicationName("APP_A"); user_appA.setApplicationServiceType(tomcat.getCode()); SpanBo appA_appB = new SpanBo(); appA_appB.setSpanId(2); appA_appB.setParentSpanId(1); - appA_appB.setApplicationId("APP_B"); + appA_appB.setApplicationName("APP_B"); appA_appB.setApplicationServiceType(tomcat.getCode()); Assertions.assertTrue(linkFilter.include(List.of(user_appA, appA_appB))); } @@ -267,12 +268,12 @@ public void wasToWasFilter_noMatch() { SpanBo user_appC = new SpanBo(); user_appC.setSpanId(1); user_appC.setParentSpanId(-1); - user_appC.setApplicationId("APP_C"); + user_appC.setApplicationName("APP_C"); user_appC.setApplicationServiceType(tomcat.getCode()); SpanBo appC_appB = new SpanBo(); appC_appB.setSpanId(2); appC_appB.setParentSpanId(1); - appC_appB.setApplicationId("APP_B"); + appC_appB.setApplicationName("APP_B"); appC_appB.setApplicationServiceType(tomcat.getCode()); Assertions.assertFalse(linkFilter.include(List.of(user_appC, appC_appB))); @@ -280,12 +281,12 @@ public void wasToWasFilter_noMatch() { SpanBo user_appA = new SpanBo(); user_appA.setSpanId(1); user_appA.setParentSpanId(-1); - user_appA.setApplicationId("APP_A"); + user_appA.setApplicationName("APP_A"); user_appA.setApplicationServiceType(tomcat.getCode()); SpanBo appA_appC = new SpanBo(); appA_appC.setSpanId(2); appA_appC.setParentSpanId(1); - appA_appC.setApplicationId("APP_C"); + appA_appC.setApplicationName("APP_C"); appA_appC.setApplicationServiceType(tomcat.getCode()); Assertions.assertFalse(linkFilter.include(List.of(user_appA, appA_appC))); } @@ -323,7 +324,7 @@ public void wasToWasFilter_noMatch_missingReceivingSpan() { SpanBo fromSpan = new SpanBo(); fromSpan.setSpanId(1); fromSpan.setParentSpanId(-1); - fromSpan.setApplicationId("APP_A"); + fromSpan.setApplicationName("APP_A"); fromSpan.setApplicationServiceType(tomcat.getCode()); AnnotationBo rpcAnnotation = AnnotationBo.of(RPC_ANNOTATION_CODE, rpcUrl); SpanEventBo rpcSpanEvent = new SpanEventBo(); @@ -372,7 +373,7 @@ public void wasToBackendFilter() { logger.debug(linkFilter.toString()); SpanBo matchingSpan = new SpanBo(); - matchingSpan.setApplicationId("APP_A"); + matchingSpan.setApplicationName("APP_A"); matchingSpan.setApplicationServiceType(tomcat.getCode()); SpanEventBo spanEventDestinationA = new SpanEventBo(); spanEventDestinationA.setDestinationId(destinationA); @@ -381,7 +382,7 @@ public void wasToBackendFilter() { Assertions.assertTrue(linkFilter.include(List.of(matchingSpan))); SpanBo unmatchingSpan = new SpanBo(); - unmatchingSpan.setApplicationId("APP_A"); + unmatchingSpan.setApplicationName("APP_A"); unmatchingSpan.setApplicationServiceType(tomcat.getCode()); SpanEventBo spanEventDestinationB = new SpanEventBo(); spanEventDestinationB.setDestinationId(destinationB); @@ -392,7 +393,7 @@ public void wasToBackendFilter() { Assertions.assertTrue(linkFilter.include(List.of(matchingSpan, unmatchingSpan))); SpanBo bothSpan = new SpanBo(); - bothSpan.setApplicationId("APP_A"); + bothSpan.setApplicationName("APP_A"); bothSpan.setApplicationServiceType(tomcat.getCode()); bothSpan.addSpanEventBoList(List.of(spanEventDestinationA, spanEventDestinationB)); Assertions.assertTrue(linkFilter.include(List.of(bothSpan))); @@ -419,7 +420,7 @@ public void wasToQueueFilter() { logger.debug(linkFilter.toString()); SpanBo matchingSpan = new SpanBo(); - matchingSpan.setApplicationId("APP_A"); + matchingSpan.setApplicationName("APP_A"); matchingSpan.setApplicationServiceType(tomcat.getCode()); SpanEventBo spanEventDestinationA = new SpanEventBo(); spanEventDestinationA.setDestinationId(messageQueueA); @@ -428,7 +429,7 @@ public void wasToQueueFilter() { Assertions.assertTrue(linkFilter.include(List.of(matchingSpan))); SpanBo unmatchingSpan = new SpanBo(); - unmatchingSpan.setApplicationId("APP_A"); + unmatchingSpan.setApplicationName("APP_A"); unmatchingSpan.setApplicationServiceType(tomcat.getCode()); SpanEventBo spanEventDestinationB = new SpanEventBo(); spanEventDestinationB.setDestinationId(messageQueueB); @@ -439,7 +440,7 @@ public void wasToQueueFilter() { Assertions.assertTrue(linkFilter.include(List.of(matchingSpan, unmatchingSpan))); SpanBo bothSpan = new SpanBo(); - bothSpan.setApplicationId("APP_A"); + bothSpan.setApplicationName("APP_A"); bothSpan.setApplicationServiceType(tomcat.getCode()); bothSpan.addSpanEventBoList(List.of(spanEventDestinationA, spanEventDestinationB)); Assertions.assertTrue(linkFilter.include(List.of(bothSpan))); @@ -466,13 +467,13 @@ public void queueToWasFilter() { logger.debug(linkFilter.toString()); SpanBo matchingSpan = new SpanBo(); - matchingSpan.setApplicationId("APP_A"); + matchingSpan.setApplicationName("APP_A"); matchingSpan.setApplicationServiceType(tomcat.getCode()); matchingSpan.setAcceptorHost(messageQueueA); Assertions.assertTrue(linkFilter.include(List.of(matchingSpan))); SpanBo unmatchingSpan = new SpanBo(); - unmatchingSpan.setApplicationId("APP_A"); + unmatchingSpan.setApplicationName("APP_A"); unmatchingSpan.setApplicationServiceType(tomcat.getCode()); unmatchingSpan.setAcceptorHost(messageQueueB); Assertions.assertFalse(linkFilter.include(List.of(unmatchingSpan))); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/mapper/FilteringSpanDecoderTest.java b/web/src/test/java/com/navercorp/pinpoint/web/mapper/FilteringSpanDecoderTest.java index b7ff32066a7d..8535bbd631dc 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/mapper/FilteringSpanDecoderTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/mapper/FilteringSpanDecoderTest.java @@ -130,7 +130,7 @@ private GetTraceInfo createGetTraceInfo() { } private GetTraceInfo createGetTraceInfo(SpanBo spanBo) { - return new GetTraceInfo(spanBo.getTransactionId(), new SpanHint(spanBo.getCollectorAcceptTime(), spanBo.getElapsed(), spanBo.getApplicationId())); + return new GetTraceInfo(spanBo.getTransactionId(), new SpanHint(spanBo.getCollectorAcceptTime(), spanBo.getElapsed(), spanBo.getApplicationName())); } private SpanDecoder createMockSpanDecoder() { @@ -157,7 +157,7 @@ private static SpanBo createSpanBo(String applicationId) { spanBo.setElapsed(createElapsed()); if (applicationId != null) { - spanBo.setApplicationId("appName"); + spanBo.setApplicationName("appName"); } return spanBo; diff --git a/web/src/test/java/com/navercorp/pinpoint/web/service/AdminServiceImplTest.java b/web/src/test/java/com/navercorp/pinpoint/web/service/AdminServiceImplTest.java index 68030252e201..9aef2ee9491d 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/service/AdminServiceImplTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/service/AdminServiceImplTest.java @@ -1,7 +1,7 @@ package com.navercorp.pinpoint.web.service; +import com.navercorp.pinpoint.common.id.ApplicationId; import com.navercorp.pinpoint.common.trace.ServiceType; -import com.navercorp.pinpoint.web.dao.ApplicationIndexDao; import com.navercorp.pinpoint.web.vo.Application; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -11,10 +11,10 @@ import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; @@ -31,64 +31,52 @@ public class AdminServiceImplTest { final String APPLICATION_NAME2 = "TEST_APP2"; final String APPLICATION_NAME3 = "TEST_APP3"; + final ApplicationId APPLICATION_UUID1 = ApplicationId.of(new UUID(1, 1)); + final ApplicationId APPLICATION_UUID2 = ApplicationId.of(new UUID(2, 2)); + final ApplicationId APPLICATION_UUID3 = ApplicationId.of(new UUID(3, 3)); + AdminService adminService; @Mock - ApplicationIndexDao applicationIndexDao; + ApplicationService applicationService; @Mock AgentInfoService agentInfoService; @BeforeEach public void setUp() { - adminService = new AdminServiceImpl(applicationIndexDao, agentInfoService); - } - - @Test - public void constructorRequireNonNullTest() { - - assertThatThrownBy(() -> new AdminServiceImpl(null, agentInfoService)) - .isInstanceOf(NullPointerException.class) - .hasMessage("applicationIndexDao"); - - assertThatThrownBy(() -> new AdminServiceImpl(applicationIndexDao, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("agentInfoService"); - - assertThatThrownBy(() -> new AdminServiceImpl(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("applicationIndexDao"); + adminService = new AdminServiceImpl(applicationService, agentInfoService); } @Test public void removeApplicationName() { // given - doNothing().when(applicationIndexDao).deleteApplicationName(APPLICATION_NAME1); + doNothing().when(applicationService).deleteApplication(APPLICATION_UUID1); // when - adminService.removeApplicationName(APPLICATION_NAME1); + adminService.removeApplicationName(APPLICATION_UUID1); // then - verify(applicationIndexDao).deleteApplicationName(APPLICATION_NAME1); + verify(applicationService).deleteApplication(APPLICATION_UUID1); } @Test public void removeAgentId() { // given - doNothing().when(applicationIndexDao).deleteAgentId(APPLICATION_NAME1, AGENT_ID1); + doNothing().when(applicationService).deleteAgent(APPLICATION_UUID1, AGENT_ID1); // when - adminService.removeAgentId(APPLICATION_NAME1, AGENT_ID1); + adminService.removeAgentId(APPLICATION_UUID1, AGENT_ID1); // then - verify(applicationIndexDao).deleteAgentId(APPLICATION_NAME1, AGENT_ID1); + verify(applicationService).deleteAgent(APPLICATION_UUID1, AGENT_ID1); } @Test public void whenApplicationDoesNotHaveAnyAgentIdsGetAgentIdMapReturnsEmptyMap() { // given List emptyApplicationList = List.of(); - when(applicationIndexDao.selectAllApplicationNames()).thenReturn(emptyApplicationList); + when(applicationService.getApplications()).thenReturn(emptyApplicationList); // when Map> agentIdMap = adminService.getAgentIdMap(); @@ -100,17 +88,17 @@ public void whenApplicationDoesNotHaveAnyAgentIdsGetAgentIdMapReturnsEmptyMap() @Test public void testDuplicateAgentIdMap() { // given - when(applicationIndexDao.selectAllApplicationNames()) + when(applicationService.getApplications()) .thenReturn(List.of( - new Application(APPLICATION_NAME1, ServiceType.UNDEFINED), - new Application(APPLICATION_NAME2, ServiceType.UNDEFINED), - new Application(APPLICATION_NAME3, ServiceType.UNDEFINED))); + new Application(APPLICATION_UUID1, APPLICATION_NAME1, ServiceType.UNDEFINED), + new Application(APPLICATION_UUID2, APPLICATION_NAME2, ServiceType.UNDEFINED), + new Application(APPLICATION_UUID3, APPLICATION_NAME3, ServiceType.UNDEFINED))); - when(applicationIndexDao.selectAgentIds(eq(APPLICATION_NAME1))) + when(applicationService.getAgents(eq(APPLICATION_UUID1))) .thenReturn(List.of(AGENT_ID1, AGENT_ID2, AGENT_ID3)); - when(applicationIndexDao.selectAgentIds(eq(APPLICATION_NAME2))) + when(applicationService.getAgents(eq(APPLICATION_UUID2))) .thenReturn(List.of(AGENT_ID2, AGENT_ID3)); - when(applicationIndexDao.selectAgentIds(eq(APPLICATION_NAME3))) + when(applicationService.getAgents(eq(APPLICATION_UUID3))) .thenReturn(List.of(AGENT_ID1)); // then @@ -122,13 +110,13 @@ public void testDuplicateAgentIdMap() { assertThat(duplicateAgentIdMap.get(AGENT_ID3)).hasSize(2); // check the application names - List applicationNamesOfAgentId1 = duplicateAgentIdMap.get(AGENT_ID1).stream().map(Application::getName).collect(Collectors.toList()); + List applicationNamesOfAgentId1 = duplicateAgentIdMap.get(AGENT_ID1).stream().map(Application::name).collect(Collectors.toList()); assertThat(applicationNamesOfAgentId1).containsAll(List.of(APPLICATION_NAME1, APPLICATION_NAME3)); - List applicationNamesOfAgentId2 = duplicateAgentIdMap.get(AGENT_ID2).stream().map(Application::getName).collect(Collectors.toList()); + List applicationNamesOfAgentId2 = duplicateAgentIdMap.get(AGENT_ID2).stream().map(Application::name).collect(Collectors.toList()); assertThat(applicationNamesOfAgentId2).containsAll(List.of(APPLICATION_NAME1, APPLICATION_NAME2)); - List applicationNamesOfAgentId3 = duplicateAgentIdMap.get(AGENT_ID3).stream().map(Application::getName).collect(Collectors.toList()); + List applicationNamesOfAgentId3 = duplicateAgentIdMap.get(AGENT_ID3).stream().map(Application::name).collect(Collectors.toList()); assertThat(applicationNamesOfAgentId3).containsAll(List.of(APPLICATION_NAME1, APPLICATION_NAME2)); } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImplTest.java b/web/src/test/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImplTest.java index e320bc789eab..44236021b531 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImplTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/service/ApdexScoreServiceImplTest.java @@ -51,7 +51,7 @@ public void mockResponseDao() { } private ResponseTime createResponseTime(long timeStamp) { - ResponseTime responseTime = new ResponseTime(testApplication.getName(), testApplication.getServiceType(), timeStamp); + ResponseTime responseTime = new ResponseTime(testApplication.name(), testApplication.serviceType(), timeStamp); for (String agentId : agentIdList) { responseTime.addResponseTime(agentId, createTestHistogram(1, 2, 3, 4, 5)); } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/service/HeatMapServiceImplTest.java b/web/src/test/java/com/navercorp/pinpoint/web/service/HeatMapServiceImplTest.java index 3ebafa62a4f5..3932b530b172 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/service/HeatMapServiceImplTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/service/HeatMapServiceImplTest.java @@ -2,7 +2,6 @@ import com.navercorp.pinpoint.common.profiler.util.TransactionId; import com.navercorp.pinpoint.common.server.bo.SpanBo; -import com.navercorp.pinpoint.web.dao.ApplicationTraceIndexDao; import com.navercorp.pinpoint.web.dao.TraceDao; import com.navercorp.pinpoint.web.scatter.DragAreaQuery; import com.navercorp.pinpoint.web.vo.LimitedScanResult; @@ -35,57 +34,57 @@ public class HeatMapServiceImplTest { @Test public void legacyCompatibilityCheckPassTest() { - ApplicationTraceIndexDao applicationTraceIndexDao = mock(ApplicationTraceIndexDao.class); + ApplicationTraceIndexService applicationTraceIndexService = mock(ApplicationTraceIndexService.class); TraceDao traceDao = mock(TraceDao.class); LimitedScanResult> scanResult = new LimitedScanResult<>(1, dotMataData()); - when(applicationTraceIndexDao.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) + when(applicationTraceIndexService.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) .thenReturn(scanResult); - HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexDao, spanService, traceDao); + HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexService, spanService, traceDao); Assertions.assertSame(scanResult, heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)); } @Test public void legacyCompatibilityCheckTest() { - ApplicationTraceIndexDao applicationTraceIndexDao = mock(ApplicationTraceIndexDao.class); + ApplicationTraceIndexService applicationTraceIndexService = mock(ApplicationTraceIndexService.class); TraceDao traceDao = mock(TraceDao.class); LimitedScanResult> scanResult = new LimitedScanResult<>(1, legacyDotMataData()); - when(applicationTraceIndexDao.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) + when(applicationTraceIndexService.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) .thenReturn(scanResult); when(traceDao.selectSpans(any())).thenReturn(matchingSpanData()); - HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexDao, spanService, traceDao); + HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexService, spanService, traceDao); heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT); Assertions.assertNotSame(scanResult, heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)); } @Test public void legacyCompatibilityCheckMoreSpanTest() { - ApplicationTraceIndexDao applicationTraceIndexDao = mock(ApplicationTraceIndexDao.class); + ApplicationTraceIndexService applicationTraceIndexService = mock(ApplicationTraceIndexService.class); TraceDao traceDao = mock(TraceDao.class); LimitedScanResult> scanResult = new LimitedScanResult<>(1, legacyDotMataData()); - when(applicationTraceIndexDao.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) + when(applicationTraceIndexService.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)) .thenReturn(scanResult); when(traceDao.selectSpans(any())).thenReturn(moreSpanData()); - HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexDao, spanService, traceDao); + HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexService, spanService, traceDao); heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT); Assertions.assertNotSame(scanResult, heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)); } @Test public void legacyCompatibilityCheckErrorTest() { - ApplicationTraceIndexDao applicationTraceIndexDao = mock(ApplicationTraceIndexDao.class); + ApplicationTraceIndexService applicationTraceIndexService = mock(ApplicationTraceIndexService.class); TraceDao traceDao = mock(TraceDao.class); LimitedScanResult> scanResult = new LimitedScanResult<>(1, legacyDotMataData()); - when(applicationTraceIndexDao.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)).thenReturn(scanResult); + when(applicationTraceIndexService.scanScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)).thenReturn(scanResult); when(traceDao.selectSpans(any())).thenReturn(lessSpanData()); - HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexDao, spanService, traceDao); + HeatMapService heatMapService = new HeatMapServiceImpl(applicationTraceIndexService, spanService, traceDao); Assertions.assertThrows(IllegalStateException.class, () -> heatMapService.dragScatterDataV2(APPLICATION_NAME, dragAreaQuery, LIMIT)); } diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByApplicationTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByApplicationTest.java index 81cc46e47b50..f827290fcc98 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByApplicationTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByApplicationTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.vo; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.web.vo.agent.AgentAndStatus; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; import com.navercorp.pinpoint.web.vo.agent.AgentStatusFilters; @@ -59,7 +60,7 @@ private static AgentAndStatus createAgentInfo(String applicationName, String age private static AgentAndStatus createAgentInfo(String applicationName, String agentId, String hostname, boolean container, long startTimestamp) { AgentInfo agentInfo = new AgentInfo(); agentInfo.setApplicationName(applicationName); - agentInfo.setAgentId(agentId); + agentInfo.setAgentId(AgentId.of(agentId)); agentInfo.setHostName(hostname); agentInfo.setContainer(container); agentInfo.setStartTimestamp(startTimestamp); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByHostTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByHostTest.java index 5b0f629f6bea..4c4a0359a3f3 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByHostTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/AgentsMapByHostTest.java @@ -1,5 +1,6 @@ package com.navercorp.pinpoint.web.vo; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.web.hyperlink.HyperLinkFactory; import com.navercorp.pinpoint.web.vo.agent.AgentAndStatus; import com.navercorp.pinpoint.web.vo.agent.AgentInfo; @@ -70,7 +71,7 @@ private static AgentAndStatus createAgentInfo(String applicationName, String age private static AgentAndStatus createAgentInfo(String applicationName, String agentId, String hostname, boolean container, long startTimestamp) { AgentInfo agentInfo = new AgentInfo(); agentInfo.setApplicationName(applicationName); - agentInfo.setAgentId(agentId); + agentInfo.setAgentId(AgentId.of(agentId)); agentInfo.setHostName(hostname); agentInfo.setContainer(container); agentInfo.setStartTimestamp(startTimestamp); diff --git a/web/src/test/java/com/navercorp/pinpoint/web/vo/callstacks/RecordFactoryTest.java b/web/src/test/java/com/navercorp/pinpoint/web/vo/callstacks/RecordFactoryTest.java index c7bb0573cac3..dbcdd92a41e0 100644 --- a/web/src/test/java/com/navercorp/pinpoint/web/vo/callstacks/RecordFactoryTest.java +++ b/web/src/test/java/com/navercorp/pinpoint/web/vo/callstacks/RecordFactoryTest.java @@ -16,6 +16,7 @@ package com.navercorp.pinpoint.web.vo.callstacks; +import com.navercorp.pinpoint.common.id.AgentId; import com.navercorp.pinpoint.common.profiler.trace.AnnotationKeyRegistry; import com.navercorp.pinpoint.common.profiler.trace.TraceMetadataLoader; import com.navercorp.pinpoint.common.profiler.util.TransactionId; @@ -218,9 +219,9 @@ public void testMakeRecord() { .build(); SpanBo.Builder spanBoBuilder = new SpanBo.Builder(8174884636707391L) .setVersion(1) - .setAgentId("express-node-sample-id") + .setAgentId(AgentId.of("express-node-sample-id")) .setAgentName("") - .setApplicationId("express-node-sample-name") + .setApplicationName("express-node-sample-name") .setAgentStartTime(1670293953108L) .setTransactionId(new TransactionId("express-node-sample-id", 1670293953108L, 30)) .setParentSpanId(-1) diff --git a/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmService.java b/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmService.java index 36ff3694fc71..fbebd1f38f2f 100644 --- a/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmService.java +++ b/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmService.java @@ -16,7 +16,7 @@ */ package com.navercorp.pinpoint.web.webhook.service; -import com.navercorp.pinpoint.common.server.alram.event.DeleteRuleEvent; +import com.navercorp.pinpoint.common.server.alarm.event.DeleteRuleEvent; import java.util.List; diff --git a/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmServiceImpl.java b/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmServiceImpl.java index 6543ccd3f32b..eedec0421786 100644 --- a/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmServiceImpl.java +++ b/webhook/src/main/java/com/navercorp/pinpoint/web/webhook/service/WebhookAlarmServiceImpl.java @@ -17,7 +17,7 @@ package com.navercorp.pinpoint.web.webhook.service; -import com.navercorp.pinpoint.common.server.alram.event.DeleteRuleEvent; +import com.navercorp.pinpoint.common.server.alarm.event.DeleteRuleEvent; import com.navercorp.pinpoint.web.webhook.dao.WebhookSendInfoDao; import com.navercorp.pinpoint.web.webhook.model.WebhookSendInfo; import org.apache.logging.log4j.LogManager;