Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Commit

Permalink
HAWKULAR-806 - the server side part of the work: the servlet now allo…
Browse files Browse the repository at this point in the history
…ws for downloading the installer jar with the internal propery file correctly filled with values given as a query param in the URL
  • Loading branch information
jkremser committed Nov 13, 2015
1 parent 30994ab commit 619fed2
Show file tree
Hide file tree
Showing 3 changed files with 161 additions and 29 deletions.
13 changes: 13 additions & 0 deletions dist/assembly.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,19 @@
<directoryMode>0755</directoryMode>
</dependencySet>

<!-- put the agent installer to the same directory as previous artefact from the same reason -->
<dependencySet>
<outputDirectory>${hawkular.dist.zip.root.dir}/standalone/configuration</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<includes>
<include>org.hawkular.agent:hawkular-wildfly-agent-installer:jar</include>
</includes>
<outputFileNameMapping>agent-installer.${artifact.extension}</outputFileNameMapping>
<unpack>false</unpack>
<fileMode>0644</fileMode>
<directoryMode>0755</directoryMode>
</dependencySet>

<!-- TODO Make the unpacking conditional == only for the dev profile -->
<dependencySet>
<outputDirectory>${hawkular.dist.zip.root.dir}/modules/org/hawkular/nest/main/deployments/${artifact.artifactId}.war</outputDirectory>
Expand Down
6 changes: 6 additions & 0 deletions dist/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@
</exclusions>
</dependency>

<dependency>
<groupId>org.hawkular.agent</groupId>
<artifactId>hawkular-wildfly-agent-installer</artifactId>
<version>${version.org.hawkular.agent}</version>
</dependency>

<dependency>
<groupId>org.hawkular.inventory</groupId>
<artifactId>hawkular-inventory-dist</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,20 @@
package org.hawkular.component.wildflymonitor;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
Expand All @@ -40,10 +47,17 @@ public class WildFlyAgentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// the system property that defines how many concurrent downloads we will allow (0 == disable)
private static String SYSPROP_AGENT_DOWNLOADS_LIMIT = "hawkular.wildfly.agent.downloads.limit";
private static final String SYSPROP_AGENT_DOWNLOADS_LIMIT = "hawkular.wildfly.agent.downloads.limit";

// if the system property is not set or invalid, this is the default limit for number of concurrent downloads
private static int DEFAULT_AGENT_DOWNLOADS_LIMIT = 100;
private static final int DEFAULT_AGENT_DOWNLOADS_LIMIT = 100;

// name of the property file stored in the root of the installer jar file
private static String AGENT_INSTALLER_PROPERTIES_FILE_NAME = "hawkular-wildfly-agent-installer.properties";

private static String AGENT_INSTALLER_PROPERTY_WILDFLY_HOME = "wildfly-home";
private static String AGENT_INSTALLER_PROPERTY_MODULE_DIST = "module-dist";
private static String AGENT_INSTALLER_PROPERTY_HAWKULAR_SERVER = "hawkular-server-url";

// the error code that will be returned if the server has been configured to disable agent updates
private static final int ERROR_CODE_AGENT_UPDATE_DISABLED = HttpServletResponse.SC_FORBIDDEN;
Expand All @@ -52,14 +66,15 @@ public class WildFlyAgentServlet extends HttpServlet {
private static final int ERROR_CODE_TOO_MANY_DOWNLOADS = HttpServletResponse.SC_SERVICE_UNAVAILABLE;

private AtomicInteger numActiveDownloads = null;
private File downloadFile = null;
private File moduleDownloadFile = null;
private File installerDownloadFile = null;

@Override
public void init() throws ServletException {
log("Starting the WildFly Agent download servlet");
numActiveDownloads = new AtomicInteger(0);
try {
log("Agent File: " + getAgentDownloadFile());
log("Agent Module File: " + getAgentModuleDownloadFile());
} catch (Throwable t) {
throw new ServletException("Missing Hawkular WildFly Agent download file", t);
}
Expand All @@ -86,37 +101,116 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid servlet path - please contact administrator");
}

return;
}

private void getDownload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int limit = getDownloadLimit();
if (limit <= 0) {
sendErrorDownloadsDisabled(resp);
return;
} else if (limit < numActiveDownloads.get()) {
sendErrorTooManyDownloads(resp);
return;
private void downloadAgentModule(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
File agentModuleZip = getAgentModuleDownloadFile();
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment; filename=" + agentModuleZip.getName());
resp.setContentLength((int) agentModuleZip.length());
resp.setDateHeader("Last-Modified", agentModuleZip.lastModified());
try (FileInputStream agentModuleZipStream = new FileInputStream(agentModuleZip)) {
copy(agentModuleZipStream, resp.getOutputStream());
}
} catch (Throwable t) {
String clientAddr = getClientAddress(req);
log("Failed to stream file to remote client [" + clientAddr + "]", t);
disableBrowserCache(resp);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to stream file");
}
}

private void downloadAgentInstaller(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
File agentJar = getAgentDownloadFile();
File agentInstallerJar = getAgentInstallerDownloadFile();
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment; filename=" + agentJar.getName());
resp.setContentLength((int) agentJar.length());
resp.setDateHeader("Last-Modified", agentJar.lastModified());
try (FileInputStream agentJarStream = new FileInputStream(agentJar)) {
copy(agentJarStream, resp.getOutputStream());
resp.setHeader("Content-Disposition", "attachment; filename=" + agentInstallerJar.getName());
resp.setContentLength((int) agentInstallerJar.length());
resp.setDateHeader("Last-Modified", agentInstallerJar.lastModified());

ZipFile agentInstallerZip = new ZipFile(agentInstallerJar);
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream(), StandardCharsets.UTF_8);
final String wildflyHome = getValueFromQueryParam(req, AGENT_INSTALLER_PROPERTY_WILDFLY_HOME, null);
final String hawkularServer = getValueFromQueryParam(req, AGENT_INSTALLER_PROPERTY_HAWKULAR_SERVER,
"http://localhost:8080");
String defaultModuleDist = hawkularServer.startsWith("http:") ? hawkularServer +
"/hawkular/wildfly-agent/download" : "http://localhost:8080/wildfly-agent/download";
final String moduleDist = getValueFromQueryParam(req, AGENT_INSTALLER_PROPERTY_MODULE_DIST,
defaultModuleDist);


for (Enumeration<? extends ZipEntry> e = agentInstallerZip.entries(); e.hasMoreElements(); ) {
ZipEntry entryIn = e.nextElement();
if (!entryIn.getName().equalsIgnoreCase(AGENT_INSTALLER_PROPERTIES_FILE_NAME)) {
// skip everything else
zos.putNextEntry(entryIn);
try (InputStream is = agentInstallerZip.getInputStream(entryIn)) {
byte[] buf = new byte[4096];
int len;
while ((len = (is.read(buf))) > 0) {
zos.write(buf, 0, len);
}
}
} else {
zos.putNextEntry(new ZipEntry(AGENT_INSTALLER_PROPERTIES_FILE_NAME));
try (BufferedReader br =
new BufferedReader(
new InputStreamReader(agentInstallerZip.getInputStream(entryIn),
StandardCharsets.UTF_8)
)) {
String line;
while ((line = br.readLine()) != null) {
//todo: it'd be better to reuse the strings from the agent installer module to keep it DRY
// and resilient against the changes
if (wildflyHome != null && line.contains("#wildfly-home=/opt/wildfly")) {
line = line.replaceAll("#wildfly-home=/opt/wildfly", "wildfly-home=" + wildflyHome);
} else if (line.contains("#module-dist=")) {
line = line.replaceAll("#module-dist=", "module-dist=" + moduleDist);
} else if (line.contains("#hawkular-server-url=http://localhost:8080")) {
line = line.replaceAll("#hawkular-server-url=http://localhost:8080",
"hawkular-server-url=" + hawkularServer);
}
byte[] buf = (line + '\n').getBytes(StandardCharsets.UTF_8);
zos.write(buf);
}
}
}
zos.closeEntry();
}
zos.close();
} catch (Throwable t) {
String clientAddr = getClientAddress(req);
log("Failed to stream file to remote client [" + clientAddr + "]", t);
disableBrowserCache(resp);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to stream file");
}
}

return;
private String getValueFromQueryParam(HttpServletRequest req, String key, String
defaultValue) throws IOException {
String value = req.getParameter(key);
if (value == null || value.isEmpty()) {
return defaultValue;
}
return value;
}

private void getDownload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int limit = getDownloadLimit();
if (limit <= 0) {
sendErrorDownloadsDisabled(resp);
return;
} else if (limit < numActiveDownloads.get()) {
sendErrorTooManyDownloads(resp);
return;
}
// ?installer=true downloads the installer
if ("true".equals(req.getParameter("installer"))) {
downloadAgentInstaller(req, resp);
} else {
downloadAgentModule(req, resp);
}
}

private int getDownloadLimit() {
Expand Down Expand Up @@ -171,23 +265,42 @@ private void copy(InputStream input, OutputStream output) throws IOException {
output.flush();
}

private File getAgentDownloadFile() throws Exception {
if (downloadFile != null) {
if (downloadFile.exists()) {
return downloadFile;
private File getAgentModuleDownloadFile() throws Exception {
if (moduleDownloadFile != null) {
if (moduleDownloadFile.exists()) {
return moduleDownloadFile;
} else {
downloadFile = null; // the file was removed recently - let's look for a new one
moduleDownloadFile = null; // the file was removed recently - let's look for a new one
}
}

File configDir = new File(System.getProperty("jboss.server.config.dir"));
for (File file : configDir.listFiles()) {
if (file.getName().startsWith("hawkular-wildfly-agent-wf-extension") && file.getName().endsWith(".zip")) {
downloadFile = file;
return downloadFile;
moduleDownloadFile = file;
return moduleDownloadFile;
}
}
throw new FileNotFoundException("Cannot find agent module download in: " + configDir);
}

private File getAgentInstallerDownloadFile() throws Exception {
if (installerDownloadFile != null) {
if (installerDownloadFile.exists()) {
return installerDownloadFile;
} else {
installerDownloadFile = null; // the file was removed recently - let's look for a new one
}
}

File configDir = new File(System.getProperty("jboss.server.config.dir"));
for (File file : configDir.listFiles()) {
if (file.getName().startsWith("agent-installer") && file.getName().endsWith(".jar")) {
installerDownloadFile = file;
return installerDownloadFile;
}
}
throw new FileNotFoundException("Cannot find agent download in: " + configDir);
throw new FileNotFoundException("Cannot find agent installer download in: " + configDir);
}

}

0 comments on commit 619fed2

Please sign in to comment.