未验证 提交 f676aece 编写于 作者: K kezhenxu94 提交者: GitHub

Remove unused codes, close leaked I/O stream (#4325)

### Motivation:

Clean up unused codes and migrate to JDK8.

### Modifications:

- Remove unused codes.

- Close unclosed I/O stream.

- Remove meaningless comments.

### Result:

- No unnecessary codes concerns.

- No resources leak.
上级 e44bc362
......@@ -18,6 +18,7 @@
package org.apache.skywalking.apm.agent.core.conf;
import java.nio.charset.StandardCharsets;
import org.apache.skywalking.apm.agent.core.boot.AgentPackageNotFoundException;
import org.apache.skywalking.apm.agent.core.boot.AgentPackagePath;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
......@@ -36,9 +37,9 @@ import java.util.*;
*/
public class SnifferConfigInitializer {
private static final ILog logger = LogManager.getLogger(SnifferConfigInitializer.class);
private static String SPECIFIED_CONFIG_PATH = "skywalking_config";
private static String DEFAULT_CONFIG_FILE_NAME = "/config/agent.config";
private static String ENV_KEY_PREFIX = "skywalking.";
private static final String SPECIFIED_CONFIG_PATH = "skywalking_config";
private static final String DEFAULT_CONFIG_FILE_NAME = "/config/agent.config";
private static final String ENV_KEY_PREFIX = "skywalking.";
private static boolean IS_INIT_COMPLETED = false;
/**
......@@ -52,16 +53,12 @@ public class SnifferConfigInitializer {
* <p>
* At the end, `agent.service_name` and `collector.servers` must not be blank.
*/
public static void initialize(String agentOptions) throws ConfigNotFoundException, AgentPackageNotFoundException {
InputStreamReader configFileStream;
try {
configFileStream = loadConfig();
public static void initialize(String agentOptions) {
try (final InputStreamReader configFileStream = loadConfig()) {
Properties properties = new Properties();
properties.load(configFileStream);
for (String key : properties.stringPropertyNames()) {
String value = (String)properties.get(key);
//replace the key's value. properties.replace(key,value) in jdk8+
properties.put(key, PropertyPlaceholderHelper.INSTANCE.replacePlaceholders(value, properties));
}
ConfigInitializer.initialize(properties, Config.class);
......@@ -114,8 +111,8 @@ public class SnifferConfigInitializer {
}
private static List<List<String>> parseAgentOptions(String agentOptions) {
List<List<String>> options = new ArrayList<List<String>>();
List<String> terms = new ArrayList<String>();
List<List<String>> options = new ArrayList<>();
List<String> terms = new ArrayList<>();
boolean isInQuotes = false;
StringBuilder currentTerm = new StringBuilder();
for (char c : agentOptions.toCharArray()) {
......@@ -129,7 +126,7 @@ public class SnifferConfigInitializer {
currentTerm = new StringBuilder();
options.add(terms);
terms = new ArrayList<String>();
terms = new ArrayList<>();
} else {
currentTerm.append(c);
}
......@@ -154,9 +151,7 @@ public class SnifferConfigInitializer {
private static void overrideConfigBySystemProp() throws IllegalAccessException {
Properties properties = new Properties();
Properties systemProperties = System.getProperties();
Iterator<Map.Entry<Object, Object>> entryIterator = systemProperties.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Object, Object> prop = entryIterator.next();
for (final Map.Entry<Object, Object> prop : systemProperties.entrySet()) {
String key = prop.getKey().toString();
if (key.startsWith(ENV_KEY_PREFIX)) {
String realKey = key.substring(ENV_KEY_PREFIX.length());
......@@ -174,20 +169,17 @@ public class SnifferConfigInitializer {
*
* @return the config file {@link InputStream}, or null if not needEnhance.
*/
private static InputStreamReader loadConfig() throws AgentPackageNotFoundException, ConfigNotFoundException, ConfigReadFailedException {
String specifiedConfigPath = System.getProperties().getProperty(SPECIFIED_CONFIG_PATH);
private static InputStreamReader loadConfig() throws AgentPackageNotFoundException, ConfigNotFoundException {
String specifiedConfigPath = System.getProperty(SPECIFIED_CONFIG_PATH);
File configFile = StringUtil.isEmpty(specifiedConfigPath) ? new File(AgentPackagePath.getPath(), DEFAULT_CONFIG_FILE_NAME) : new File(specifiedConfigPath);
if (configFile.exists() && configFile.isFile()) {
try {
logger.info("Config file found in {}.", configFile);
return new InputStreamReader(new FileInputStream(configFile), "UTF-8");
return new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8);
} catch (FileNotFoundException e) {
throw new ConfigNotFoundException("Failed to load agent.config", e);
} catch (UnsupportedEncodingException e) {
throw new ConfigReadFailedException("Failed to load agent.config", e);
}
}
throw new ConfigNotFoundException("Failed to load agent.config.");
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.agent.core.context;
/**
* The <code>Injectable</code> represents a provider, which gives the reference of {@link ContextCarrier} and peer
* for the agent core, for cross-process propagation.
*
* @author wusheng
*/
public interface Injectable {
ContextCarrier getCarrier();
/**
* @return peer, represent ipv4, ipv6, hostname, or cluster addresses list.
*/
String getPeer();
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.agent.core.context;
/**
* @author wusheng
*/
public class TraceContextCarrierItem extends CarrierItem {
private static final String HEAD_NAME = "Trace-Context";
public TraceContextCarrierItem(String headValue, CarrierItem next) {
super(HEAD_NAME, headValue, next);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.agent.core.plugin.interceptor;
public class InterceptorException extends RuntimeException {
private static final long serialVersionUID = 7846035239994885019L;
public InterceptorException(String message) {
super(message);
}
public InterceptorException(String message, Throwable cause) {
super(message, cause);
}
}
......@@ -21,9 +21,7 @@ package org.apache.skywalking.apm.agent.core.plugin.loader;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
......@@ -33,6 +31,7 @@ import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import lombok.RequiredArgsConstructor;
import org.apache.skywalking.apm.agent.core.boot.AgentPackageNotFoundException;
import org.apache.skywalking.apm.agent.core.boot.AgentPackagePath;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
......@@ -48,7 +47,10 @@ import org.apache.skywalking.apm.agent.core.plugin.PluginBootstrap;
public class AgentClassLoader extends ClassLoader {
static {
tryRegisterAsParallelCapable();
/*
* Try to solve the classloader dead lock. See https://github.com/apache/skywalking/pull/2016
*/
registerAsParallelCapable();
}
private static final ILog logger = LogManager.getLogger(AgentClassLoader.class);
......@@ -61,35 +63,14 @@ public class AgentClassLoader extends ClassLoader {
private List<Jar> allJars;
private ReentrantLock jarScanLock = new ReentrantLock();
/**
* Functional Description: solve the classloader dead lock when jvm start
* only support JDK7+, since ParallelCapable appears in JDK7+
*/
private static void tryRegisterAsParallelCapable() {
Method[] methods = ClassLoader.class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String methodName = method.getName();
if ("registerAsParallelCapable".equalsIgnoreCase(methodName)) {
try {
method.setAccessible(true);
method.invoke(null);
} catch (Exception e) {
logger.warn(e, "can not invoke ClassLoader.registerAsParallelCapable()");
}
return;
}
}
}
public static AgentClassLoader getDefault() {
return DEFAULT_LOADER;
}
/**
* Init the default
* Init the default class loader.
*
* @throws AgentPackageNotFoundException
* @throws AgentPackageNotFoundException if agent package is not found.
*/
public static void initDefaultLoader() throws AgentPackageNotFoundException {
if (DEFAULT_LOADER == null) {
......@@ -104,7 +85,7 @@ public class AgentClassLoader extends ClassLoader {
public AgentClassLoader(ClassLoader parent) throws AgentPackageNotFoundException {
super(parent);
File agentDictionary = AgentPackagePath.getPath();
classpath = new LinkedList<File>();
classpath = new LinkedList<>();
classpath.add(new File(agentDictionary, "plugins"));
classpath.add(new File(agentDictionary, "activations"));
}
......@@ -115,38 +96,23 @@ public class AgentClassLoader extends ClassLoader {
String path = name.replace('.', '/').concat(".class");
for (Jar jar : allJars) {
JarEntry entry = jar.jarFile.getJarEntry(path);
if (entry != null) {
try {
URL classFileUrl = new URL("jar:file:" + jar.sourceFile.getAbsolutePath() + "!/" + path);
byte[] data = null;
BufferedInputStream is = null;
ByteArrayOutputStream baos = null;
try {
is = new BufferedInputStream(classFileUrl.openStream());
baos = new ByteArrayOutputStream();
int ch = 0;
while ((ch = is.read()) != -1) {
baos.write(ch);
}
data = baos.toByteArray();
} finally {
if (is != null)
try {
is.close();
} catch (IOException ignored) {
}
if (baos != null)
try {
baos.close();
} catch (IOException ignored) {
}
if (entry == null) {
continue;
}
try {
URL classFileUrl = new URL("jar:file:" + jar.sourceFile.getAbsolutePath() + "!/" + path);
byte[] data;
try (final BufferedInputStream is = new BufferedInputStream(classFileUrl.openStream());
final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int ch;
while ((ch = is.read()) != -1) {
baos.write(ch);
}
return defineClass(name, data, 0, data.length);
} catch (MalformedURLException e) {
logger.error(e, "find class fail.");
} catch (IOException e) {
logger.error(e, "find class fail.");
data = baos.toByteArray();
}
return defineClass(name, data, 0, data.length);
} catch (IOException e) {
logger.error(e, "find class fail.");
}
}
throw new ClassNotFoundException("Can't find " + name);
......@@ -160,8 +126,7 @@ public class AgentClassLoader extends ClassLoader {
if (entry != null) {
try {
return new URL("jar:file:" + jar.sourceFile.getAbsolutePath() + "!/" + name);
} catch (MalformedURLException e) {
continue;
} catch (MalformedURLException ignored) {
}
}
}
......@@ -170,7 +135,7 @@ public class AgentClassLoader extends ClassLoader {
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
List<URL> allResources = new LinkedList<URL>();
List<URL> allResources = new LinkedList<>();
List<Jar> allJars = getAllJars();
for (Jar jar : allJars) {
JarEntry entry = jar.jarFile.getJarEntry(name);
......@@ -198,15 +163,10 @@ public class AgentClassLoader extends ClassLoader {
jarScanLock.lock();
try {
if (allJars == null) {
allJars = new LinkedList<Jar>();
allJars = new LinkedList<>();
for (File path : classpath) {
if (path.exists() && path.isDirectory()) {
String[] jarFileNames = path.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
String[] jarFileNames = path.list((dir, name) -> name.endsWith(".jar"));
for (String fileName : jarFileNames) {
try {
File file = new File(path, fileName);
......@@ -228,13 +188,9 @@ public class AgentClassLoader extends ClassLoader {
return allJars;
}
private class Jar {
private JarFile jarFile;
private File sourceFile;
private Jar(JarFile jarFile, File sourceFile) {
this.jarFile = jarFile;
this.sourceFile = sourceFile;
}
@RequiredArgsConstructor
private static class Jar {
private final JarFile jarFile;
private final File sourceFile;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.agent.core.remote;
/**
* The <code>RESTResponseStatusError</code> represents the REST-Service discovery got an unexpected response code.
* Most likely, the response code is not 200.
*
* @author wusheng
*/
class RESTResponseStatusError extends Exception {
RESTResponseStatusError(int responseCode) {
super("Unexpected service response code: " + responseCode);
}
}
......@@ -45,7 +45,6 @@ import static org.apache.skywalking.apm.agent.core.remote.GRPCChannelStatus.CONN
@DefaultImplementor
public class TraceSegmentServiceClient implements BootService, IConsumer<TraceSegment>, TracingContextListener, GRPCChannelListener {
private static final ILog logger = LogManager.getLogger(TraceSegmentServiceClient.class);
private static final int TIMEOUT = 30 * 1000;
private long lastLogTime;
private long segmentUplinkedCounter;
......@@ -55,27 +54,27 @@ public class TraceSegmentServiceClient implements BootService, IConsumer<TraceSe
private volatile GRPCChannelStatus status = GRPCChannelStatus.DISCONNECT;
@Override
public void prepare() throws Throwable {
public void prepare() {
ServiceManager.INSTANCE.findService(GRPCChannelManager.class).addChannelListener(this);
}
@Override
public void boot() throws Throwable {
public void boot() {
lastLogTime = System.currentTimeMillis();
segmentUplinkedCounter = 0;
segmentAbandonedCounter = 0;
carrier = new DataCarrier<TraceSegment>(CHANNEL_SIZE, BUFFER_SIZE);
carrier = new DataCarrier<>(CHANNEL_SIZE, BUFFER_SIZE);
carrier.setBufferStrategy(BufferStrategy.IF_POSSIBLE);
carrier.consume(this, 1);
}
@Override
public void onComplete() throws Throwable {
public void onComplete() {
TracingContext.ListenerManager.add(this);
}
@Override
public void shutdown() throws Throwable {
public void shutdown() {
TracingContext.ListenerManager.remove(this);
carrier.shutdownConsumers();
}
......
......@@ -18,7 +18,6 @@
package org.apache.skywalking.apm.agent;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.List;
import net.bytebuddy.ByteBuddy;
......@@ -33,7 +32,6 @@ import net.bytebuddy.utility.JavaModule;
import org.apache.skywalking.apm.agent.core.boot.AgentPackageNotFoundException;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.ConfigNotFoundException;
import org.apache.skywalking.apm.agent.core.conf.SnifferConfigInitializer;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
......@@ -60,21 +58,14 @@ public class SkyWalkingAgent {
/**
* Main entrance. Use byte-buddy transform to enhance all classes, which define in plugins.
*
* @param agentArgs
* @param instrumentation
* @throws PluginException
*/
public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException, IOException {
public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException {
final PluginFinder pluginFinder;
try {
SnifferConfigInitializer.initialize(agentArgs);
pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins());
} catch (ConfigNotFoundException ce) {
logger.error(ce, "SkyWalking agent could not find config. Shutting down.");
return;
} catch (AgentPackageNotFoundException ape) {
logger.error(ape, "Locate agent.jar failure. Shutting down.");
return;
......@@ -96,7 +87,7 @@ public class SkyWalkingAgent {
.or(nameContains(".reflectasm."))
.or(nameStartsWith("sun.reflect"))
.or(allSkyWalkingAgentExcludeToolkit())
.or(ElementMatchers.<TypeDescription>isSynthetic()));
.or(ElementMatchers.isSynthetic()));
JDK9ModuleExporter.EdgeClasses edgeClasses = new JDK9ModuleExporter.EdgeClasses();
try {
......@@ -126,11 +117,7 @@ public class SkyWalkingAgent {
logger.error(e, "Skywalking agent boot failure.");
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override public void run() {
ServiceManager.INSTANCE.shutdown();
}
}, "skywalking service shutdown thread"));
Runtime.getRuntime().addShutdownHook(new Thread(ServiceManager.INSTANCE::shutdown, "skywalking service shutdown thread"));
}
private static class Transformer implements AgentBuilder.Transformer {
......
......@@ -18,9 +18,7 @@
package org.apache.skywalking.apm.plugin.trace.ignore;
import org.apache.skywalking.apm.agent.core.boot.AgentPackageNotFoundException;
import org.apache.skywalking.apm.agent.core.boot.OverrideImplementor;
import org.apache.skywalking.apm.agent.core.conf.ConfigNotFoundException;
import org.apache.skywalking.apm.agent.core.context.AbstractTracerContext;
import org.apache.skywalking.apm.agent.core.context.ContextManagerExtendService;
import org.apache.skywalking.apm.agent.core.context.IgnoredTracerContext;
......@@ -40,8 +38,6 @@ public class TraceIgnoreExtendService extends ContextManagerExtendService {
private static final ILog LOGGER = LogManager.getLogger(TraceIgnoreExtendService.class);
private static final String DEFAULT_PATH_SEPARATOR = "/";
private static final String PATTERN_SEPARATOR = ",";
private TracePathMatcher pathMatcher = new FastPathMatcher();
......@@ -50,13 +46,9 @@ public class TraceIgnoreExtendService extends ContextManagerExtendService {
@Override
public void boot() {
try {
IgnoreConfigInitializer.initialize();
if (StringUtil.isNotEmpty(IgnoreConfig.Trace.IGNORE_PATH)) {
patterns = IgnoreConfig.Trace.IGNORE_PATH.split(PATTERN_SEPARATOR);
}
} catch (ConfigNotFoundException | AgentPackageNotFoundException e) {
LOGGER.error("trace ignore config init error", e);
IgnoreConfigInitializer.initialize();
if (StringUtil.isNotEmpty(IgnoreConfig.Trace.IGNORE_PATH)) {
patterns = IgnoreConfig.Trace.IGNORE_PATH.split(PATTERN_SEPARATOR);
}
}
......
......@@ -30,8 +30,8 @@ import org.apache.skywalking.apm.util.*;
*/
public class IgnoreConfigInitializer {
private static final ILog LOGGER = LogManager.getLogger(IgnoreConfigInitializer.class);
private static String CONFIG_FILE_NAME = "/config/apm-trace-ignore-plugin.config";
private static String ENV_KEY_PREFIX = "skywalking.";
private static final String CONFIG_FILE_NAME = "/config/apm-trace-ignore-plugin.config";
private static final String ENV_KEY_PREFIX = "skywalking.";
/**
* Try to locate `apm-trace-ignore-plugin.config`, which should be in the /optional-plugins/apm-trace-ignore-plugin/
......@@ -42,16 +42,12 @@ public class IgnoreConfigInitializer {
* `trace.ignore_path` in apm-trace-ignore-plugin.config file.
* <p>
*/
public static void initialize() throws ConfigNotFoundException, AgentPackageNotFoundException {
InputStream configFileStream;
try {
configFileStream = loadConfigFromAgentFolder();
public static void initialize() {
try (final InputStream configFileStream = loadConfigFromAgentFolder()) {
Properties properties = new Properties();
properties.load(configFileStream);
PropertyPlaceholderHelper helper = PropertyPlaceholderHelper.INSTANCE;
for (String key : properties.stringPropertyNames()) {
String value = (String)properties.get(key);
//replace the key's value. properties.replace(key,value) in jdk8+
properties.put(key, PropertyPlaceholderHelper.INSTANCE.replacePlaceholders(value, properties));
}
ConfigInitializer.initialize(properties, IgnoreConfig.class);
......@@ -69,9 +65,7 @@ public class IgnoreConfigInitializer {
private static void overrideConfigBySystemProp() throws IllegalAccessException {
Properties properties = new Properties();
Properties systemProperties = System.getProperties();
Iterator<Map.Entry<Object, Object>> entryIterator = systemProperties.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Object, Object> prop = entryIterator.next();
for (final Map.Entry<Object, Object> prop : systemProperties.entrySet()) {
if (prop.getKey().toString().startsWith(ENV_KEY_PREFIX)) {
String realKey = prop.getKey().toString().substring(ENV_KEY_PREFIX.length());
properties.put(realKey, prop.getValue());
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册