Skip to content
This repository has been archived by the owner on Sep 15, 2023. It is now read-only.

Some improvements #5

Merged
merged 4 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package de.adito.aditoweb.nbm.metrics.impl.detectors;

import lombok.NonNull;
import org.jetbrains.annotations.Nullable;

import java.lang.management.*;
import java.util.*;
Expand All @@ -22,12 +23,16 @@ public class ThreadUtility
@NonNull
static String getThreadInfoStacktrace(@NonNull ThreadInfo pThreadInfo)
{
Thread.State state = getThreadState(pThreadInfo);
if (state == null)
state = Thread.State.TERMINATED;

StringBuilder sb = new StringBuilder("\"" + pThreadInfo.getThreadName() + "\"" +
(pThreadInfo.isDaemon() ? " daemon" : "") +
" prio=" + pThreadInfo.getPriority() +
" tid=0x" + String.format("%X", pThreadInfo.getThreadId()) +
" nid=NA " +
pThreadInfo.getThreadState().toString().toLowerCase());
state.toString().toLowerCase());
if (pThreadInfo.getLockName() != null)
{
sb.append(" on " + pThreadInfo.getLockName());
Expand All @@ -46,7 +51,7 @@ static String getThreadInfoStacktrace(@NonNull ThreadInfo pThreadInfo)
sb.append(" (in native)");
}
sb.append('\n');
sb.append(" java.lang.Thread.State: ").append(pThreadInfo.getThreadState()).append("\n");
sb.append(" java.lang.Thread.State: ").append(state).append("\n");
StackTraceElement[] stackTrace = pThreadInfo.getStackTrace();
int i = 0;
for (; i < stackTrace.length; i++)
Expand All @@ -56,7 +61,7 @@ static String getThreadInfoStacktrace(@NonNull ThreadInfo pThreadInfo)
sb.append('\n');
if (i == 0 && pThreadInfo.getLockInfo() != null)
{
Thread.State ts = pThreadInfo.getThreadState();
Thread.State ts = state;
switch (ts)
{
case BLOCKED:
Expand Down Expand Up @@ -123,4 +128,20 @@ public static String getDeadlockedThreadsAsString(@NonNull List<?> pDeadlockedTh
.map(String::valueOf)
.collect(Collectors.joining("\n")) + "\n";
}

/**
* Extracts the thread state of the given info.
* This method is necessary, because IntelliJ should interpret TIMED_WAITING and WAITING the same way
*
* @param pInfo Info to read the state from
* @return the state
*/
@Nullable
private static Thread.State getThreadState(@NonNull ThreadInfo pInfo)
{
Thread.State state = pInfo.getThreadState();
if (state == Thread.State.TIMED_WAITING)
state = Thread.State.WAITING;
return state;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@
import java.io.*;
import java.lang.management.ThreadInfo;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.function.Supplier;
import java.util.logging.*;
import java.util.stream.Collectors;
import java.util.stream.*;
import java.util.zip.*;

/**
* @author w.glanzer, 23.06.2022
Expand Down Expand Up @@ -101,7 +101,7 @@ public String captureBugReport(@NonNull IBugReport pReport, @Nullable File pOutp
{
return _catchException(() -> {
// Prepare event
SentryEvent ev = _createEvent(SentryLevel.INFO, null, null, "User Feedback - " + Instant.now().toString());
SentryEvent ev = _createEvent(SentryLevel.INFO, null, new UserFeedbackEvent(), null);
ev.setExtras(extractExtraInformation(pReport));
SentryId eventId = ev.getEventId();
assert eventId != null;
Expand Down Expand Up @@ -174,14 +174,69 @@ private List<Attachment> extractAttachments(@NonNull IBugReport pReport)

// Append Logs
Optional.ofNullable(pReport.getLogs())
.map(pLogFiles -> pLogFiles.stream()
.map(pLogFile -> new Attachment(pLogFile.getData(), "log_" + pLogFile.getName(), MediaType.PLAIN_TEXT_UTF_8.toString()))
.collect(Collectors.toList()))
.map(pLogFiles -> {
List<Attachment> result = new ArrayList<>();
List<IBugReport.LogFile> remainingFiles = new ArrayList<>(pLogFiles);

// Add a "standalone" messages.log, if possible - so it will be accessable more quickly
for (Iterator<IBugReport.LogFile> iterator = remainingFiles.iterator(); iterator.hasNext(); )
{
IBugReport.LogFile file = iterator.next();
if ("messages.log".equalsIgnoreCase(file.getName()))
{
result.add(new Attachment(file.getData(), "log_" + file.getName(), MediaType.PLAIN_TEXT_UTF_8.toString()));
iterator.remove();
}
}

// Combine all other log files into one large zip file
if (!remainingFiles.isEmpty())
{
Attachment others = compress(remainingFiles.stream().collect(Collectors.toMap(pLogFile -> "log_" + pLogFile.getName(), IBugReport.LogFile::getData)));
if (others != null)
result.add(others);
}

return result;
})
.ifPresent(attachments::addAll);

return attachments;
}

/**
* Combines the given data into a large zip file
*
* @param pFiles Files to compress to a zip file
* @return the zip file as attachment or null, if it could not be created
*/
@Nullable
private Attachment compress(@NonNull Map<String, byte[]> pFiles)
{
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos))
{
// Add everything to the ZipOutputStream
for (Map.Entry<String, byte[]> file : pFiles.entrySet())
{
zos.putNextEntry(new ZipEntry(file.getKey()));
zos.write(file.getValue());
zos.closeEntry();
}

// close the zip, because we finished
zos.close();

// return a new attachment
return new Attachment(baos.toByteArray(), "log_others.zip", MediaType.ZIP.toString());
}
catch (IOException e)
{
LOGGER.log(Level.WARNING, "", e);
return null;
}
}

/**
* Extracts all extra information to send
*
Expand Down Expand Up @@ -380,6 +435,46 @@ public void run()
}
}

/**
* Exception that gets transmitted to sentry, if a userfeedback should be sent
*/
private static class UserFeedbackEvent extends Exception
{
/**
* Length of the random trace generation
*/
private static final int RANDOM_TRACE_DEPTH = 3;

public UserFeedbackEvent()
{
setStackTrace(appendRandomStackTraceElements(getStackTrace()));
}

/**
* Appends random stacktrace elements to the given element array,
* so Sentry is forced to not combining those exceptions
wglanzer marked this conversation as resolved.
Show resolved Hide resolved
*
* @param pOriginalElements Original elements
* @return the elements, with the appended generated ones
*/
@NonNull
private StackTraceElement[] appendRandomStackTraceElements(StackTraceElement @NonNull [] pOriginalElements)
{
List<StackTraceElement> elements = new ArrayList<>();

// Add random stacktrace elements
IntStream.range(0, RANDOM_TRACE_DEPTH)
.mapToObj(pIdx -> new StackTraceElement(getClass().getName() + ".Dyn_" + new Random().nextInt(Integer.MAX_VALUE),
"init", "Dynamic_" + new Random().nextInt(Integer.MAX_VALUE) + ".java", -1))
.forEachOrdered(elements::add);

// Append all current stacktrace elements, so it stays human readable in sentry logging
elements.addAll(Arrays.asList(pOriginalElements));

return elements.toArray(new StackTraceElement[0]);
}
}

/**
* Supplier that is capable of handling exceptions
*
Expand Down
Loading