Search in sources :

Example 1 with InvalidFilterException

use of com.srotya.sidewinder.core.utils.InvalidFilterException in project sidewinder by srotya.

the class GrafanaQueryApiv2 method queryData.

@Path("/query")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
public Response queryData(@PathParam(DatabaseOpsApi.DB_NAME) String dbName, String queryString) throws ParseException {
    grafanaQueryCounter.mark();
    Context time = grafanaQueryLatency.time();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    logger.log(Level.FINE, () -> "Grafana query:" + dbName + "\t" + gson.toJson(gson.fromJson(queryString, JsonObject.class)));
    JsonObject json = gson.fromJson(queryString, JsonObject.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    JsonObject range = json.get("range").getAsJsonObject();
    long startTs = sdf.parse(range.get("from").getAsString()).getTime();
    long endTs = sdf.parse(range.get("to").getAsString()).getTime();
    startTs = tz.getOffset(startTs) + startTs;
    endTs = tz.getOffset(endTs) + endTs;
    List<TargetSeries> targetSeries = new ArrayList<>();
    try {
        GrafanaUtils.extractTargetsFromJson(json, targetSeries);
    } catch (InvalidFilterException e) {
        throw new BadRequestException(e.getMessage());
    }
    List<Iterator<GrafanaOutputv2>> output = new ArrayList<>();
    logger.log(Level.FINE, "Extracted targets from query json, target count:" + targetSeries.size() + " " + new Date(startTs));
    for (TargetSeries targetSeriesEntry : targetSeries) {
        logger.log(Level.FINE, () -> "Running grafana query fetch for:" + targetSeriesEntry);
        try {
            Iterator<GrafanaOutputv2> outputIterator = GrafanaUtils.queryAndGetDatav2(engine, dbName, startTs, endTs, targetSeriesEntry);
            if (outputIterator != null) {
                output.add(outputIterator);
            }
        } catch (IOException e) {
            throw new InternalServerErrorException(e);
        }
    }
    time.stop();
    // Adding sorted output so series colors do not change in grafana
    logger.log(Level.FINER, () -> "Grafana query result size:" + output.size());
    return Response.ok(new GrafanaStreamingOutput(output)).type("application/json").build();
}
Also used : Context(com.codahale.metrics.Timer.Context) InvalidFilterException(com.srotya.sidewinder.core.utils.InvalidFilterException) GrafanaStreamingOutput(com.srotya.sidewinder.core.utils.GrafanaStreamingOutput) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) Date(java.util.Date) Iterator(java.util.Iterator) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 2 with InvalidFilterException

use of com.srotya.sidewinder.core.utils.InvalidFilterException in project sidewinder by srotya.

the class GrafanaUtils method extractTargetsFromJson.

/**
 * Extract target series from Grafana Json query payload
 *
 * @param json
 * @param targetSeries
 * @throws InvalidFilterException
 */
public static void extractTargetsFromJson(JsonObject json, List<TargetSeries> targetSeries) throws InvalidFilterException {
    JsonArray targets = json.get("targets").getAsJsonArray();
    for (int i = 0; i < targets.size(); i++) {
        JsonObject jsonElement = targets.get(i).getAsJsonObject();
        if (jsonElement == null) {
            continue;
        }
        if (jsonElement.has("target") && jsonElement.has("field")) {
            TagFilter filter = extractGrafanaFilter(jsonElement);
            Function aggregationFunction = extractGrafanaAggregation(jsonElement);
            FunctionIteratorFactory functionIterator = extractGrafanaFunction(jsonElement);
            boolean correlate = false;
            if (jsonElement.has("correlate")) {
                correlate = jsonElement.get("correlate").getAsBoolean();
            }
            TargetSeries e = new TargetSeries(jsonElement.get("target").getAsString(), jsonElement.get("field").getAsString(), filter, aggregationFunction, correlate, functionIterator);
            targetSeries.add(e);
            logger.log(Level.FINE, () -> "Parsed and extracted target:" + e);
        } else if (jsonElement.has("raw") && jsonElement.get("rawQuery").getAsBoolean()) {
            // raw query recieved
            TargetSeries e;
            try {
                e = MiscUtils.extractTargetFromQuery(jsonElement.get("raw").getAsString());
            } catch (Exception e1) {
                throw new InvalidFilterException("Bad function expression:" + jsonElement.get("raw").getAsString() + " reason:" + e1.getMessage());
            }
            logger.log(Level.FINE, () -> "Parsed and extracted raw query:" + e);
            if (e != null) {
                targetSeries.add(e);
            }
        }
    }
}
Also used : JsonArray(com.google.gson.JsonArray) Function(com.srotya.sidewinder.core.functions.list.Function) InvalidFilterException(com.srotya.sidewinder.core.utils.InvalidFilterException) TagFilter(com.srotya.sidewinder.core.filters.TagFilter) SimpleTagFilter(com.srotya.sidewinder.core.filters.SimpleTagFilter) ComplexTagFilter(com.srotya.sidewinder.core.filters.ComplexTagFilter) JsonObject(com.google.gson.JsonObject) FunctionIteratorFactory(com.srotya.sidewinder.core.functions.iterative.FunctionIteratorFactory) DataPoint(com.srotya.sidewinder.core.storage.DataPoint) ItemNotFoundException(com.srotya.sidewinder.core.storage.ItemNotFoundException) InvalidFilterException(com.srotya.sidewinder.core.utils.InvalidFilterException) BadRequestException(javax.ws.rs.BadRequestException) IOException(java.io.IOException) NotFoundException(javax.ws.rs.NotFoundException)

Example 3 with InvalidFilterException

use of com.srotya.sidewinder.core.utils.InvalidFilterException in project sidewinder by srotya.

the class TestStorageEngine method testWriteIndexAndQuery.

@Test
public void testWriteIndexAndQuery() throws IOException, InvalidFilterException {
    final long curr = 1497720652566L;
    conf.put("default.bucket.size", "409600");
    conf.put("use.query.pool", "false");
    engine.configure(conf, bgTasks);
    Point dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr).addValueFieldName("user").addValue(20).addFp(false).addValueFieldName("system").addValue(11).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test1.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr).addValueFieldName("user").addValue(24).addFp(false).addValueFieldName("system").addValue(12).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test2.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr).addValueFieldName("user").addValue(21).addFp(false).addValueFieldName("system").addValue(10).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test3.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    TagFilter filter = MiscUtils.buildTagFilter("host=test1.xyz.com");
    List<SeriesOutput> series = engine.queryDataPoints("db1", "cpu", "system", curr - 1, curr + 10, filter);
    assertEquals(1, series.size());
    assertEquals(1, series.get(0).getDataPoints().size());
    assertEquals(curr, series.get(0).getDataPoints().get(0).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(0).getLongValue());
    series = engine.queryDataPoints("db1", "cpu", ".*", curr - 1, curr + 10, filter);
    assertEquals("Error:" + series, 2, series.size());
    assertEquals(1, series.get(0).getDataPoints().size());
    assertEquals(1, series.get(1).getDataPoints().size());
    assertEquals(curr, series.get(0).getDataPoints().get(0).getTimestamp());
    assertEquals(curr, series.get(1).getDataPoints().get(0).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(0).getLongValue());
    assertEquals(20, series.get(1).getDataPoints().get(0).getLongValue());
    dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr + 1000).addValueFieldName("user").addValue(20).addFp(false).addValueFieldName("system").addValue(11).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test1.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr + 1000).addValueFieldName("user").addValue(24).addFp(false).addValueFieldName("system").addValue(12).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test2.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    dp = Point.newBuilder().setDbName("db1").setMeasurementName("cpu").setTimestamp(curr + 1000).addValueFieldName("user").addValue(21).addFp(false).addValueFieldName("system").addValue(10).addFp(false).addTags(Tag.newBuilder().setTagKey("host").setTagValue("test3.xyz.com").build()).build();
    engine.writeDataPointWithLock(dp, true);
    series = engine.queryDataPoints("db1", "cpu", ".*", curr, curr + 10, filter);
    assertEquals(2, series.size());
    assertEquals(1, series.get(0).getDataPoints().size());
    assertEquals(1, series.get(1).getDataPoints().size());
    assertEquals(curr, series.get(0).getDataPoints().get(0).getTimestamp());
    assertEquals(curr, series.get(1).getDataPoints().get(0).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(0).getLongValue());
    assertEquals(20, series.get(1).getDataPoints().get(0).getLongValue());
    series = engine.queryDataPoints("db1", "cpu", ".*", curr, curr + 1001, filter);
    assertEquals(2, series.size());
    assertEquals(2, series.get(0).getDataPoints().size());
    assertEquals(2, series.get(1).getDataPoints().size());
    assertEquals(curr, series.get(0).getDataPoints().get(0).getTimestamp());
    assertEquals(curr, series.get(1).getDataPoints().get(0).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(0).getLongValue());
    assertEquals(20, series.get(1).getDataPoints().get(0).getLongValue());
    assertEquals(curr + 1000, series.get(0).getDataPoints().get(1).getTimestamp());
    assertEquals(curr + 1000, series.get(1).getDataPoints().get(1).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(1).getLongValue());
    assertEquals(20, series.get(1).getDataPoints().get(1).getLongValue());
    filter = MiscUtils.buildTagFilter("host=test1.xyz.com|host=test2.xyz.com");
    series = engine.queryDataPoints("db1", "cpu", "system", curr - 1, curr + 10, filter);
    assertEquals(2, series.size());
    assertEquals(1, series.get(0).getDataPoints().size());
    assertEquals(1, series.get(1).getDataPoints().size());
    assertEquals(curr, series.get(0).getDataPoints().get(0).getTimestamp());
    assertEquals(11, series.get(0).getDataPoints().get(0).getLongValue());
    assertEquals(curr, series.get(1).getDataPoints().get(0).getTimestamp());
    assertEquals(12, series.get(1).getDataPoints().get(0).getLongValue());
    // test bad queries
    // tag filter contains a space therefore it
    filter = MiscUtils.buildTagFilter("host=test1.xyz.com host=test2.xyz.com");
    series = engine.queryDataPoints("db1", "cpu", "system", curr - 1, curr + 10, filter);
    assertEquals(0, series.size());
    try {
        filter = MiscUtils.buildTagFilter("host332&=test1");
        series = engine.queryDataPoints("db1", "cpu", "system", curr - 1, curr + 10, filter);
        fail("Bad tag filter can't succeed the query");
    } catch (Exception e) {
    }
    filter = MiscUtils.buildTagFilter("host~.*.xyz.com");
    series = engine.queryDataPoints("db1", "cpu", "system", curr - 1, curr + 10, filter);
    assertEquals(3, series.size());
}
Also used : SimpleTagFilter(com.srotya.sidewinder.core.filters.SimpleTagFilter) ComplexTagFilter(com.srotya.sidewinder.core.filters.ComplexTagFilter) TagFilter(com.srotya.sidewinder.core.filters.TagFilter) Point(com.srotya.sidewinder.core.rpc.Point) InvalidFilterException(com.srotya.sidewinder.core.utils.InvalidFilterException) IOException(java.io.IOException) Test(org.junit.Test)

Example 4 with InvalidFilterException

use of com.srotya.sidewinder.core.utils.InvalidFilterException in project sidewinder by srotya.

the class GrafanaQueryApiv1 method queryData.

@Path("/query")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public List<GrafanaOutput> queryData(@PathParam(DatabaseOpsApi.DB_NAME) String dbName, String queryString) throws ParseException {
    grafanaQueryCounter.mark();
    Context time = grafanaQueryLatency.time();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    logger.log(Level.FINE, () -> "Grafana query:" + dbName + "\t" + gson.toJson(gson.fromJson(queryString, JsonObject.class)));
    JsonObject json = gson.fromJson(queryString, JsonObject.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    JsonObject range = json.get("range").getAsJsonObject();
    long startTs = sdf.parse(range.get("from").getAsString()).getTime();
    long endTs = sdf.parse(range.get("to").getAsString()).getTime();
    startTs = tz.getOffset(startTs) + startTs;
    endTs = tz.getOffset(endTs) + endTs;
    List<TargetSeries> targetSeries = new ArrayList<>();
    try {
        GrafanaUtils.extractTargetsFromJson(json, targetSeries);
    } catch (InvalidFilterException e) {
        throw new BadRequestException(e.getMessage());
    }
    List<GrafanaOutput> output = new ArrayList<>();
    logger.log(Level.FINE, "Extracted targets from query json, target count:" + targetSeries.size() + " " + new Date(startTs));
    for (TargetSeries targetSeriesEntry : targetSeries) {
        logger.log(Level.FINE, () -> "Running grafana query fetch for:" + targetSeriesEntry);
        try {
            GrafanaUtils.queryAndGetData(engine, dbName, startTs, endTs, output, targetSeriesEntry);
        } catch (IOException e) {
            throw new InternalServerErrorException(e);
        }
    }
    time.stop();
    // Adding sorted output so series colors do not change in grafana
    Collections.sort(output);
    logger.log(Level.FINEST, () -> {
        StringBuilder builder = new StringBuilder();
        for (GrafanaOutput out : output) {
            builder.append(out.getTarget() + " " + out.getDatapoints().size() + "\n");
        }
        return builder.toString();
    });
    logger.log(Level.FINER, () -> "Grafana query result size:" + output.size());
    return output;
}
Also used : Context(com.codahale.metrics.Timer.Context) InvalidFilterException(com.srotya.sidewinder.core.utils.InvalidFilterException) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) Date(java.util.Date) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

InvalidFilterException (com.srotya.sidewinder.core.utils.InvalidFilterException)4 IOException (java.io.IOException)4 JsonObject (com.google.gson.JsonObject)3 BadRequestException (javax.ws.rs.BadRequestException)3 Context (com.codahale.metrics.Timer.Context)2 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 ComplexTagFilter (com.srotya.sidewinder.core.filters.ComplexTagFilter)2 SimpleTagFilter (com.srotya.sidewinder.core.filters.SimpleTagFilter)2 TagFilter (com.srotya.sidewinder.core.filters.TagFilter)2 SimpleDateFormat (java.text.SimpleDateFormat)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 Consumes (javax.ws.rs.Consumes)2 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 JsonArray (com.google.gson.JsonArray)1 FunctionIteratorFactory (com.srotya.sidewinder.core.functions.iterative.FunctionIteratorFactory)1 Function (com.srotya.sidewinder.core.functions.list.Function)1