Search in sources :

Example 21 with Deferred

use of com.stumbleupon.async.Deferred in project opentsdb by OpenTSDB.

the class BaseTsdbTest method setupTagkMaps.

/** Adds the static UIDs to the tag keys UID mock object */
void setupTagkMaps() {
    when(tag_names.getId(TAGK_STRING)).thenReturn(TAGK_BYTES);
    when(tag_names.getOrCreateId(TAGK_STRING)).thenReturn(TAGK_BYTES);
    when(tag_names.getIdAsync(TAGK_STRING)).thenAnswer(new Answer<Deferred<byte[]>>() {

        @Override
        public Deferred<byte[]> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult(TAGK_BYTES);
        }
    });
    when(tag_names.getOrCreateIdAsync(TAGK_STRING)).thenReturn(Deferred.fromResult(TAGK_BYTES));
    when(tag_names.getId(TAGK_B_STRING)).thenReturn(TAGK_B_BYTES);
    when(tag_names.getOrCreateId(TAGK_B_STRING)).thenReturn(TAGK_B_BYTES);
    when(tag_names.getIdAsync(TAGK_B_STRING)).thenAnswer(new Answer<Deferred<byte[]>>() {

        @Override
        public Deferred<byte[]> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult(TAGK_B_BYTES);
        }
    });
    when(tag_names.getOrCreateIdAsync(TAGK_B_STRING)).thenReturn(Deferred.fromResult(TAGK_B_BYTES));
    when(tag_names.getNameAsync(TAGK_BYTES)).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult(TAGK_STRING);
        }
    });
    when(tag_names.getNameAsync(TAGK_B_BYTES)).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult(TAGK_B_STRING);
        }
    });
    when(tag_names.getNameAsync(NSUI_TAGK)).thenThrow(new NoSuchUniqueId("tagk", NSUI_TAGK));
    final NoSuchUniqueName nsun = new NoSuchUniqueName(NSUN_TAGK, "tagk");
    when(tag_names.getId(NSUN_TAGK)).thenThrow(nsun);
    when(tag_names.getIdAsync(NSUN_TAGK)).thenReturn(Deferred.<byte[]>fromError(nsun));
    // Iterate over the tagk UIDs and handle both forward and reverse
    for (final Map.Entry<String, byte[]> uid : TAGK_UIDS.entrySet()) {
        when(tag_names.getId(uid.getKey())).thenReturn(uid.getValue());
        when(tag_names.getIdAsync(uid.getKey())).thenAnswer(new Answer<Deferred<byte[]>>() {

            @Override
            public Deferred<byte[]> answer(InvocationOnMock invocation) throws Throwable {
                return Deferred.fromResult(uid.getValue());
            }
        });
        when(tag_names.getOrCreateId(uid.getKey())).thenReturn(uid.getValue());
        when(tag_names.getNameAsync(uid.getValue())).thenAnswer(new Answer<Deferred<String>>() {

            @Override
            public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
                return Deferred.fromResult(uid.getKey());
            }
        });
    }
}
Also used : InvocationOnMock(org.mockito.invocation.InvocationOnMock) NoSuchUniqueId(net.opentsdb.uid.NoSuchUniqueId) Deferred(com.stumbleupon.async.Deferred) HashMap(java.util.HashMap) Map(java.util.Map) NoSuchUniqueName(net.opentsdb.uid.NoSuchUniqueName)

Example 22 with Deferred

use of com.stumbleupon.async.Deferred in project opentsdb by OpenTSDB.

the class TestUniqueId method renameRaceCondition.

@Test(expected = IllegalStateException.class)
public void renameRaceCondition() throws Exception {
    // Simulate a race between client A(default) and client B.
    // A and B rename same UID to different name.
    // B waits till A start to invoke PutRequest to start.
    uid = new UniqueId(client, table, METRIC, 3);
    HBaseClient client_b = mock(HBaseClient.class);
    final UniqueId uid_b = new UniqueId(client_b, table, METRIC, 3);
    final byte[] foo_id = { 0, 'a', 0x42 };
    final byte[] foo_name = { 'f', 'o', 'o' };
    ArrayList<KeyValue> kvs = new ArrayList<KeyValue>(1);
    kvs.add(new KeyValue(foo_name, ID, METRIC_ARRAY, foo_id));
    when(client_b.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
    when(client_b.put(anyPut())).thenAnswer(answerTrue());
    when(client_b.delete(anyDelete())).thenAnswer(answerTrue());
    final Answer<Deferred<Boolean>> the_race = new Answer<Deferred<Boolean>>() {

        public Deferred<Boolean> answer(final InvocationOnMock inv) throws Exception {
            uid_b.rename("foo", "xyz");
            return Deferred.fromResult(true);
        }
    };
    when(client.get(anyGet())).thenReturn(Deferred.fromResult(kvs)).thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(null));
    when(client.put(anyPut())).thenAnswer(the_race);
    when(client.delete(anyDelete())).thenAnswer(answerTrue());
    uid.rename("foo", "bar");
}
Also used : Answer(org.mockito.stubbing.Answer) KeyValue(org.hbase.async.KeyValue) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HBaseClient(org.hbase.async.HBaseClient) Deferred(com.stumbleupon.async.Deferred) ArrayList(java.util.ArrayList) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 23 with Deferred

use of com.stumbleupon.async.Deferred in project opentsdb by OpenTSDB.

the class TestSearchRpc method setupLookup.

private void setupLookup(final boolean use_meta) {
    storage = new MockBase(tsdb, client, true, true, true, true);
    if (use_meta) {
        TestTimeSeriesLookup.generateMeta(tsdb, storage);
    } else {
        TestTimeSeriesLookup.generateData(tsdb, storage);
    }
    when(metrics.getNameAsync(new byte[] { 0, 0, 4 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("filtered");
        }
    });
    when(tag_names.getNameAsync(new byte[] { 0, 0, 6 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("6");
        }
    });
    when(tag_names.getNameAsync(new byte[] { 0, 0, 8 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("8");
        }
    });
    when(tag_names.getNameAsync(new byte[] { 0, 0, 9 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("9");
        }
    });
    when(tag_values.getNameAsync(new byte[] { 0, 0, 7 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("7");
        }
    });
    when(tag_values.getNameAsync(new byte[] { 0, 0, 5 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("5");
        }
    });
    when(tag_values.getNameAsync(new byte[] { 0, 0, 10 })).thenAnswer(new Answer<Deferred<String>>() {

        @Override
        public Deferred<String> answer(InvocationOnMock invocation) throws Throwable {
            return Deferred.fromResult("10");
        }
    });
}
Also used : InvocationOnMock(org.mockito.invocation.InvocationOnMock) Deferred(com.stumbleupon.async.Deferred) MockBase(net.opentsdb.storage.MockBase)

Example 24 with Deferred

use of com.stumbleupon.async.Deferred 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 25 with Deferred

use of com.stumbleupon.async.Deferred in project opentsdb by OpenTSDB.

the class EDPtoDPS method getAggregatedTagsAsync.

@Override
public Deferred<List<String>> getAggregatedTagsAsync() {
    final ByteSet tagks = edps[index].aggregatedTags();
    final List<String> aggregated_tags = new ArrayList<String>(tagks.size());
    final List<Deferred<String>> names = new ArrayList<Deferred<String>>(tagks.size());
    for (final byte[] tagk : tagks) {
        names.add(tsdb.getUidName(UniqueIdType.TAGK, tagk));
    }
    /** Adds the names to the aggregated_tags list */
    final class ResolveCB implements Callback<List<String>, ArrayList<String>> {

        @Override
        public List<String> call(final ArrayList<String> names) throws Exception {
            for (final String name : names) {
                aggregated_tags.add(name);
            }
            return aggregated_tags;
        }
    }
    return Deferred.group(names).addCallback(new ResolveCB());
}
Also used : Callback(com.stumbleupon.async.Callback) Deferred(com.stumbleupon.async.Deferred) ArrayList(java.util.ArrayList) ByteSet(net.opentsdb.utils.ByteSet)

Aggregations

Deferred (com.stumbleupon.async.Deferred)40 ArrayList (java.util.ArrayList)33 Callback (com.stumbleupon.async.Callback)29 IOException (java.io.IOException)14 KeyValue (org.hbase.async.KeyValue)14 HashMap (java.util.HashMap)12 Map (java.util.Map)11 Scanner (org.hbase.async.Scanner)11 HBaseException (org.hbase.async.HBaseException)9 DeferredGroupException (com.stumbleupon.async.DeferredGroupException)8 List (java.util.List)8 NoSuchUniqueName (net.opentsdb.uid.NoSuchUniqueName)8 DeleteRequest (org.hbase.async.DeleteRequest)6 TSSubQuery (net.opentsdb.core.TSSubQuery)5 Annotation (net.opentsdb.meta.Annotation)5 NoSuchUniqueId (net.opentsdb.uid.NoSuchUniqueId)5 JSONException (net.opentsdb.utils.JSONException)5 InvocationOnMock (org.mockito.invocation.InvocationOnMock)5 DataPoints (net.opentsdb.core.DataPoints)4 IncomingDataPoint (net.opentsdb.core.IncomingDataPoint)4