Class RulesToolkit
- java.lang.Object
-
- org.openjdk.jmc.flightrecorder.rules.util.RulesToolkit
-
public class RulesToolkit extends Object
A collection of useful methods when evaluating rules.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
RulesToolkit.EventAvailability
Knowledge about the state of affairs of an event type in an IItemCollection.static class
RulesToolkit.RequiredEventsBuilder
-
Field Summary
Fields Modifier and Type Field Description static String
REC_SETTING_NAME_PERIOD
static String
REC_SETTING_PERIOD_EVERY_CHUNK
-
Constructor Summary
Constructors Constructor Description RulesToolkit()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> double
calculateBalanceScore(List<MapToolkit.IntEntry<T>> array)
Calculates a balance for entries, where later elements get a higher relevance than earlier elements.static <T> List<MapToolkit.IntEntry<T>>
calculateGroupingScore(IItemCollection items, IAccessorFactory<T> accessorFactory)
Each group is represented by the number of elements that belong in that group, elements are grouped by accessor value.static IItemFilter
createRangeFilter(IItem item)
Creates a range filter for an event.static TimeRangeThreadFilter
createThreadsAndRangesFilter(IItemCollection items)
Creates a thread and range filter for a set of related events.static Map<IRule,Future<IResult>>
evaluateParallel(Collection<IRule> rules, IItemCollection items, IPreferenceValueProvider preferences, int nThreads)
Evaluates a collection of rules in parallel threads.static String
findMatches(String typeId, IItemCollection items, IAttribute<String> attribute, String match, boolean ignoreCase)
Finds items of a specific type where the given attribute has a value matching that of the provided match string.static Collection<String>
getAllTopics()
Retrieves all topics that have rules associated with them.static IQuantity
getDuration(IItem item)
Convenience method to get the duration value from a specific event.static IQuantity
getDurationInWindow(IQuantity windowStart, IQuantity windowEnd, IItem item)
Get the duration for item within the specified windowstatic IQuantity
getEarliestEndTime(IItemCollection items)
Returns the earliest end time in the provided item collection.static IQuantity
getEarliestStartTime(IItemCollection items)
Returns the earliest start time in the provided item collection.static String
getEnabledEventTypesRecommendation(IItemCollection items, String... typeIds)
Creates a text message informing that event types are recommendedstatic IQuantity
getEndTime(IItem item)
Convenience method to get the end time value from a specific event.static RulesToolkit.EventAvailability
getEventAvailability(IItemCollection items, String... typeIds)
Checks the event availability for the event types.static Map<String,String>
getFlightRecorderOptions(IItemCollection items)
Convenience method for parsing the -XX:FlightRecorderOptions JVM flag.static JavaVersion
getJavaSpecVersion(IItemCollection items)
Gets the Java version for the recording the providedIItemCollection
represents.static JavaVersion
getJavaVersion(String vmInfoVersionString)
static JavaVersion
getJavaVersion(IItemCollection items)
static IQuantity
getLatestEndTime(IItemCollection items)
Returns the latest end time in the provided item collection.static RulesToolkit.EventAvailability
getLeastAvailable(RulesToolkit.EventAvailability... availabilites)
Returns the least available EventAvailability from the ones provided.static IResult
getMissingAttributeResult(IRule rule, IType<IItem> type, IAttribute<?> attribute, IPreferenceValueProvider vp)
Gets aIResult
object representing a not applicable result due to a missing attribute.static IResult
getNotApplicableResult(IRule rule, IPreferenceValueProvider vp, String message)
Creates aIResult
object with a generic not applicable (N/A) result for a given rule with a specified message.static String
getPeriodIfGreaterThan(IItemCollection items, IQuantity minPeriod, String... typeIds)
If possible, gets the longest period setting that is longer than the specified minimum period for the given event types.static String
getSecondFrameInMostCommonTrace(IItemCollection items)
Gets the second frame in the most common stack trace.static IQuantity
getSettingMaxPeriod(IItemCollection items, String... typeIds)
Gets the maximum period setting for the specified event types in the given item collection.static IItemFilter
getSettingsFilter(String settingsName, String... typeIds)
Gets a filter for a specific setting for the provided types.static String
getShortRecordingInfo(IItemCollection items, IQuantity shortRecordingLimit)
Checks if the timerange spanned by the items is shorter than the limit, and returns a informative text message if that is the case.static IQuantity
getStartTime(IItem item)
Convenience method for getting the start time value from a specific event.static IMCThread
getThread(IItem item)
Convenience method to get the event thread value from a specific event.static IResult
getTooFewEventsResult(IRule rule, IPreferenceValueProvider vp)
static IType<IItem>
getType(IItemCollection items, String typeId)
Gets theIType
representation of a specific event type in anIItemCollection
.static String
getTypesWithZeroThreshold(IItemCollection items, String... typeIds)
Returns a string describing the subset of event types given which have no duration threshold set.static <T> T
getValue(IItem item, IAccessorFactory<T> attribute)
Gets the value of a certain attribute for a given itemstatic boolean
isEventsEnabled(IItemCollection items, String... typeIds)
This method checks if the provided event types were explicitly enabled by checking the recording setting events.static boolean
isEventsEnabled(RulesToolkit.EventAvailability... eventAvailabilities)
This method returns false if anyRulesToolkit.EventAvailability
is disabled or unavailable.static double
leastSquareMemory(Iterator<? extends IItem> items, IMemberAccessor<IQuantity,IItem> timeField, IMemberAccessor<IQuantity,IItem> memField)
static double
mapExp(double value, double ceiling, double x1, double y1)
static double
mapExp100(double value, double x1)
An exponential mapping from 0/infinity to 0/100 passing through 75 at limit.static double
mapExp100(double value, double x1, double x2)
An exponential mapping from 0/infinity to 0/100 passing through 25 and 75 at limits.static double
mapExp100Y(double value, double x1, double y1)
An exponential mapping from 0/infinity to 0/100 passing through y1 at x1.static double
mapExp74(double value, double x1)
An exponential mapping from 0/infinity to 0/74 passing through 25 at limit.static double
mapLin100(double value, double x1, double x2)
An multi-linear mapping from 0/1 to 0/100 passing through 25 and 75 at limits.static double
mapSigmoid(double input, double minimum, double maximum, double lowCurveFit, double inflectionPoint, double highCurveFit)
Maps the input value into a value between the minimum and maximum values (exclusive) using a sigmoidal curve with the given parameters.static boolean
matchesEventAvailabilityMap(IItemCollection items, Map<String,RulesToolkit.EventAvailability> availabilityMap)
static IQuantity
parsePersistedJvmTimespan(String persistedValue)
Converts a value persisted as a string by the JVM into anIQuantity
.static Map<String,Integer>
sortMap(Map<String,Integer> map, boolean sortAscending)
Sorts map according to values.static IQuantity
toRatioPercent(IQuantity antecedent, IQuantity consequent)
Calculates the ratio between twoIQuantity
values of compatible, linear kind and returns it represented as a percentage.static String
toRatioPercentString(IQuantity antecedent, IQuantity consequent)
Same calculation astoRatioPercent(IQuantity, IQuantity)
but it returns the percentage as a string instead.
-
-
-
Field Detail
-
REC_SETTING_NAME_PERIOD
public static final String REC_SETTING_NAME_PERIOD
- See Also:
- Constant Field Values
-
REC_SETTING_PERIOD_EVERY_CHUNK
public static final String REC_SETTING_PERIOD_EVERY_CHUNK
- See Also:
- Constant Field Values
-
-
Method Detail
-
leastSquareMemory
public static double leastSquareMemory(Iterator<? extends IItem> items, IMemberAccessor<IQuantity,IItem> timeField, IMemberAccessor<IQuantity,IItem> memField)
- Returns:
- a least squares approximation of the increase in memory over the given time period, in mebibytes/second
-
findMatches
public static String findMatches(String typeId, IItemCollection items, IAttribute<String> attribute, String match, boolean ignoreCase)
Finds items of a specific type where the given attribute has a value matching that of the provided match string.- Parameters:
typeId
- the event type to find matches initems
- the set of items to searchattribute
- the attribute to matchmatch
- the pattern to findignoreCase
- whether or not to ignore case when matching- Returns:
- a comma-delimited string with all matching attributes
-
getValue
public static <T> T getValue(IItem item, IAccessorFactory<T> attribute)
Gets the value of a certain attribute for a given item- Parameters:
item
- the item to get the attribute fromattribute
- the attribute to get- Returns:
- the value of the specified attribute for the given item
-
getSettingsFilter
public static IItemFilter getSettingsFilter(String settingsName, String... typeIds)
Gets a filter for a specific setting for the provided types.- Parameters:
settingsName
- the specific setting to findtypeIds
- the ids of the types to find the setting for- Returns:
- a filter for a specified setting for the provided type ids
-
getSettingMaxPeriod
public static IQuantity getSettingMaxPeriod(IItemCollection items, String... typeIds)
Gets the maximum period setting for the specified event types in the given item collection.- Parameters:
items
- the items to find the period setting intypeIds
- the event type ids to find settings for- Returns:
- the maximum period setting for the specified event types
-
getPeriodIfGreaterThan
public static String getPeriodIfGreaterThan(IItemCollection items, IQuantity minPeriod, String... typeIds)
If possible, gets the longest period setting that is longer than the specified minimum period for the given event types.- Parameters:
items
- the item collection to search throughminPeriod
- the minimum period settingtypeIds
- the event type ids to find the period setting for- Returns:
- a string representation of the longest period longer than the
minPeriod
, ornull
if all periods are shorter thanminPeriod
-
parsePersistedJvmTimespan
public static IQuantity parsePersistedJvmTimespan(String persistedValue) throws QuantityConversionException
Converts a value persisted as a string by the JVM into anIQuantity
.- Parameters:
persistedValue
- the persisted value to convert- Returns:
- the resulting
IQuantity
- Throws:
QuantityConversionException
-
getTypesWithZeroThreshold
public static String getTypesWithZeroThreshold(IItemCollection items, String... typeIds)
Returns a string describing the subset of event types given which have no duration threshold set.- Parameters:
items
- the item collection to searchtypeIds
- the event type ids to find thresholds for- Returns:
- a comma-delimited string describing the event types with no threshold
-
isEventsEnabled
public static boolean isEventsEnabled(IItemCollection items, String... typeIds)
This method checks if the provided event types were explicitly enabled by checking the recording setting events.- Parameters:
items
- the collection to check.typeIds
- the identifiers for the event types to check.- Returns:
- true if all of the required event types were known to be explicitly enabled.
-
isEventsEnabled
public static boolean isEventsEnabled(RulesToolkit.EventAvailability... eventAvailabilities)
This method returns false if anyRulesToolkit.EventAvailability
is disabled or unavailable. Otherwise true.- Parameters:
eventAvailabilities
- theRulesToolkit.EventAvailability
to check- Returns:
- false if any
RulesToolkit.EventAvailability
is disabled or unavailable. Otherwise true.
-
getEventAvailability
public static RulesToolkit.EventAvailability getEventAvailability(IItemCollection items, String... typeIds)
Checks the event availability for the event types.Care should be taken when used with multiple typeIds. Use it when all of the provided typeIds are expected to have the same availability; if mixed, the lowest common availability for all types will be returned.
- Parameters:
items
- the collection to checktypeIds
- the type identifiers to check- Returns:
- the availability for the event types
-
matchesEventAvailabilityMap
public static boolean matchesEventAvailabilityMap(IItemCollection items, Map<String,RulesToolkit.EventAvailability> availabilityMap)
-
getLeastAvailable
public static RulesToolkit.EventAvailability getLeastAvailable(RulesToolkit.EventAvailability... availabilites)
Returns the least available EventAvailability from the ones provided. SeeRulesToolkit.EventAvailability
.- Returns:
- the least available EventAvailability from the ones provided.
-
getTooFewEventsResult
public static IResult getTooFewEventsResult(IRule rule, IPreferenceValueProvider vp)
Creates aIResult
object for the givenIRule
object representing a result where there are too few events to properly evaluate a rule.- Parameters:
rule
- the rule to create aIResult
object for- Returns:
- an object describing that the rule could not be evaluated due to there not being enough data
-
getNotApplicableResult
public static IResult getNotApplicableResult(IRule rule, IPreferenceValueProvider vp, String message)
Creates aIResult
object with a generic not applicable (N/A) result for a given rule with a specified message.- Parameters:
rule
- the rule to create aIResult
object formessage
- the description of the result- Returns:
- an object representing a generic not applicable result for the provided rule
-
getEnabledEventTypesRecommendation
public static String getEnabledEventTypesRecommendation(IItemCollection items, String... typeIds)
Creates a text message informing that event types are recommended- Parameters:
items
- the events.typeIds
- the identifiers of the event types to check.- Returns:
- a text message informing that event types are recommended
-
getJavaSpecVersion
public static JavaVersion getJavaSpecVersion(IItemCollection items)
Gets the Java version for the recording the providedIItemCollection
represents.- Parameters:
items
- the recording to find the version of- Returns:
- an object representing the Java version of the VM the items originate from
-
getJavaVersion
public static JavaVersion getJavaVersion(IItemCollection items)
- Parameters:
items
- the items to look for the JVM version in.- Returns:
- the parsed JavaVersion, or null if no VM information event with the JVM version could be found.
-
mapExp74
public static double mapExp74(double value, double x1)
An exponential mapping from 0/infinity to 0/74 passing through 25 at limit. This approaches 74 at about 300-400% of the limit.- Parameters:
value
- Input value. Negative values will be treated as zero.x1
- Return 25 if value is equal to this. Must be more than zero.- Returns:
- A value between 0 and 74.
-
mapExp100
public static double mapExp100(double value, double x1)
An exponential mapping from 0/infinity to 0/100 passing through 75 at limit. This approaches 100 at about 300-400% of the limit.- Parameters:
value
- Input value. Negative values will be treated as zero.x1
- Return 75 if value is equal to this. Must be more than zero.- Returns:
- A value between 0 and 100.
-
mapExp100Y
public static double mapExp100Y(double value, double x1, double y1)
An exponential mapping from 0/infinity to 0/100 passing through y1 at x1.- Parameters:
value
- Input value. Negative values will be treated as zero.x1
- Return y1 if value is equal to this. Must be more than zero.y1
- Return value at x1. Must be more than zero and less than 100.- Returns:
- A value between 0 and 100.
-
mapExp100
public static double mapExp100(double value, double x1, double x2)
An exponential mapping from 0/infinity to 0/100 passing through 25 and 75 at limits. This approaches 100 at about 300-400% of the 75 limit.- Parameters:
value
- Input value. Negative values will be treated as zero.x1
- Return 25 if value is equal to this. Must be more than zero.x2
- Return 75 if value is equal to this. Must be more than x1.- Returns:
- A value between 0 and 100.
-
mapExp
public static double mapExp(double value, double ceiling, double x1, double y1)
- Parameters:
value
- Input value. Negative values will be treated as zero.ceiling
- Max return value. Must be more than zero.x1
- Return y1 if value is equal to this. Must be more than zero.y1
- Return value at x1. Must be more than zero and less than ceiling.- Returns:
- A value between 0 and ceiling.
-
mapLin100
public static double mapLin100(double value, double x1, double x2)
An multi-linear mapping from 0/1 to 0/100 passing through 25 and 75 at limits.- Parameters:
value
- Input value. Negative values will be treated as zero.x1
- Return 25 if value is equal to this. Must be more than zero.x2
- Return 75 if value is equal to this. Must be more than x1.- Returns:
- A value between 0 and 100.
-
calculateGroupingScore
public static <T> List<MapToolkit.IntEntry<T>> calculateGroupingScore(IItemCollection items, IAccessorFactory<T> accessorFactory)
Each group is represented by the number of elements that belong in that group, elements are grouped by accessor value.For example, the items {A, B, C, A, B, A, A} will become {1, 2, 4}
- Parameters:
items
- input itemsaccessorFactory
- a factory that provides accessors for the input item types- Returns:
- A sorted list of counts, one for each unique value that the accessor computes from the input items, that tells how many input items gave that accessor value.
-
calculateBalanceScore
public static <T> double calculateBalanceScore(List<MapToolkit.IntEntry<T>> array)
Calculates a balance for entries, where later elements get a higher relevance than earlier elements.For example the values 1, 1, 2, 5 will get the total score 5/9/1 + 2/9/2 + 1/9/3 + 1/9/4
- Parameters:
array
- input values- Returns:
- the balance score
-
getDurationInWindow
public static IQuantity getDurationInWindow(IQuantity windowStart, IQuantity windowEnd, IItem item)
Get the duration for item within the specified window- Parameters:
windowStart
- window startwindowEnd
- window enditem
- item to get duration for- Returns:
- duration within window
-
mapSigmoid
public static double mapSigmoid(double input, double minimum, double maximum, double lowCurveFit, double inflectionPoint, double highCurveFit)
Maps the input value into a value between the minimum and maximum values (exclusive) using a sigmoidal curve with the given parameters. Minimum and maximum values are asymptotes, so will never be mapped to. If you want to map from [0,1] to (0,100) using this you should set a low inflection point and a single digit high curve fit with a low curve fit around 150. This will lead to exponential growth until the midway point where it will start growing logarithmically.- Parameters:
input
- the value to mapminimum
- the maximum value to map to (exclusive)maximum
- the minimum value to map to (exclusive)lowCurveFit
- fitting parameter for the lower end of the curveinflectionPoint
- the inflection point of the curve (where input leads to 1/3 between min and max)highCurveFit
- fitting parameter for the higher end of the curve- Returns:
- a mapped value in the range (minimum,maximum)
-
getJavaVersion
public static JavaVersion getJavaVersion(String vmInfoVersionString)
- Parameters:
vmInfoVersionString
- the JVM version information as presented in the VM information events, containing both the JVM and JDK version numbers.- Returns:
- the parsed JavaVersion.
-
getType
public static IType<IItem> getType(IItemCollection items, String typeId)
Gets theIType
representation of a specific event type in anIItemCollection
.- Parameters:
items
- the items to find the type intypeId
- the event type id to find the type object of- Returns:
- an object representing the type with the specified id in the provided item collection
-
getMissingAttributeResult
public static IResult getMissingAttributeResult(IRule rule, IType<IItem> type, IAttribute<?> attribute, IPreferenceValueProvider vp)
Gets aIResult
object representing a not applicable result due to a missing attribute.- Parameters:
rule
- the rule which could not be evaluatedtype
- the type of the item which is missing a required attributeattribute
- the attribute that is missing- Returns:
- an object that represents the not applicable result due to the missing attribute
-
createThreadsAndRangesFilter
public static TimeRangeThreadFilter createThreadsAndRangesFilter(IItemCollection items)
Creates a thread and range filter for a set of related events. It assumes all the events provided are related and spans one contiguous time range per thread. The resulting filter will include all the original events plus any other occurred in the same thread during the time period (per thread) spanned by the events in the collection. Note that this is an expensive operation. Use with care.- Parameters:
items
- a collection of related items.- Returns:
- a filter for the thread and time range.
-
createRangeFilter
public static IItemFilter createRangeFilter(IItem item)
Creates a range filter for an event. The range will span the same time as the event.- Parameters:
item
- the event for which to create the range filter- Returns:
- a filter for the time range of the event.
-
getStartTime
public static IQuantity getStartTime(IItem item)
Convenience method for getting the start time value from a specific event.- Parameters:
item
- the event to get the start time from- Returns:
- the start time of the provided event
-
getEndTime
public static IQuantity getEndTime(IItem item)
Convenience method to get the end time value from a specific event.- Parameters:
item
- the event to get the end time from- Returns:
- the end time of the provided event
-
getDuration
public static IQuantity getDuration(IItem item)
Convenience method to get the duration value from a specific event.- Parameters:
item
- the event to get the duration from- Returns:
- the duration of the provided event
-
getThread
public static IMCThread getThread(IItem item)
Convenience method to get the event thread value from a specific event.- Parameters:
item
- the event to get the thread value from- Returns:
- the thread the provided event occurred in
-
toRatioPercent
public static IQuantity toRatioPercent(IQuantity antecedent, IQuantity consequent)
Calculates the ratio between twoIQuantity
values of compatible, linear kind and returns it represented as a percentage.- Parameters:
antecedent
- the antecedent (numerator) valueconsequent
- the consequent (denominator) value- Returns:
- the ratio between the two values as a percentage
-
toRatioPercentString
public static String toRatioPercentString(IQuantity antecedent, IQuantity consequent)
Same calculation astoRatioPercent(IQuantity, IQuantity)
but it returns the percentage as a string instead.- Parameters:
antecedent
- the antecedent (numerator) valueconsequent
- the consequent (denominator) value- Returns:
- the ratio between the two values as a percentage, as a string
-
getAllTopics
public static Collection<String> getAllTopics()
Retrieves all topics that have rules associated with them.- Returns:
- all topics associated with any rule
-
evaluateParallel
public static Map<IRule,Future<IResult>> evaluateParallel(Collection<IRule> rules, IItemCollection items, IPreferenceValueProvider preferences, int nThreads)
Evaluates a collection of rules in parallel threads. The method returns a map of rules andfuture
results that are scheduled to run using the specified number of threads.You can use a single threaded loop over the returned futures to
get
the results.If evaluation of a rule fails, then the get method of the corresponding future will throw an
ExecutionException
.- Parameters:
rules
- rules to runitems
- items to evaluatepreferences
- SeeIRule.createEvaluation(IItemCollection, IPreferenceValueProvider, IResultValueProvider)
. Ifnull
, then default values will be used.nThreads
- The number or parallel threads to use when evaluating. If 0, then the number of available processors will be used.- Returns:
- a map from rules to result futures
-
getSecondFrameInMostCommonTrace
public static String getSecondFrameInMostCommonTrace(IItemCollection items)
Gets the second frame in the most common stack trace. Useful when showing what called a interesting method, like for example java.lang.Integer.valueOf (aka autoboxing)- Parameters:
items
- the item collection to build the aggregated stack trace on- Returns:
- a stack trace frame
-
getFlightRecorderOptions
public static Map<String,String> getFlightRecorderOptions(IItemCollection items)
Convenience method for parsing the -XX:FlightRecorderOptions JVM flag. Since this is one flag that contains all flight recorder settings in a comma separated list as a single string it is useful to have one place to get the actual setting/value pairs from anIItemCollection
.- Parameters:
items
- an item collection containing at least oneJdkTypeIDs.STRING_FLAG
event with the value "FlightRecorderOptions"- Returns:
- a setting/value map for all FlightRecorderOptions
-
getShortRecordingInfo
public static String getShortRecordingInfo(IItemCollection items, IQuantity shortRecordingLimit)
Checks if the timerange spanned by the items is shorter than the limit, and returns a informative text message if that is the case.- Parameters:
items
- the item collection to get recording range fromshortRecordingLimit
- limit for a short recording- Returns:
- a text message informing that this is a short recording, or null if recording is not short
-
sortMap
public static Map<String,Integer> sortMap(Map<String,Integer> map, boolean sortAscending)
Sorts map according to values.- Parameters:
map
- the map to sortsortAscending
- true if the sorting should be from lower to higher, false for higher to lower- Returns:
- sorted map
-
getEarliestStartTime
public static IQuantity getEarliestStartTime(IItemCollection items)
Returns the earliest start time in the provided item collection. This method is based on the assumption that item collection lanes are sorted by timestamp.- Parameters:
items
- the item collection to find the earliest start time in- Returns:
- the earliest start time in the provided collection
-
getEarliestEndTime
public static IQuantity getEarliestEndTime(IItemCollection items)
Returns the earliest end time in the provided item collection. This method is based on the assumption that item collection lanes are sorted by timestamp and are not overlapping.- Parameters:
items
- the item collection to find the earliest end time in- Returns:
- the earliest end time in the provided collection
-
getLatestEndTime
public static IQuantity getLatestEndTime(IItemCollection items)
Returns the latest end time in the provided item collection. This method is based on the assumption that item collection lanes are sorted by timestamp and are not overlapping.- Parameters:
items
- the item collection to find the latest end time in- Returns:
- the latest end time in the provided collection
-
-