Search in sources :

Example 1 with FetchResults

use of org.opennms.netmgt.measurements.api.FetchResults in project opennms by OpenNMS.

the class NewtsFetchStrategyTest method cannotRetrieveUnknownAttributeAndUnknownFallbackAttribute.

@Test
public void cannotRetrieveUnknownAttributeAndUnknownFallbackAttribute() {
    createMockResource("icmplocalhost", "shouldNotBeFound", "127.0.0.1", false);
    replay();
    Source sourceToBeFetched = new Source();
    sourceToBeFetched.setResourceId("nodeSource[NODES:1505998205].responseTime[127.0.0.1]");
    sourceToBeFetched.setAttribute("willNotBeFound");
    sourceToBeFetched.setFallbackAttribute("willNotBeFoundToo");
    sourceToBeFetched.setAggregation("AVERAGE");
    sourceToBeFetched.setLabel("icmp");
    FetchResults fetchResults = m_newtsFetchStrategy.fetch(1431047069000L - (60 * 60 * 1000), 1431047069000L, 300 * 1000, 0, null, null, Lists.newArrayList(sourceToBeFetched), false);
    assertNull(fetchResults);
}
Also used : FetchResults(org.opennms.netmgt.measurements.api.FetchResults) Source(org.opennms.netmgt.measurements.model.Source) Test(org.junit.Test)

Example 2 with FetchResults

use of org.opennms.netmgt.measurements.api.FetchResults in project opennms by OpenNMS.

the class NewtsFetchStrategyTest method canRetrieveFallbackAttributeWhenAttributeNotFound.

@Test
public void canRetrieveFallbackAttributeWhenAttributeNotFound() throws Exception {
    createMockResource("icmplocalhost", "icmp", "127.0.0.1");
    replay();
    Source sourceToBeFetched = new Source();
    sourceToBeFetched.setResourceId("nodeSource[NODES:1505998205].responseTime[127.0.0.1]");
    sourceToBeFetched.setAttribute("willNotBeFound");
    sourceToBeFetched.setFallbackAttribute("icmp");
    sourceToBeFetched.setAggregation("AVERAGE");
    sourceToBeFetched.setLabel("icmp");
    FetchResults fetchResults = m_newtsFetchStrategy.fetch(1431047069000L - (60 * 60 * 1000), 1431047069000L, 300 * 1000, 0, null, null, Lists.newArrayList(sourceToBeFetched), false);
    assertEquals(1, fetchResults.getColumns().keySet().size());
    assertTrue(fetchResults.getColumns().containsKey("icmplocalhost"));
    assertEquals(1, fetchResults.getTimestamps().length);
}
Also used : FetchResults(org.opennms.netmgt.measurements.api.FetchResults) Source(org.opennms.netmgt.measurements.model.Source) Test(org.junit.Test)

Example 3 with FetchResults

use of org.opennms.netmgt.measurements.api.FetchResults in project opennms by OpenNMS.

the class NewtsFetchStrategyTest method testFetch.

@Test
public void testFetch() throws Exception {
    List<Source> sources = Lists.newArrayList(createMockResource("icmplocalhost", "icmp", "127.0.0.1"), createMockResource("snmplocalhost", "snmp", "127.0.0.1"), createMockResource("snmp192", "snmp", "192.168.0.1"));
    replay();
    FetchResults fetchResults = m_newtsFetchStrategy.fetch(1431047069000L - (60 * 60 * 1000), 1431047069000L, 300 * 1000, 0, null, null, sources, false);
    assertEquals(3, fetchResults.getColumns().keySet().size());
    assertTrue(fetchResults.getColumns().containsKey("icmplocalhost"));
    assertTrue(fetchResults.getColumns().containsKey("snmplocalhost"));
    assertTrue(fetchResults.getColumns().containsKey("snmp192"));
    assertEquals(1, fetchResults.getTimestamps().length);
}
Also used : FetchResults(org.opennms.netmgt.measurements.api.FetchResults) Source(org.opennms.netmgt.measurements.model.Source) Test(org.junit.Test)

Example 4 with FetchResults

use of org.opennms.netmgt.measurements.api.FetchResults in project opennms by OpenNMS.

the class CustomSpringConfiguration method createFetchStrategy.

@Bean(name = "measurementFetchStrategy")
public MeasurementFetchStrategy createFetchStrategy() {
    return new AbstractRrdBasedFetchStrategy() {

        @Override
        protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {
            final long[] timestamps = new long[] { start, end };
            final Map columnMap = new HashMap<>();
            if (!rrdsBySource.isEmpty()) {
                for (Source eachKey : rrdsBySource.keySet()) {
                    columnMap.put(eachKey.getLabel(), new double[] { 13, 17 });
                }
            }
            return new FetchResults(timestamps, columnMap, step, constants);
        }
    };
}
Also used : AbstractRrdBasedFetchStrategy(org.opennms.netmgt.measurements.impl.AbstractRrdBasedFetchStrategy) HashMap(java.util.HashMap) FetchResults(org.opennms.netmgt.measurements.api.FetchResults) HashMap(java.util.HashMap) Map(java.util.Map) Source(org.opennms.netmgt.measurements.model.Source) Bean(org.springframework.context.annotation.Bean)

Example 5 with FetchResults

use of org.opennms.netmgt.measurements.api.FetchResults 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;
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Context(org.opennms.newts.api.Context) StandardAggregationFunctions(org.opennms.newts.api.query.StandardAggregationFunctions) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Callable(java.util.concurrent.Callable) AggregationFunction(org.opennms.newts.api.query.AggregationFunction) Utils(org.opennms.netmgt.measurements.utils.Utils) SampleRepository(org.opennms.newts.api.SampleRepository) Strings(com.google.common.base.Strings) Future(java.util.concurrent.Future) Lists(com.google.common.collect.Lists) Optional(com.google.common.base.Optional) Map(java.util.Map) OnmsResource(org.opennms.netmgt.model.OnmsResource) ThreadFactory(java.util.concurrent.ThreadFactory) ResultDescriptor(org.opennms.newts.api.query.ResultDescriptor) RrdGraphAttribute(org.opennms.netmgt.model.RrdGraphAttribute) ExecutorService(java.util.concurrent.ExecutorService) SampleSelectCallback(org.opennms.newts.api.SampleSelectCallback) ResourceId(org.opennms.netmgt.model.ResourceId) Logger(org.slf4j.Logger) Semaphore(java.util.concurrent.Semaphore) Collection(java.util.Collection) Resource(org.opennms.newts.api.Resource) Throwables(com.google.common.base.Throwables) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) File(java.io.File) Executors(java.util.concurrent.Executors) Row(org.opennms.newts.api.Results.Row) ExecutionException(java.util.concurrent.ExecutionException) FetchResults(org.opennms.netmgt.measurements.api.FetchResults) List(java.util.List) Duration(org.opennms.newts.api.Duration) Results(org.opennms.newts.api.Results) MeasurementFetchStrategy(org.opennms.netmgt.measurements.api.MeasurementFetchStrategy) Measurement(org.opennms.newts.api.Measurement) Entry(java.util.Map.Entry) Timestamp(org.opennms.newts.api.Timestamp) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ResourceDao(org.opennms.netmgt.dao.api.ResourceDao) Source(org.opennms.netmgt.measurements.model.Source) Measurement(org.opennms.newts.api.Measurement) Timestamp(org.opennms.newts.api.Timestamp) Source(org.opennms.netmgt.measurements.model.Source) RrdGraphAttribute(org.opennms.netmgt.model.RrdGraphAttribute) FetchResults(org.opennms.netmgt.measurements.api.FetchResults) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) OnmsResource(org.opennms.netmgt.model.OnmsResource) ResourceId(org.opennms.netmgt.model.ResourceId) Future(java.util.concurrent.Future) Row(org.opennms.newts.api.Results.Row)

Aggregations

FetchResults (org.opennms.netmgt.measurements.api.FetchResults)19 Source (org.opennms.netmgt.measurements.model.Source)18 RrdGraphAttribute (org.opennms.netmgt.model.RrdGraphAttribute)7 Test (org.junit.Test)6 OnmsResource (org.opennms.netmgt.model.OnmsResource)6 Map (java.util.Map)5 OnmsAttribute (org.opennms.netmgt.model.OnmsAttribute)5 MockResourceType (org.opennms.netmgt.mock.MockResourceType)4 RrdException (org.jrobin.core.RrdException)3 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Optional (com.google.common.base.Optional)1 Strings (com.google.common.base.Strings)1 Throwables (com.google.common.base.Throwables)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1