Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "URI is not hierarchical" during runtime attachment #359

Merged
merged 10 commits into from
Jun 17, 2022
Merged

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.contrib.attach;

import io.opentelemetry.javaagent.OpenTelemetryAgent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;

final class AgentFileProvider {

static File getAgentFile() {

verifyExistenceOfAgentJarFile();

Path tempDirPath = createTempDir();

Path tempAgentJarPath = createTempAgentJarFile(tempDirPath);

deleteTempDirOnJvmExit(tempDirPath, tempAgentJarPath);

return tempAgentJarPath.toFile();
}

private static void deleteTempDirOnJvmExit(Path tempDirPath, Path tempAgentJarPath) {
tempAgentJarPath.toFile().deleteOnExit();
tempDirPath.toFile().deleteOnExit();
}

private static void verifyExistenceOfAgentJarFile() {
CodeSource codeSource = OpenTelemetryAgent.class.getProtectionDomain().getCodeSource();
if (codeSource == null) {
throw new IllegalStateException("could not get agent jar location");
}
}

private static Path createTempDir() {
Path tempDir;
try {
tempDir = Files.createTempDirectory("otel-agent");
} catch (IOException e) {
throw new IllegalStateException("Runtime attachment can't create temp directory", e);
}
return tempDir;
}

private static Path createTempAgentJarFile(Path tempDir) {
URL url = OpenTelemetryAgent.class.getProtectionDomain().getCodeSource().getLocation();
try {
return copyTo(url, tempDir, "agent.jar");
} catch (IOException e) {
throw new IllegalStateException(
"Runtime attachment can't create agent jar file in temp directory", e);
}
}

private static Path copyTo(URL url, Path tempDir, String fileName) throws IOException {
Path tempFile = tempDir.resolve(fileName);
try (InputStream in = url.openStream()) {
Files.copy(in, tempFile);
}
return tempFile;
}

private AgentFileProvider() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static void attachJavaagentToCurrentJVM() {
return;
}

File javaagentFile = AgentFileLocator.locateAgentFile();
File javaagentFile = AgentFileProvider.getAgentFile();
ByteBuddyAgent.attach(javaagentFile, getPid());

if (!agentIsAttached()) {
Expand Down