use of net.opentsdb.core.DataPoints in project opentsdb by OpenTSDB.
the class CliQuery method doQuery.
private static Plot doQuery(final TSDB tsdb, final String[] args, final boolean want_plot) {
final ArrayList<String> plotparams = new ArrayList<String>();
final ArrayList<Query> queries = new ArrayList<Query>();
final ArrayList<String> plotoptions = new ArrayList<String>();
parseCommandLineQuery(args, tsdb, queries, plotparams, plotoptions);
if (queries.isEmpty()) {
usage(null, "Not enough arguments, need at least one query.", 2);
}
final Plot plot = (want_plot ? new Plot(queries.get(0).getStartTime(), queries.get(0).getEndTime()) : null);
if (want_plot) {
plot.setParams(parsePlotParams(plotparams));
}
final int nqueries = queries.size();
for (int i = 0; i < nqueries; i++) {
// TODO(tsuna): Optimization: run each query in parallel.
final StringBuilder buf = want_plot ? null : new StringBuilder();
for (final DataPoints datapoints : queries.get(i).run()) {
if (want_plot) {
plot.add(datapoints, plotoptions.get(i));
} else {
final String metric = datapoints.metricName();
final String tagz = datapoints.getTags().toString();
for (final DataPoint datapoint : datapoints) {
buf.append(metric).append(' ').append(datapoint.timestamp()).append(' ');
if (datapoint.isInteger()) {
buf.append(datapoint.longValue());
} else {
buf.append(String.format("%f", datapoint.doubleValue()));
}
buf.append(' ').append(tagz).append('\n');
System.out.print(buf);
buf.delete(0, buf.length());
}
}
}
}
return plot;
}
use of net.opentsdb.core.DataPoints in project opentsdb by OpenTSDB.
the class Alias method evaluate.
@Override
public DataPoints[] evaluate(final TSQuery data_query, final List<DataPoints[]> query_results, final List<String> params) {
if (data_query == null) {
throw new IllegalArgumentException("Missing time series query");
}
if (query_results == null || query_results.isEmpty()) {
return new DataPoints[] {};
}
if (params == null || params.isEmpty()) {
throw new IllegalArgumentException("Missing the alias");
}
final String alias_template = COMMA_JOINER.join(params);
int num_results = 0;
for (DataPoints[] results : query_results) {
num_results += results.length;
}
final DataPoints[] results = new DataPoints[num_results];
int ix = 0;
// one or more sub queries (m=...&m=...&m=...)
for (final DataPoints[] sub_query_result : query_results) {
// group bys (m=sum:foo{host=*})
for (final DataPoints dps : sub_query_result) {
// TODO(cl) - Using an array as the size function may not return the exact
// results and we should figure a way to avoid copying data anyway.
final List<DataPoint> new_dps_list = new ArrayList<DataPoint>();
final SeekableView view = dps.iterator();
while (view.hasNext()) {
DataPoint pt = view.next();
if (pt.isInteger()) {
new_dps_list.add(MutableDataPoint.ofLongValue(pt.timestamp(), Math.abs(pt.longValue())));
} else {
new_dps_list.add(MutableDataPoint.ofDoubleValue(pt.timestamp(), Math.abs(pt.doubleValue())));
}
}
final DataPoint[] new_dps = new DataPoint[dps.size()];
new_dps_list.toArray(new_dps);
final PostAggregatedDataPoints padps = new PostAggregatedDataPoints(dps, new_dps);
padps.setAlias(alias_template);
results[ix++] = padps;
}
}
return results;
}
use of net.opentsdb.core.DataPoints in project opentsdb by OpenTSDB.
the class QueryExecutor method execute.
/**
* Execute the RPC and serialize the response
* @param query The HTTP query to parse and and return results to
*/
public void execute(final HttpQuery query) {
http_query = query;
final QueryStats query_stats = new QueryStats(query.getRemoteAddress(), ts_query, query.getHeaders());
ts_query.setQueryStats(query_stats);
/**
* Sends the serialized results to the caller. This should be the very
* last callback executed.
*/
class CompleteCB implements Callback<Object, ChannelBuffer> {
@Override
public Object call(final ChannelBuffer cb) throws Exception {
query.sendReply(cb);
return null;
}
}
/**
* After all of the queries have run and we have data (or not) then we
* need to compile the iterators.
* This class could probably be improved:
* First we iterate over the results AND for each result, iterate over
* the expressions, giving a time synced iterator to each expression that
* needs the result set.
* THEN we iterate over the expressions again and build a DAG to determine
* if any of the expressions require the output of an expression. If so
* then we add the expressions to the proper parent and compile them in
* order.
* After all of that we're ready to start serializing and iterating
* over the results.
*/
class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
public Object call(final ArrayList<DataPoints[]> query_results) throws Exception {
for (int i = 0; i < query_results.size(); i++) {
final TSSubQuery sub = ts_query.getQueries().get(i);
Iterator<Entry<String, TSSubQuery>> it = sub_queries.entrySet().iterator();
while (it.hasNext()) {
final Entry<String, TSSubQuery> entry = it.next();
if (entry.getValue().equals(sub)) {
sub_query_results.put(entry.getKey(), query_results.get(i));
for (final ExpressionIterator ei : expressions.values()) {
if (ei.getVariableNames().contains(entry.getKey())) {
final TimeSyncedIterator tsi = new TimeSyncedIterator(entry.getKey(), sub.getFilterTagKs(), query_results.get(i));
final NumericFillPolicy fill = fills.get(entry.getKey());
if (fill != null) {
tsi.setFillPolicy(fill);
}
ei.addResults(entry.getKey(), tsi);
if (LOG.isDebugEnabled()) {
LOG.debug("Added results for " + entry.getKey() + " to " + ei.getId());
}
}
}
}
}
}
// handle nested expressions
final DirectedAcyclicGraph<String, DefaultEdge> graph = new DirectedAcyclicGraph<String, DefaultEdge>(DefaultEdge.class);
for (final Entry<String, ExpressionIterator> eii : expressions.entrySet()) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Expression entry key is %s, value is %s", eii.getKey(), eii.getValue().toString()));
LOG.debug(String.format("Time to loop through the variable names " + "for %s", eii.getKey()));
}
if (!graph.containsVertex(eii.getKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding vertex " + eii.getKey());
}
graph.addVertex(eii.getKey());
}
for (final String var : eii.getValue().getVariableNames()) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("var is %s", var));
}
final ExpressionIterator ei = expressions.get(var);
if (ei != null) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("The expression iterator for %s is %s", var, ei.toString()));
}
// TODO - really ought to calculate this earlier
if (eii.getKey().equals(var)) {
throw new IllegalArgumentException("Self referencing expression found: " + eii.getKey());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Nested expression detected. " + eii.getKey() + " depends on " + var);
}
if (!graph.containsVertex(eii.getKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Added vertex " + eii.getKey());
}
graph.addVertex(eii.getKey());
} else if (LOG.isDebugEnabled()) {
LOG.debug("Already contains vertex " + eii.getKey());
}
if (!graph.containsVertex(var)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Added vertex " + var);
}
graph.addVertex(var);
} else if (LOG.isDebugEnabled()) {
LOG.debug("Already contains vertex " + var);
}
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Added Edge " + eii.getKey() + " - " + var);
}
graph.addDagEdge(eii.getKey(), var);
} catch (CycleFoundException cfe) {
throw new IllegalArgumentException("Circular reference found: " + eii.getKey(), cfe);
}
} else if (LOG.isDebugEnabled()) {
LOG.debug(String.format("The expression iterator for %s is null", var));
}
}
}
// compile all of the expressions
final long intersect_start = DateTime.currentTimeMillis();
final Integer expressionLength = expressions.size();
final ExpressionIterator[] compile_stack = new ExpressionIterator[expressionLength];
final TopologicalOrderIterator<String, DefaultEdge> it = new TopologicalOrderIterator<String, DefaultEdge>(graph);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Expressions Size is %d", expressionLength));
LOG.debug(String.format("Topology Iterator %s", it.toString()));
}
int i = 0;
while (it.hasNext()) {
String next = it.next();
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Expression: %s", next));
}
ExpressionIterator ei = expressions.get(next);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Expression Iterator: %s", ei.toString()));
}
if (ei == null) {
LOG.error(String.format("The expression iterator for %s is null", next));
}
compile_stack[i] = ei;
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Added expression %s to compile_stack[%d]", next, i));
}
i++;
}
if (i != expressionLength) {
throw new IOException(String.format(" Internal Error: Fewer " + "expressions where added to the compile stack than " + "expressions.size (%d instead of %d)", i, expressionLength));
}
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("compile stack length: %d", compile_stack.length));
}
for (int x = compile_stack.length - 1; x >= 0; x--) {
if (compile_stack[x] == null) {
throw new NullPointerException(String.format("Item %d in " + "compile_stack[] is null", x));
}
// look for and add expressions
for (final String var : compile_stack[x].getVariableNames()) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Looking for variable %s for %s", var, compile_stack[x].getId()));
}
ExpressionIterator source = expressions.get(var);
if (source != null) {
compile_stack[x].addResults(var, source.getCopy());
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Adding expression %s to %s", source.getId(), compile_stack[x].getId()));
}
}
}
compile_stack[x].compile();
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Successfully compiled %s", compile_stack[x].getId()));
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Finished compilations in " + (DateTime.currentTimeMillis() - intersect_start) + " ms");
}
return serialize().addCallback(new CompleteCB()).addErrback(new ErrorCB());
}
}
/**
* Callback executed after we have resolved the metric, tag names and tag
* values to their respective UIDs. This callback then runs the actual
* queries and fetches their results.
*/
class BuildCB implements Callback<Deferred<Object>, net.opentsdb.core.Query[]> {
@Override
public Deferred<Object> call(final net.opentsdb.core.Query[] queries) {
final ArrayList<Deferred<DataPoints[]>> deferreds = new ArrayList<Deferred<DataPoints[]>>(queries.length);
for (final net.opentsdb.core.Query query : queries) {
deferreds.add(query.runAsync());
}
return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB()).addErrback(new ErrorCB());
}
}
// TODO - only run the ones that will be involved in an output. Folks WILL
// ask for stuff they don't need.... *sigh*
ts_query.buildQueriesAsync(tsdb).addCallback(new BuildCB()).addErrback(new ErrorCB());
}
use of net.opentsdb.core.DataPoints in project opentsdb by OpenTSDB.
the class QueryRpc method handleQuery.
/**
* Processing for a data point query
* @param tsdb The TSDB to which we belong
* @param query The HTTP query to parse/respond
* @param allow_expressions Whether or not expressions should be parsed
* (based on the endpoint)
*/
private void handleQuery(final TSDB tsdb, final HttpQuery query, final boolean allow_expressions) {
final long start = DateTime.currentTimeMillis();
final TSQuery data_query;
final List<ExpressionTree> expressions;
if (query.method() == HttpMethod.POST) {
switch(query.apiVersion()) {
case 0:
case 1:
data_query = query.serializer().parseQueryV1();
break;
default:
query_invalid.incrementAndGet();
throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented");
}
expressions = null;
} else {
expressions = new ArrayList<ExpressionTree>();
data_query = parseQuery(tsdb, query, expressions);
}
if (query.getAPIMethod() == HttpMethod.DELETE && tsdb.getConfig().getBoolean("tsd.http.query.allow_delete")) {
data_query.setDelete(true);
}
// validate and then compile the queries
try {
LOG.debug(data_query.toString());
data_query.validateAndSetQuery();
} catch (Exception e) {
throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, e.getMessage(), data_query.toString(), e);
}
// if the user tried this query multiple times from the same IP and src port
// they'll be rejected on subsequent calls
final QueryStats query_stats = new QueryStats(query.getRemoteAddress(), data_query, query.getPrintableHeaders());
data_query.setQueryStats(query_stats);
query.setStats(query_stats);
final int nqueries = data_query.getQueries().size();
final ArrayList<DataPoints[]> results = new ArrayList<DataPoints[]>(nqueries);
final List<Annotation> globals = new ArrayList<Annotation>();
/** This has to be attached to callbacks or we may never respond to clients */
class ErrorCB implements Callback<Object, Exception> {
public Object call(final Exception e) throws Exception {
Throwable ex = e;
try {
LOG.error("Query exception: ", e);
if (ex instanceof DeferredGroupException) {
ex = e.getCause();
while (ex != null && ex instanceof DeferredGroupException) {
ex = ex.getCause();
}
if (ex == null) {
LOG.error("The deferred group exception didn't have a cause???");
}
}
if (ex instanceof RpcTimedOutException) {
query_stats.markSerialized(HttpResponseStatus.REQUEST_TIMEOUT, ex);
query.badRequest(new BadRequestException(HttpResponseStatus.REQUEST_TIMEOUT, ex.getMessage()));
query_exceptions.incrementAndGet();
} else if (ex instanceof HBaseException) {
query_stats.markSerialized(HttpResponseStatus.FAILED_DEPENDENCY, ex);
query.badRequest(new BadRequestException(HttpResponseStatus.FAILED_DEPENDENCY, ex.getMessage()));
query_exceptions.incrementAndGet();
} else if (ex instanceof QueryException) {
query_stats.markSerialized(((QueryException) ex).getStatus(), ex);
query.badRequest(new BadRequestException(((QueryException) ex).getStatus(), ex.getMessage()));
query_exceptions.incrementAndGet();
} else if (ex instanceof BadRequestException) {
query_stats.markSerialized(((BadRequestException) ex).getStatus(), ex);
query.badRequest((BadRequestException) ex);
query_invalid.incrementAndGet();
} else if (ex instanceof NoSuchUniqueName) {
query_stats.markSerialized(HttpResponseStatus.BAD_REQUEST, ex);
query.badRequest(new BadRequestException(ex));
query_invalid.incrementAndGet();
} else {
query_stats.markSerialized(HttpResponseStatus.INTERNAL_SERVER_ERROR, ex);
query.badRequest(new BadRequestException(ex));
query_exceptions.incrementAndGet();
}
} catch (RuntimeException ex2) {
LOG.error("Exception thrown during exception handling", ex2);
query_stats.markSerialized(HttpResponseStatus.INTERNAL_SERVER_ERROR, ex2);
query.sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR, ex2.getMessage().getBytes());
query_exceptions.incrementAndGet();
}
return null;
}
}
/**
* After all of the queries have run, we get the results in the order given
* and add dump the results in an array
*/
class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
public Object call(final ArrayList<DataPoints[]> query_results) throws Exception {
if (allow_expressions) {
// process each of the expressions into a new list, then merge it
// with the original. This avoids possible recursion loops.
final List<DataPoints[]> expression_results = new ArrayList<DataPoints[]>(expressions.size());
// let exceptions bubble up
for (final ExpressionTree expression : expressions) {
expression_results.add(expression.evaluate(query_results));
}
results.addAll(expression_results);
} else {
results.addAll(query_results);
}
/** Simply returns the buffer once serialization is complete and logs it */
class SendIt implements Callback<Object, ChannelBuffer> {
public Object call(final ChannelBuffer buffer) throws Exception {
query.sendReply(buffer);
query_success.incrementAndGet();
return null;
}
}
switch(query.apiVersion()) {
case 0:
case 1:
query.serializer().formatQueryAsyncV1(data_query, results, globals).addCallback(new SendIt()).addErrback(new ErrorCB());
break;
default:
query_invalid.incrementAndGet();
throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "Requested API version not implemented", "Version " + query.apiVersion() + " is not implemented");
}
return null;
}
}
/**
* Callback executed after we have resolved the metric, tag names and tag
* values to their respective UIDs. This callback then runs the actual
* queries and fetches their results.
*/
class BuildCB implements Callback<Deferred<Object>, Query[]> {
@Override
public Deferred<Object> call(final Query[] queries) {
final ArrayList<Deferred<DataPoints[]>> deferreds = new ArrayList<Deferred<DataPoints[]>>(queries.length);
for (final Query query : queries) {
deferreds.add(query.runAsync());
}
return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB());
}
}
/** Handles storing the global annotations after fetching them */
class GlobalCB implements Callback<Object, List<Annotation>> {
public Object call(final List<Annotation> annotations) throws Exception {
globals.addAll(annotations);
return data_query.buildQueriesAsync(tsdb).addCallback(new BuildCB());
}
}
// when complete
if (!data_query.getNoAnnotations() && data_query.getGlobalAnnotations()) {
Annotation.getGlobalAnnotations(tsdb, data_query.startTime() / 1000, data_query.endTime() / 1000).addCallback(new GlobalCB()).addErrback(new ErrorCB());
} else {
data_query.buildQueriesAsync(tsdb).addCallback(new BuildCB()).addErrback(new ErrorCB());
}
}
use of net.opentsdb.core.DataPoints in project opentsdb by OpenTSDB.
the class GraphHandler method respondAsciiQuery.
/**
* Respond to a query that wants the output in ASCII.
* <p>
* When a query specifies the "ascii" query string parameter, we send the
* data points back to the client in plain text instead of sending a PNG.
* @param query The query we're currently serving.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @param plot The plot object to generate Gnuplot's input files.
*/
private static void respondAsciiQuery(final HttpQuery query, final int max_age, final String basepath, final Plot plot) {
final String path = basepath + ".txt";
PrintWriter asciifile;
try {
asciifile = new PrintWriter(path);
} catch (IOException e) {
query.internalError(e);
return;
}
try {
final StringBuilder tagbuf = new StringBuilder();
for (final DataPoints dp : plot.getDataPoints()) {
final String metric = dp.metricName();
tagbuf.setLength(0);
for (final Map.Entry<String, String> tag : dp.getTags().entrySet()) {
tagbuf.append(' ').append(tag.getKey()).append('=').append(tag.getValue());
}
for (final DataPoint d : dp) {
if (d.isInteger()) {
printMetricHeader(asciifile, metric, d.timestamp());
asciifile.print(d.longValue());
} else {
// Doubles require extra processing.
final double value = d.doubleValue();
// Value might be NaN or infinity.
if (Double.isInfinite(value)) {
// Infinity is invalid.
throw new IllegalStateException("Infinity:" + value + " d=" + d + ", query=" + query);
} else if (Double.isNaN(value)) {
// NaNs should be skipped.
continue;
}
printMetricHeader(asciifile, metric, d.timestamp());
asciifile.print(value);
}
asciifile.print(tagbuf);
asciifile.print('\n');
}
}
} finally {
asciifile.close();
}
try {
query.sendFile(path, max_age);
} catch (IOException e) {
query.internalError(e);
}
}
Aggregations