Search in sources :

Example 21 with TSQuery

use of net.opentsdb.core.TSQuery in project opentsdb by OpenTSDB.

the class BaseTimeSyncedIteratorTest method runQueries.

/**
   * Executes the queries against MockBase through the regular pipeline and stores
   * the results in {@linke #results}
   * @param subs The queries to execute
   */
protected void runQueries(final ArrayList<TSSubQuery> subs) throws Exception {
    query = new TSQuery();
    query.setStart(Long.toString(START_TS));
    query.setQueries(subs);
    query.validateAndSetQuery();
    final Query[] compiled = query.buildQueries(tsdb);
    results = new HashMap<String, Pair<TSSubQuery, DataPoints[]>>(compiled.length);
    iterators = new HashMap<String, ITimeSyncedIterator>(compiled.length);
    int index = 0;
    for (final Query q : compiled) {
        final DataPoints[] dps = q.runAsync().join();
        results.put(Integer.toString(index), new Pair<TSSubQuery, DataPoints[]>(query.getQueries().get(index), dps));
        final ITimeSyncedIterator it = new TimeSyncedIterator(Integer.toString(index), query.getQueries().get(index).getFilterTagKs(), dps);
        it.setFillPolicy(new NumericFillPolicy(FillPolicy.NOT_A_NUMBER));
        iterators.put(Integer.toString(index), it);
        index++;
    }
}
Also used : Query(net.opentsdb.core.Query) TSQuery(net.opentsdb.core.TSQuery) TSSubQuery(net.opentsdb.core.TSSubQuery) DataPoints(net.opentsdb.core.DataPoints) TSSubQuery(net.opentsdb.core.TSSubQuery) TSQuery(net.opentsdb.core.TSQuery) Pair(net.opentsdb.utils.Pair)

Example 22 with TSQuery

use of net.opentsdb.core.TSQuery in project opentsdb by OpenTSDB.

the class QueryExample method main.

public static void main(final String[] args) throws IOException {
    // Set these as arguments so you don't have to keep path information in
    // source files 
    String pathToConfigFile = (args != null && args.length > 0 ? args[0] : null);
    // Create a config object with a path to the file for parsing. Or manually
    // override settings.
    // e.g. config.overrideConfig("tsd.storage.hbase.zk_quorum", "localhost");
    final Config config;
    if (pathToConfigFile != null && !pathToConfigFile.isEmpty()) {
        config = new Config(pathToConfigFile);
    } else {
        // Search for a default config from /etc/opentsdb/opentsdb.conf, etc.
        config = new Config(true);
    }
    final TSDB tsdb = new TSDB(config);
    // main query
    final TSQuery query = new TSQuery();
    // use any string format from
    // http://opentsdb.net/docs/build/html/user_guide/query/dates.html
    query.setStart("1h-ago");
    // Optional: set other global query params
    // at least one sub query required. This is where you specify the metric and
    // tags
    final TSSubQuery subQuery = new TSSubQuery();
    subQuery.setMetric("my.tsdb.test.metric");
    // filters are optional but useful.
    final List<TagVFilter> filters = new ArrayList<TagVFilter>(1);
    filters.add(new TagVFilter.Builder().setType("literal_or").setFilter("example1").setTagk("script").setGroupBy(true).build());
    subQuery.setFilters(filters);
    // you do have to set an aggregator. Just provide the name as a string
    subQuery.setAggregator("sum");
    // IMPORTANT: don't forget to add the subQuery
    final ArrayList<TSSubQuery> subQueries = new ArrayList<TSSubQuery>(1);
    subQueries.add(subQuery);
    query.setQueries(subQueries);
    // otherwise we aggregate on the second. 
    query.setMsResolution(true);
    // make sure the query is valid. This will throw exceptions if something
    // is missing
    query.validateAndSetQuery();
    // compile the queries into TsdbQuery objects behind the scenes
    Query[] tsdbqueries = query.buildQueries(tsdb);
    // create some arrays for storing the results and the async calls
    final int nqueries = tsdbqueries.length;
    final ArrayList<DataPoints[]> results = new ArrayList<DataPoints[]>(nqueries);
    final ArrayList<Deferred<DataPoints[]>> deferreds = new ArrayList<Deferred<DataPoints[]>>(nqueries);
    // deferred in an array so we can wait for them to complete.
    for (int i = 0; i < nqueries; i++) {
        deferreds.add(tsdbqueries[i].runAsync());
    }
    // Start timer
    long startTime = DateTime.nanoTime();
    // query has finished
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {

        public Object call(final ArrayList<DataPoints[]> queryResults) throws Exception {
            results.addAll(queryResults);
            return null;
        }
    }
    // Make sure to handle any errors that might crop up
    class QueriesEB implements Callback<Object, Exception> {

        @Override
        public Object call(final Exception e) throws Exception {
            System.err.println("Queries failed");
            e.printStackTrace();
            return null;
        }
    }
    // have completed.
    try {
        Deferred.groupInOrder(deferreds).addCallback(new QueriesCB()).addErrback(new QueriesEB()).join();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // End timer.
    double elapsedTime = DateTime.msFromNanoDiff(DateTime.nanoTime(), startTime);
    System.out.println("Query returned in: " + elapsedTime + " milliseconds.");
    // results and do any processing necessary.
    for (final DataPoints[] dataSets : results) {
        for (final DataPoints data : dataSets) {
            System.out.print(data.metricName());
            Map<String, String> resolvedTags = data.getTags();
            for (final Map.Entry<String, String> pair : resolvedTags.entrySet()) {
                System.out.print(" " + pair.getKey() + "=" + pair.getValue());
            }
            System.out.print("\n");
            final SeekableView it = data.iterator();
            /*
         * An important point about SeekableView:
         * Because no data is copied during iteration and no new object gets
         * created, the DataPoint returned must not be stored and gets
         * invalidated as soon as next is called on the iterator (actually it
         * doesn't get invalidated but rather its contents changes). If you want
         * to store individual data points, you need to copy the timestamp and
         * value out of each DataPoint into your own data structures.
         * 
         * In the vast majority of cases, the iterator will be used to go once
         * through all the data points, which is why it's not a problem if the
         * iterator acts just as a transient "view". Iterating will be very
         * cheap since no memory allocation is required (except to instantiate
         * the actual iterator at the beginning).
         */
            while (it.hasNext()) {
                final DataPoint dp = it.next();
                System.out.println("  " + dp.timestamp() + " " + (dp.isInteger() ? dp.longValue() : dp.doubleValue()));
            }
            System.out.println("");
        }
    }
    // Gracefully shutdown connection to TSDB
    try {
        tsdb.shutdown().join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Query(net.opentsdb.core.Query) TSQuery(net.opentsdb.core.TSQuery) TSSubQuery(net.opentsdb.core.TSSubQuery) Config(net.opentsdb.utils.Config) Deferred(com.stumbleupon.async.Deferred) ArrayList(java.util.ArrayList) DataPoints(net.opentsdb.core.DataPoints) TSQuery(net.opentsdb.core.TSQuery) TagVFilter(net.opentsdb.query.filter.TagVFilter) DataPoint(net.opentsdb.core.DataPoint) TSDB(net.opentsdb.core.TSDB) SeekableView(net.opentsdb.core.SeekableView) TSSubQuery(net.opentsdb.core.TSSubQuery) DataPoint(net.opentsdb.core.DataPoint) IOException(java.io.IOException) Callback(com.stumbleupon.async.Callback) Map(java.util.Map)

Example 23 with TSQuery

use of net.opentsdb.core.TSQuery in project opentsdb by OpenTSDB.

the class GraphHandler method doGraph.

// TODO(HugoMFernandes): Most of this (query-related) logic is implemented in
// net.opentsdb.tsd.QueryRpc.java (which actually does this asynchronously),
// so we should refactor both classes to split the actual logic used to
// generate the data from the actual visualization (removing all duped code).
private void doGraph(final TSDB tsdb, final HttpQuery query) throws IOException {
    final String basepath = getGnuplotBasePath(tsdb, query);
    long start_time = DateTime.parseDateTimeString(query.getRequiredQueryStringParam("start"), query.getQueryStringParam("tz"));
    final boolean nocache = query.hasQueryStringParam("nocache");
    if (start_time == -1) {
        throw BadRequestException.missingParameter("start");
    } else {
        // temp fixup to seconds from ms until the rest of TSDB supports ms
        // Note you can't append this to the DateTime.parseDateTimeString() call as
        // it clobbers -1 results
        start_time /= 1000;
    }
    long end_time = DateTime.parseDateTimeString(query.getQueryStringParam("end"), query.getQueryStringParam("tz"));
    final long now = System.currentTimeMillis() / 1000;
    if (end_time == -1) {
        end_time = now;
    } else {
        // temp fixup to seconds from ms until the rest of TSDB supports ms
        // Note you can't append this to the DateTime.parseDateTimeString() call as
        // it clobbers -1 results
        end_time /= 1000;
    }
    final int max_age = computeMaxAge(query, start_time, end_time, now);
    if (!nocache && isDiskCacheHit(query, end_time, max_age, basepath)) {
        return;
    }
    // Parse TSQuery from HTTP query
    final TSQuery tsquery = QueryRpc.parseQuery(tsdb, query);
    tsquery.validateAndSetQuery();
    // Build the queries for the parsed TSQuery
    Query[] tsdbqueries = tsquery.buildQueries(tsdb);
    List<String> options = query.getQueryStringParams("o");
    if (options == null) {
        options = new ArrayList<String>(tsdbqueries.length);
        for (int i = 0; i < tsdbqueries.length; i++) {
            options.add("");
        }
    } else if (options.size() != tsdbqueries.length) {
        throw new BadRequestException(options.size() + " `o' parameters, but " + tsdbqueries.length + " `m' parameters.");
    }
    for (final Query tsdbquery : tsdbqueries) {
        try {
            tsdbquery.setStartTime(start_time);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("start time: " + e.getMessage());
        }
        try {
            tsdbquery.setEndTime(end_time);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("end time: " + e.getMessage());
        }
    }
    final Plot plot = new Plot(start_time, end_time, DateTime.timezones.get(query.getQueryStringParam("tz")));
    setPlotDimensions(query, plot);
    setPlotParams(query, plot);
    final int nqueries = tsdbqueries.length;
    @SuppressWarnings("unchecked") final HashSet<String>[] aggregated_tags = new HashSet[nqueries];
    int npoints = 0;
    for (int i = 0; i < nqueries; i++) {
        try {
            // execute the TSDB query!
            // XXX This is slow and will block Netty.  TODO(tsuna): Don't block.
            // TODO(tsuna): Optimization: run each query in parallel.
            final DataPoints[] series = tsdbqueries[i].run();
            for (final DataPoints datapoints : series) {
                plot.add(datapoints, options.get(i));
                aggregated_tags[i] = new HashSet<String>();
                aggregated_tags[i].addAll(datapoints.getAggregatedTags());
                npoints += datapoints.aggregatedSize();
            }
        } catch (RuntimeException e) {
            logInfo(query, "Query failed (stack trace coming): " + tsdbqueries[i]);
            throw e;
        }
        // free()
        tsdbqueries[i] = null;
    }
    // free()
    tsdbqueries = null;
    if (query.hasQueryStringParam("ascii")) {
        respondAsciiQuery(query, max_age, basepath, plot);
        return;
    }
    final RunGnuplot rungnuplot = new RunGnuplot(query, max_age, plot, basepath, aggregated_tags, npoints);
    class ErrorCB implements Callback<Object, Exception> {

        public Object call(final Exception e) throws Exception {
            LOG.warn("Failed to retrieve global annotations: ", e);
            throw e;
        }
    }
    class GlobalCB implements Callback<Object, List<Annotation>> {

        public Object call(final List<Annotation> global_annotations) throws Exception {
            rungnuplot.plot.setGlobals(global_annotations);
            execGnuplot(rungnuplot, query);
            return null;
        }
    }
    // Fetch global annotations, if needed
    if (!tsquery.getNoAnnotations() && tsquery.getGlobalAnnotations()) {
        Annotation.getGlobalAnnotations(tsdb, start_time, end_time).addCallback(new GlobalCB()).addErrback(new ErrorCB());
    } else {
        execGnuplot(rungnuplot, query);
    }
}
Also used : Query(net.opentsdb.core.Query) TSQuery(net.opentsdb.core.TSQuery) DataPoints(net.opentsdb.core.DataPoints) TSQuery(net.opentsdb.core.TSQuery) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) Plot(net.opentsdb.graph.Plot) DataPoint(net.opentsdb.core.DataPoint) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) Annotation(net.opentsdb.meta.Annotation) Callback(com.stumbleupon.async.Callback)

Example 24 with TSQuery

use of net.opentsdb.core.TSQuery in project opentsdb by OpenTSDB.

the class QueryRpc method parseQuery.

/**
   * Parses a query string legacy style query from the URI
   * @param tsdb The TSDB we belong to
   * @param query The HTTP Query for parsing
   * @param expressions A list of parsed expression trees filled from the URI.
   * If this is null, it means any expressions in the URI will be skipped.
   * @return A TSQuery if parsing was successful
   * @throws BadRequestException if parsing was unsuccessful
   * @since 2.3
   */
public static TSQuery parseQuery(final TSDB tsdb, final HttpQuery query, final List<ExpressionTree> expressions) {
    final TSQuery data_query = new TSQuery();
    data_query.setStart(query.getRequiredQueryStringParam("start"));
    data_query.setEnd(query.getQueryStringParam("end"));
    if (query.hasQueryStringParam("padding")) {
        data_query.setPadding(true);
    }
    if (query.hasQueryStringParam("no_annotations")) {
        data_query.setNoAnnotations(true);
    }
    if (query.hasQueryStringParam("global_annotations")) {
        data_query.setGlobalAnnotations(true);
    }
    if (query.hasQueryStringParam("show_tsuids")) {
        data_query.setShowTSUIDs(true);
    }
    if (query.hasQueryStringParam("ms")) {
        data_query.setMsResolution(true);
    }
    if (query.hasQueryStringParam("show_query")) {
        data_query.setShowQuery(true);
    }
    if (query.hasQueryStringParam("show_stats")) {
        data_query.setShowStats(true);
    }
    if (query.hasQueryStringParam("show_summary")) {
        data_query.setShowSummary(true);
    }
    // handle tsuid queries first
    if (query.hasQueryStringParam("tsuid")) {
        final List<String> tsuids = query.getQueryStringParams("tsuid");
        for (String q : tsuids) {
            parseTsuidTypeSubQuery(q, data_query);
        }
    }
    if (query.hasQueryStringParam("m")) {
        final List<String> legacy_queries = query.getQueryStringParams("m");
        for (String q : legacy_queries) {
            parseMTypeSubQuery(q, data_query);
        }
    }
    // param that could stand for experimental or expression ;)
    if (expressions != null) {
        if (query.hasQueryStringParam("exp")) {
            final List<String> uri_expressions = query.getQueryStringParams("exp");
            final List<String> metric_queries = new ArrayList<String>(uri_expressions.size());
            // parse the expressions into their trees. If one or more expressions 
            // are improper then it will toss an exception up
            expressions.addAll(Expressions.parseExpressions(uri_expressions, data_query, metric_queries));
            // TSQuery list so that we fetch the data for them.
            for (final String mq : metric_queries) {
                parseMTypeSubQuery(mq, data_query);
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received a request with an expression but at the " + "wrong endpoint: " + query);
        }
    }
    if (data_query.getQueries() == null || data_query.getQueries().size() < 1) {
        throw new BadRequestException("Missing sub queries");
    }
    return data_query;
}
Also used : TSQuery(net.opentsdb.core.TSQuery) ArrayList(java.util.ArrayList)

Example 25 with TSQuery

use of net.opentsdb.core.TSQuery in project opentsdb by OpenTSDB.

the class TestQueryStats method ctorDuplicate.

@Test
public void ctorDuplicate() throws Exception {
    QueryStats.setEnableDuplicates(false);
    final TSQuery query = new TSQuery();
    query.setStart("1h-ago");
    final QueryStats stats = new QueryStats(remote, query, headers);
    assertNotNull(stats);
    final Map<String, Object> map = QueryStats.getRunningAndCompleteStats();
    assertNotNull(map);
    assertEquals(1, ((List<Object>) map.get("running")).size());
    assertEquals(0, ((Collection<QueryStats>) map.get("completed")).size());
    try {
        new QueryStats(remote, query, headers);
        fail("Expected a QueryException");
    } catch (QueryException e) {
    }
    QueryStats.setEnableDuplicates(true);
}
Also used : TSQuery(net.opentsdb.core.TSQuery) QueryException(net.opentsdb.core.QueryException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

TSQuery (net.opentsdb.core.TSQuery)63 Test (org.junit.Test)57 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)57 TSSubQuery (net.opentsdb.core.TSSubQuery)30 ArrayList (java.util.ArrayList)18 DataPoints (net.opentsdb.core.DataPoints)17 Annotation (net.opentsdb.meta.Annotation)15 MockDataPoints (net.opentsdb.storage.MockDataPoints)13 Matchers.anyString (org.mockito.Matchers.anyString)10 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)9 TagVWildcardFilter (net.opentsdb.query.filter.TagVWildcardFilter)7 Query (net.opentsdb.core.Query)4 Callback (com.stumbleupon.async.Callback)3 IOException (java.io.IOException)3 NoSuchUniqueId (net.opentsdb.uid.NoSuchUniqueId)3 Deferred (com.stumbleupon.async.Deferred)2 List (java.util.List)2 DataPoint (net.opentsdb.core.DataPoint)2 QueryException (net.opentsdb.core.QueryException)2 TagVLiteralOrFilter (net.opentsdb.query.filter.TagVLiteralOrFilter)2