use of org.opennms.newts.api.Results in project newts by OpenNMS.
the class RateTest method testMissing.
@Test
public void testMissing() {
Results<Sample> input = new Results<>();
Timestamp start = Timestamp.fromEpochMillis(1000);
Duration step = Duration.seconds(1);
// row_1
input.addElement(new Sample(start, m_resource, m_metrics[0], COUNTER, new Counter(0)));
input.addElement(new Sample(start, m_resource, m_metrics[1], COUNTER, new Counter(0)));
// row_2
input.addElement(new Sample(start.plus(step), m_resource, m_metrics[0], COUNTER, new Counter(100)));
input.addElement(new Sample(start.plus(step), m_resource, m_metrics[1], COUNTER, new Counter(100)));
// row_3 (sample for m_metrics[0] missing)
input.addElement(new Sample(start.plus(step.times(2)), m_resource, m_metrics[1], COUNTER, new Counter(200)));
// row_4
input.addElement(new Sample(start.plus(step.times(3)), m_resource, m_metrics[0], COUNTER, new Counter(300)));
input.addElement(new Sample(start.plus(step.times(3)), m_resource, m_metrics[1], COUNTER, new Counter(300)));
Iterator<Results.Row<Sample>> output = new Rate(input.iterator(), getMetrics(2)).iterator();
// result_1 is always null
assertTrue(output.hasNext());
assertEquals(new Gauge(Double.NaN), output.next().getElement(m_metrics[0]).getValue());
// result_2, rate 100
assertTrue(output.hasNext());
assertEquals(100.0d, output.next().getElement(m_metrics[0]).getValue().doubleValue(), 0.0d);
// result_3, missing because sample in row_3 is missing
assertTrue(output.hasNext());
assertNull(output.next().getElement(m_metrics[0]));
// result_4, rate of 100 calculated between row_4 and row_2
assertTrue(output.hasNext());
assertEquals(100.0d, output.next().getElement(m_metrics[0]).getValue().doubleValue(), 0.0d);
}
use of org.opennms.newts.api.Results in project newts by OpenNMS.
the class ResultSerializationTest method testMeasurements.
@Test
public void testMeasurements() throws JsonProcessingException {
Results<Measurement> data = new Results<>();
data.addElement(new Measurement(Timestamp.fromEpochSeconds(900000000), new Resource("localhost"), "ifInOctets", 5000));
data.addElement(new Measurement(Timestamp.fromEpochSeconds(900000000), new Resource("localhost"), "ifOutOctets", 6000));
data.addElement(new Measurement(Timestamp.fromEpochSeconds(900000300), new Resource("localhost"), "ifInOctets", 6000));
data.addElement(new Measurement(Timestamp.fromEpochSeconds(900000300), new Resource("localhost"), "ifOutOctets", 7000));
String json = "[" + " [" + " {" + " \"name\": \"ifOutOctets\"," + " \"timestamp\":900000000000," + " \"value\":6000.0" + " }," + " {" + " \"name\": \"ifInOctets\"," + " \"timestamp\":900000000000," + " \"value\":5000.0" + " }" + " ]," + " [" + " {" + " \"name\": \"ifOutOctets\"," + " \"timestamp\":900000300000," + " \"value\":7000.0" + " }," + " {" + " \"name\": \"ifInOctets\"," + " \"timestamp\":900000300000," + " \"value\":6000.0" + " }" + " ]" + "]";
assertThat(new ObjectMapper().writeValueAsString(Transform.measurementDTOs(data)), is(normalize(json)));
}
use of org.opennms.newts.api.Results in project opennms by OpenNMS.
the class NewtsConverterIT method execute.
private void execute(final boolean storeByGroup, final boolean storeByForeignSource, final boolean useRrdTool) throws Exception {
final Path data = OPENNMS_HOME.resolve("share").resolve(useRrdTool ? "rrd" : "jrb").resolve(storeByGroup ? "sbg" : "sbm").resolve(storeByForeignSource ? "fs" : "id");
assertTrue(Files.isDirectory(data));
exit.expectSystemExitWithStatus(0);
exit.checkAssertionAfterwards(() -> {
assertThat(resourceStorageDao.exists(RESOURCE_PATH_SNMP, 0), is(true));
assertThat(resourceStorageDao.getAttributes(RESOURCE_PATH_SNMP), hasItems(allOf(hasProperty("name", is("ifInOctets"))), allOf(hasProperty("name", is("ifSpeed")), hasProperty("value", is("1000")))));
assertThat(resourceStorageDao.exists(RESOURCE_PATH_RESPONSE, 0), is(true));
assertThat(resourceStorageDao.getAttributes(RESOURCE_PATH_RESPONSE), hasItems(allOf(hasProperty("name", is("icmp")))));
final Results<Measurement> result = repository.select(Context.DEFAULT_CONTEXT, new Resource(NewtsUtils.toResourceId(ResourcePath.get(RESOURCE_PATH_SNMP, "mib2-interfaces"))), Optional.of(Timestamp.fromEpochSeconds(1414504800)), Optional.of(Timestamp.fromEpochSeconds(1417047045)), new ResultDescriptor(Duration.seconds(7200)).datasource("ifInOctets", StandardAggregationFunctions.AVERAGE).export("ifInOctets"), Optional.of(Duration.seconds(7200)));
assertThat(result.getRows().size(), is(EXPECTED_DATA.length));
int i = 0;
for (Results.Row<Measurement> r : result) {
final double deltaAbs = r.getElement("ifInOctets").getValue().doubleValue() - EXPECTED_DATA[i].value;
final double deltaRel = deltaAbs / EXPECTED_DATA[i].value * 100.0;
/* Use the following for debugging of non-matching entries...
System.out.println(String.format(
"%4d: %-24s %11.2f %11.2f %11.2f (%6.2f) %36s|%-36s %f%%",
i,
r.getElement("ifInOctets").getTimestamp().asDate().toString(),
r.getElement("ifInOctets").getValue().doubleValue(),
EXPECTED_DATA[i].value,
deltaAbs,
deltaRel,
deltaAbs < -1.0 ? Strings.repeat("▒", (int) Math.abs(Math.log10(-deltaAbs) * 10.0)) : "",
deltaAbs > 1.0 ? Strings. repeat("▒", (int) Math.abs(Math.log10(deltaAbs) * 10.0)) : "",
Math.abs(deltaAbs / EXPECTED_DATA[i].value * 100.0)));
*/
assertThat(r.getTimestamp().asSeconds(), is(EXPECTED_DATA[i].timestamp));
if (i != 270) {
// We got some errors on the RRA boundaries - ignore them
assertThat(r.getElement("ifInOctets").getValue().doubleValue(), is(anyOf(equalTo(EXPECTED_DATA[i].value), // Allow a relative error of 0.3%
closeTo(EXPECTED_DATA[i].value, EXPECTED_DATA[i].value * 0.003))));
}
i++;
}
});
NewtsConverter.main("-o", OPENNMS_HOME.toString(), "-r", data.toString(), "-t", Boolean.toString(useRrdTool), "-T", RRD_BINARY.toAbsolutePath().toString(), "-s", Boolean.toString(storeByGroup));
}
use of org.opennms.newts.api.Results in project opennms by OpenNMS.
the class NewtsFetchStrategy method fetch.
@Override
public FetchResults fetch(long start, long end, long step, int maxrows, Long interval, Long heartbeat, List<Source> sources, boolean relaxed) {
final LateAggregationParams lag = getLagParams(step, interval, heartbeat);
final Optional<Timestamp> startTs = Optional.of(Timestamp.fromEpochMillis(start));
final Optional<Timestamp> endTs = Optional.of(Timestamp.fromEpochMillis(end));
final Map<String, Object> constants = Maps.newHashMap();
// Group the sources by resource id to avoid calling the ResourceDao
// multiple times for the same resource
Map<ResourceId, List<Source>> sourcesByResourceId = sources.stream().collect(Collectors.groupingBy((source) -> ResourceId.fromString(source.getResourceId())));
// Lookup the OnmsResources in parallel
Map<ResourceId, Future<OnmsResource>> resourceFuturesById = Maps.newHashMapWithExpectedSize(sourcesByResourceId.size());
for (ResourceId resourceId : sourcesByResourceId.keySet()) {
resourceFuturesById.put(resourceId, threadPool.submit(getResourceByIdCallable(resourceId)));
}
// Gather the results, fail if any of the resources were not found
Map<OnmsResource, List<Source>> sourcesByResource = Maps.newHashMapWithExpectedSize(sourcesByResourceId.size());
for (Entry<ResourceId, Future<OnmsResource>> entry : resourceFuturesById.entrySet()) {
try {
OnmsResource resource = entry.getValue().get();
if (resource == null) {
if (relaxed)
continue;
LOG.error("No resource with id: {}", entry.getKey());
return null;
}
sourcesByResource.put(resource, sourcesByResourceId.get(entry.getKey()));
} catch (ExecutionException | InterruptedException e) {
throw Throwables.propagate(e);
}
}
// Now group the sources by Newts Resource ID, which differs from the OpenNMS Resource ID.
Map<String, List<Source>> sourcesByNewtsResourceId = Maps.newHashMap();
for (Entry<OnmsResource, List<Source>> entry : sourcesByResource.entrySet()) {
final OnmsResource resource = entry.getKey();
for (Source source : entry.getValue()) {
// Gather the values from strings.properties
Utils.convertStringAttributesToConstants(source.getLabel(), resource.getStringPropertyAttributes(), constants);
// Grab the attribute that matches the source
RrdGraphAttribute rrdGraphAttribute = resource.getRrdGraphAttributes().get(source.getAttribute());
if (rrdGraphAttribute == null && !Strings.isNullOrEmpty(source.getFallbackAttribute())) {
LOG.error("No attribute with name '{}', using fallback-attribute with name '{}'", source.getAttribute(), source.getFallbackAttribute());
source.setAttribute(source.getFallbackAttribute());
source.setFallbackAttribute(null);
rrdGraphAttribute = resource.getRrdGraphAttributes().get(source.getAttribute());
}
if (rrdGraphAttribute == null) {
if (relaxed)
continue;
LOG.error("No attribute with name: {}", source.getAttribute());
return null;
}
// The Newts Resource ID is stored in the rrdFile attribute
String newtsResourceId = rrdGraphAttribute.getRrdRelativePath();
// Remove the file separator prefix, added by the RrdGraphAttribute class
if (newtsResourceId.startsWith(File.separator)) {
newtsResourceId = newtsResourceId.substring(File.separator.length(), newtsResourceId.length());
}
List<Source> listOfSources = sourcesByNewtsResourceId.get(newtsResourceId);
// Create the list if it doesn't exist
if (listOfSources == null) {
listOfSources = Lists.newLinkedList();
sourcesByNewtsResourceId.put(newtsResourceId, listOfSources);
}
listOfSources.add(source);
}
}
// The Newts API only allows us to perform a query using a single (Newts) Resource ID,
// so we perform multiple queries in parallel, and aggregate the results.
Map<String, Future<Collection<Row<Measurement>>>> measurementsByNewtsResourceId = Maps.newHashMapWithExpectedSize(sourcesByNewtsResourceId.size());
for (Entry<String, List<Source>> entry : sourcesByNewtsResourceId.entrySet()) {
measurementsByNewtsResourceId.put(entry.getKey(), threadPool.submit(getMeasurementsForResourceCallable(entry.getKey(), entry.getValue(), startTs, endTs, lag)));
}
long[] timestamps = null;
Map<String, double[]> columns = Maps.newHashMap();
for (Entry<String, Future<Collection<Row<Measurement>>>> entry : measurementsByNewtsResourceId.entrySet()) {
Collection<Row<Measurement>> rows;
try {
rows = entry.getValue().get();
} catch (InterruptedException | ExecutionException e) {
throw Throwables.propagate(e);
}
final int N = rows.size();
if (timestamps == null) {
timestamps = new long[N];
int k = 0;
for (final Row<Measurement> row : rows) {
timestamps[k] = row.getTimestamp().asMillis();
k++;
}
}
int k = 0;
for (Row<Measurement> row : rows) {
for (Measurement measurement : row.getElements()) {
double[] column = columns.get(measurement.getName());
if (column == null) {
column = new double[N];
columns.put(measurement.getName(), column);
}
column[k] = measurement.getValue();
}
k += 1;
}
}
FetchResults fetchResults = new FetchResults(timestamps, columns, lag.getStep(), constants);
if (relaxed) {
Utils.fillMissingValues(fetchResults, sources);
}
LOG.trace("Fetch results: {}", fetchResults);
return fetchResults;
}
use of org.opennms.newts.api.Results in project newts by OpenNMS.
the class ResultSerializationTest method testSamples.
@Test
public void testSamples() throws JsonProcessingException {
// Use the optional attributes map at least once.
Map<String, String> attributes = Maps.newHashMap();
attributes.put("units", "bytes");
Results<Sample> data = new Results<>();
data.addElement(new Sample(Timestamp.fromEpochSeconds(900000000), new Resource("localhost"), "ifInOctets", COUNTER, ValueType.compose(5000, COUNTER)));
data.addElement(new Sample(Timestamp.fromEpochSeconds(900000000), new Resource("localhost"), "ifOutOctets", COUNTER, ValueType.compose(6000, COUNTER), attributes));
data.addElement(new Sample(Timestamp.fromEpochSeconds(900000300), new Resource("localhost"), "ifInOctets", COUNTER, ValueType.compose(6000, COUNTER)));
data.addElement(new Sample(Timestamp.fromEpochSeconds(900000300), new Resource("localhost"), "ifOutOctets", COUNTER, ValueType.compose(7000, COUNTER)));
String json = "[" + " [" + " {" + " \"name\": \"ifOutOctets\"," + " \"timestamp\":900000000000," + " \"type\":\"COUNTER\"," + " \"value\":6000," + " \"attributes\":{\"units\":\"bytes\"}" + " }," + " {" + " \"name\": \"ifInOctets\"," + " \"timestamp\":900000000000," + " \"type\":\"COUNTER\"," + " \"value\":5000" + " }" + " ]," + " [" + " {" + " \"name\": \"ifOutOctets\"," + " \"timestamp\":900000300000," + " \"type\":\"COUNTER\"," + " \"value\":7000" + " }," + " {" + " \"name\": \"ifInOctets\"," + " \"timestamp\":900000300000," + " \"type\":\"COUNTER\"," + " \"value\":6000" + " }" + " ]" + "]";
assertThat(new ObjectMapper().writeValueAsString(Transform.sampleDTOs(data)), is(normalize(json)));
}
Aggregations