Search in sources :

Example 41 with PrefabGraph

use of org.opennms.netmgt.model.PrefabGraph in project opennms by OpenNMS.

the class PropertiesGraphDaoIT method testBasicPrefabConfigDirectorySingleReports.

/**
 * Test that individual graph files in an include directory are loaded as expected
 */
@Test
public void testBasicPrefabConfigDirectorySingleReports() throws IOException {
    File rootFile = m_fileAnticipator.tempFile("snmp-graph.properties");
    File graphDirectory = m_fileAnticipator.tempDir("snmp-graph.properties.d");
    File graphBits = m_fileAnticipator.tempFile(graphDirectory, "mib2.bits.properties");
    File graphHCbits = m_fileAnticipator.tempFile(graphDirectory, "mib2.HCbits.properties");
    m_outputStream = new FileOutputStream(rootFile);
    m_writer = new OutputStreamWriter(m_outputStream, StandardCharsets.UTF_8);
    m_writer.write(s_baseIncludePrefab);
    m_writer.close();
    m_outputStream.close();
    graphDirectory.mkdir();
    m_outputStream = new FileOutputStream(graphBits);
    m_writer = new OutputStreamWriter(m_outputStream, StandardCharsets.UTF_8);
    m_writer.write(s_separateBitsGraph);
    m_writer.close();
    m_outputStream.close();
    m_outputStream = new FileOutputStream(graphHCbits);
    m_writer = new OutputStreamWriter(m_outputStream, StandardCharsets.UTF_8);
    m_writer.write(s_separateHCBitsGraph);
    m_writer.close();
    m_outputStream.close();
    HashMap<String, Resource> prefabConfigs = new HashMap<String, Resource>();
    prefabConfigs.put("performance", new FileSystemResource(rootFile));
    PropertiesGraphDao dao = createPropertiesGraphDao(prefabConfigs, s_emptyMap);
    PrefabGraph mib2Bits = dao.getPrefabGraph("mib2.bits");
    assertNotNull(mib2Bits);
    assertEquals("mib2.bits", mib2Bits.getName());
    assertEquals("Bits In/Out", mib2Bits.getTitle());
    String[] columns1 = { "ifInOctets", "ifOutOctets" };
    Assert.assertArrayEquals(columns1, mib2Bits.getColumns());
    PrefabGraph mib2HCBits = dao.getPrefabGraph("mib2.HCbits");
    assertNotNull(mib2HCBits);
    assertEquals("mib2.HCbits", mib2HCBits.getName());
    assertEquals("Bits In/Out", mib2HCBits.getTitle());
    String[] columns2 = { "ifHCInOctets", "ifHCOutOctets" };
    Assert.assertArrayEquals(columns2, mib2HCBits.getColumns());
}
Also used : PrefabGraph(org.opennms.netmgt.model.PrefabGraph) HashMap(java.util.HashMap) FileOutputStream(java.io.FileOutputStream) FileSystemResource(org.springframework.core.io.FileSystemResource) OnmsResource(org.opennms.netmgt.model.OnmsResource) Resource(org.springframework.core.io.Resource) OutputStreamWriter(java.io.OutputStreamWriter) FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File) Test(org.junit.Test)

Example 42 with PrefabGraph

use of org.opennms.netmgt.model.PrefabGraph in project opennms by OpenNMS.

the class DefaultGraphResultsService method createGraphResultSet.

/**
 * <p>createGraphResultSet</p>
 *
 * @param resourceId a {@link java.lang.String} object.
 * @param resource a {@link org.opennms.netmgt.model.OnmsResource} object.
 * @param reports an array of {@link java.lang.String} objects.
 * @param graphResults a {@link org.opennms.web.svclayer.model.GraphResults} object.
 * @return a {@link org.opennms.web.svclayer.model.GraphResults.GraphResultSet}
 * object.
 */
private GraphResultSet createGraphResultSet(ResourceId resourceId, OnmsResource resource, String[] reports, GraphResults graphResults) throws IllegalArgumentException {
    if (resource == null) {
        resource = m_resourceDao.getResourceById(resourceId);
        if (resource == null) {
            throw new IllegalArgumentException("Could not find resource \"" + resourceId + "\"");
        }
    }
    GraphResultSet rs = graphResults.new GraphResultSet();
    rs.setResource(resource);
    if (reports.length == 1 && "all".equals(reports[0])) {
        PrefabGraph[] queries = m_graphDao.getPrefabGraphsForResource(resource);
        List<String> queryNames = new ArrayList<String>(queries.length);
        for (PrefabGraph query : queries) {
            queryNames.add(query.getName());
        }
        reports = queryNames.toArray(new String[queryNames.size()]);
    }
    List<Graph> graphs = new ArrayList<Graph>(reports.length);
    List<String> filesToPromote = new LinkedList<>();
    for (String report : reports) {
        PrefabGraph prefabGraph = m_graphDao.getPrefabGraph(report);
        Graph graph = new Graph(prefabGraph, resource, graphResults.getStart(), graphResults.getEnd());
        getAttributeFiles(graph, filesToPromote);
        graphs.add(graph);
    }
    sendEvent(filesToPromote);
    /*
         * Sort the graphs by their order in the properties file. PrefabGraph
         * implements the Comparable interface.
         */
    Collections.sort(graphs);
    rs.setGraphs(graphs);
    return rs;
}
Also used : PrefabGraph(org.opennms.netmgt.model.PrefabGraph) Graph(org.opennms.web.svclayer.model.Graph) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) ArrayList(java.util.ArrayList) GraphResultSet(org.opennms.web.svclayer.model.GraphResults.GraphResultSet) LinkedList(java.util.LinkedList)

Example 43 with PrefabGraph

use of org.opennms.netmgt.model.PrefabGraph in project opennms by OpenNMS.

the class DefaultRrdGraphService method createPrefabCommand.

/**
 * <p>createPrefabCommand</p>
 *
 * @param graph a {@link org.opennms.web.svclayer.model.Graph} object.
 * @param commandPrefix a {@link java.lang.String} object.
 * @param workDir a {@link java.io.File} object.
 * @param reportName a {@link java.lang.String} object.
 * @return a {@link java.lang.String} object.
 */
protected String createPrefabCommand(Graph graph, String commandPrefix, String reportName, Integer width, Integer height) {
    PrefabGraph prefabGraph = graph.getPrefabGraph();
    String[] rrds = getRrdNames(graph.getResource(), graph.getPrefabGraph().getColumns());
    final StringBuilder buf = new StringBuilder();
    buf.append(commandPrefix);
    buf.append(" ");
    buf.append(prefabGraph.getCommand());
    String command = buf.toString();
    long startTime = graph.getStart().getTime();
    long endTime = graph.getEnd().getTime();
    long diffTime = endTime - startTime;
    /*
         * remember rrdtool wants the time in seconds, not milliseconds;
         * java.util.Date.getTime() returns milliseconds, so divide by 1000
         */
    String startTimeString = Long.toString(startTime / 1000);
    String endTimeString = Long.toString(endTime / 1000);
    String diffTimeString = Long.toString(diffTime / 1000);
    HashMap<String, String> translationMap = new HashMap<String, String>();
    for (int i = 0; i < rrds.length; i++) {
        String key = "{rrd" + (i + 1) + "}";
        translationMap.put(key, rrds[i]);
    }
    translationMap.put("{startTime}", startTimeString);
    translationMap.put("{endTime}", endTimeString);
    translationMap.put("{diffTime}", diffTimeString);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    translationMap.put("{startTimeDate}", fmt.format(new Date(startTime)).replace(":", "\\:"));
    translationMap.put("{endTimeDate}", fmt.format(new Date(endTime)).replace(":", "\\:"));
    // Handle a start time with a format.
    Matcher stm = Pattern.compile("\\{startTime:(.+?)\\}").matcher(command);
    boolean matchFail = false;
    while (stm.find() && !matchFail) {
        String sdfPattern = stm.group(0);
        if (sdfPattern == null) {
            matchFail = true;
        } else {
            try {
                fmt = new SimpleDateFormat(sdfPattern);
                translationMap.put("{startTime:" + sdfPattern + "}", fmt.format(new Date(startTime)).replace(":", "\\:"));
            } catch (IllegalArgumentException e) {
                LOG.error("Cannot parse date format '{}' for graph {}.", sdfPattern, reportName);
            }
        }
    }
    // Handle an end time with a format
    Matcher etm = Pattern.compile("\\{endTime:(.+?)\\}").matcher(command);
    matchFail = false;
    while (etm.find() && !matchFail) {
        String sdfPattern = etm.group(0);
        if (sdfPattern == null) {
            matchFail = true;
        } else {
            try {
                fmt = new SimpleDateFormat(sdfPattern);
                translationMap.put("{endTime:" + sdfPattern + "}", fmt.format(new Date(endTime)).replace(":", "\\:"));
            } catch (IllegalArgumentException e) {
                LOG.error("Cannot parse date format '{}' for graph {}.", sdfPattern, reportName);
            }
        }
    }
    try {
        translationMap.putAll(getTranslationsForAttributes(graph.getResource().getExternalValueAttributes(), prefabGraph.getExternalValues(), "external value attribute"));
        translationMap.putAll(getTranslationsForAttributes(graph.getResource().getStringPropertyAttributes(), prefabGraph.getPropertiesValues(), "string property attribute"));
    } catch (RuntimeException e) {
        LOG.error("Invalid attributes were found on resource '{}'", graph.getResource().getId());
        throw e;
    }
    try {
        for (Map.Entry<String, String> translation : translationMap.entrySet()) {
            // replace s1 with s2
            final Matcher matcher = Pattern.compile(translation.getKey(), Pattern.LITERAL).matcher(command);
            command = matcher.replaceAll(Matcher.quoteReplacement(translation.getValue()));
        }
    } catch (PatternSyntaxException e) {
        throw new IllegalArgumentException("Invalid regular expression syntax, check rrd-properties file", e);
    }
    if (width != null) {
        final Pattern re = Pattern.compile("(--width|-w)(\\w+|=)(\\d+)");
        final Matcher matcher = re.matcher(command);
        if (matcher.matches()) {
            matcher.replaceFirst("--width " + width);
        } else {
            command = command + " --width " + width;
        }
    }
    if (height != null) {
        final Pattern re = Pattern.compile("(--height|-h)(\\w+|=)(\\d+)");
        final Matcher matcher = re.matcher(command);
        if (matcher.matches()) {
            matcher.replaceFirst("--height " + height);
        } else {
            command = command + " --height " + height;
        }
    }
    return command;
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) Date(java.util.Date) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) Map(java.util.Map) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 44 with PrefabGraph

use of org.opennms.netmgt.model.PrefabGraph in project opennms by OpenNMS.

the class DefaultRrdGraphService method getPrefabGraph.

/**
 * {@inheritDoc}
 */
@Override
public InputStream getPrefabGraph(ResourceId resourceId, String report, long start, long end, Integer width, Integer height) {
    Assert.notNull(resourceId, "resourceId argument cannot be null");
    Assert.notNull(report, "report argument cannot be null");
    Assert.isTrue(end > start, "end time " + end + " must be after start time" + start);
    PrefabGraphType t = m_graphDao.findPrefabGraphTypeByName("performance");
    if (t == null) {
        throw new IllegalArgumentException("graph type \"" + "performance" + "\" is not valid");
    }
    OnmsResource r = m_resourceDao.getResourceById(resourceId);
    Assert.notNull(r, "resource could not be located");
    PrefabGraph prefabGraph = m_graphDao.getPrefabGraph(report);
    Graph graph = new Graph(prefabGraph, r, new Date(start), new Date(end));
    String command = createPrefabCommand(graph, t.getCommandPrefix(), report, width, height);
    return getInputStreamForCommand(command);
}
Also used : OnmsResource(org.opennms.netmgt.model.OnmsResource) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) Graph(org.opennms.web.svclayer.model.Graph) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) PrefabGraphType(org.opennms.netmgt.model.PrefabGraphType) Date(java.util.Date)

Example 45 with PrefabGraph

use of org.opennms.netmgt.model.PrefabGraph in project opennms by OpenNMS.

the class GraphResultsController method getSuggestedReports.

/**
 * <p>getSuggestedReports</p>
 *
 * @return an array of {@link java.lang.String} objects.
 */
public String[] getSuggestedReports(ResourceId resourceId, String matching) {
    List<String> metricList = new ArrayList<>();
    JexlEngine expressionParser = new JexlEngine();
    try {
        ExpressionImpl e = (ExpressionImpl) expressionParser.createExpression(matching);
        for (List<String> list : e.getVariables()) {
            if (list.get(0).equalsIgnoreCase("math")) {
                continue;
            }
            if (list.get(0).equalsIgnoreCase("datasources")) {
                metricList.add(list.get(1).intern());
            } else {
                metricList.add(list.get(0).intern());
            }
        }
    } catch (Exception e) {
    }
    if (!metricList.isEmpty()) {
        List<String> templates = new ArrayList<>();
        for (PrefabGraph graph : m_graphResultsService.getAllPrefabGraphs(resourceId)) {
            boolean found = false;
            for (String c : graph.getColumns()) {
                if (metricList.contains(c)) {
                    found = true;
                    continue;
                }
            }
            if (found) {
                templates.add(graph.getName());
            }
        }
        if (!templates.isEmpty()) {
            return templates.toArray(new String[templates.size()]);
        }
    }
    return new String[] { "all" };
}
Also used : ExpressionImpl(org.apache.commons.jexl2.ExpressionImpl) PrefabGraph(org.opennms.netmgt.model.PrefabGraph) JexlEngine(org.apache.commons.jexl2.JexlEngine) ArrayList(java.util.ArrayList) MissingParameterException(org.opennms.web.servlet.MissingParameterException) RrdException(org.jrobin.core.RrdException)

Aggregations

PrefabGraph (org.opennms.netmgt.model.PrefabGraph)50 Test (org.junit.Test)28 OnmsResource (org.opennms.netmgt.model.OnmsResource)16 File (java.io.File)8 ArrayList (java.util.ArrayList)8 FileSystemResource (org.springframework.core.io.FileSystemResource)8 HashMap (java.util.HashMap)7 ObjectRetrievalFailureException (org.springframework.orm.ObjectRetrievalFailureException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 OnmsAttribute (org.opennms.netmgt.model.OnmsAttribute)5 Resource (org.springframework.core.io.Resource)5 FileOutputStream (java.io.FileOutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 HashSet (java.util.HashSet)4 Report (org.opennms.netmgt.config.kscReports.Report)4 MockResourceType (org.opennms.netmgt.mock.MockResourceType)4 RrdGraphAttribute (org.opennms.netmgt.model.RrdGraphAttribute)4 Calendar (java.util.Calendar)3 LinkedHashMap (java.util.LinkedHashMap)3 Graph (org.opennms.netmgt.config.kscReports.Graph)3