Search in sources :

Example 1 with FunctionType

use of org.hypertrace.gateway.service.v1.common.FunctionType in project gateway-service by hypertrace.

the class QueryServiceEntityFetcher method getTimeAggregatedMetrics.

@Override
public EntityFetcherResponse getTimeAggregatedMetrics(EntitiesRequestContext requestContext, EntitiesRequest entitiesRequest) {
    // No need to make execute the rest of this if there are no TimeAggregations in the request.
    if (entitiesRequest.getTimeAggregationCount() == 0) {
        return new EntityFetcherResponse();
    }
    // Only supported filter is entityIds IN ["id1", "id2", "id3"]
    List<String> idColumns = AttributeMetadataUtil.getIdAttributeIds(attributeMetadataProvider, entityIdColumnsConfigs, requestContext, entitiesRequest.getEntityType());
    String timeColumn = AttributeMetadataUtil.getTimestampAttributeId(attributeMetadataProvider, requestContext, entitiesRequest.getEntityType());
    Map<String, AttributeMetadata> attributeMetadataMap = attributeMetadataProvider.getAttributesMetadata(requestContext, entitiesRequest.getEntityType());
    Map<String, AttributeMetadata> resultKeyToAttributeMetadataMap = this.remapAttributeMetadataByResultName(entitiesRequest, attributeMetadataMap);
    entitiesRequestValidator.validate(entitiesRequest, attributeMetadataMap);
    entitiesRequest.getTimeAggregationList().forEach(timeAggregation -> requestContext.mapAliasToTimeAggregation(timeAggregation.getAggregation().getFunction().getAlias(), timeAggregation));
    // First group the Aggregations based on the period so that we can issue separate queries
    // to QueryService for each different Period.
    Collection<List<TimeAggregation>> result = entitiesRequest.getTimeAggregationList().stream().collect(Collectors.groupingBy(TimeAggregation::getPeriod)).values();
    Map<EntityKey, Map<String, MetricSeries.Builder>> entityMetricSeriesMap = new LinkedHashMap<>();
    for (List<TimeAggregation> batch : result) {
        Period period = batch.get(0).getPeriod();
        ChronoUnit unit = ChronoUnit.valueOf(period.getUnit());
        long periodSecs = Duration.of(period.getValue(), unit).getSeconds();
        QueryRequest request = buildTimeSeriesQueryRequest(entitiesRequest, requestContext, periodSecs, batch, idColumns, timeColumn);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending time series queryRequest to query service: ======== \n {}", request.toString());
        }
        Iterator<ResultSetChunk> resultSetChunkIterator = queryServiceClient.executeQuery(request, requestContext.getHeaders(), requestTimeout);
        while (resultSetChunkIterator.hasNext()) {
            ResultSetChunk chunk = resultSetChunkIterator.next();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Received chunk: " + chunk.toString());
            }
            if (chunk.getRowCount() < 1) {
                break;
            }
            if (!chunk.hasResultSetMetadata()) {
                LOG.warn("Chunk doesn't have result metadata so couldn't process the response.");
                break;
            }
            for (Row row : chunk.getRowList()) {
                // Construct the entity id from the entityIdAttributeIds columns
                EntityKey entityKey = EntityKey.of(IntStream.range(0, idColumns.size()).mapToObj(value -> row.getColumn(value).getString()).toArray(String[]::new));
                Map<String, MetricSeries.Builder> metricSeriesMap = entityMetricSeriesMap.computeIfAbsent(entityKey, k -> new LinkedHashMap<>());
                Interval.Builder intervalBuilder = Interval.newBuilder();
                // Second column is the time column
                Value value = QueryAndGatewayDtoConverter.convertQueryValueToGatewayValue(row.getColumn(idColumns.size()));
                if (value.getValueType() == ValueType.STRING) {
                    long startTime = Long.parseLong(value.getString());
                    long endTime = startTime + TimeUnit.SECONDS.toMillis(periodSecs);
                    intervalBuilder.setStartTimeMillis(startTime);
                    intervalBuilder.setEndTimeMillis(endTime);
                    for (int i = idColumns.size() + 1; i < chunk.getResultSetMetadata().getColumnMetadataCount(); i++) {
                        ColumnMetadata metadata = chunk.getResultSetMetadata().getColumnMetadata(i);
                        TimeAggregation timeAggregation = requestContext.getTimeAggregationByAlias(metadata.getColumnName());
                        if (timeAggregation == null) {
                            LOG.warn("Couldn't find an aggregate for column: {}", metadata.getColumnName());
                            continue;
                        }
                        FunctionType functionType = timeAggregation.getAggregation().getFunction().getFunction();
                        AttributeMetadata functionAttributeMetadata = resultKeyToAttributeMetadataMap.get(metadata.getColumnName());
                        Value convertedValue = QueryAndGatewayDtoConverter.convertToGatewayValueForMetricValue(MetricAggregationFunctionUtil.getValueTypeForFunctionType(functionType, functionAttributeMetadata), resultKeyToAttributeMetadataMap, metadata, row.getColumn(i));
                        List<org.hypertrace.gateway.service.v1.common.Expression> healthExpressions = timeAggregation.getAggregation().getFunction().getArgumentsList().stream().filter(org.hypertrace.gateway.service.v1.common.Expression::hasHealth).collect(Collectors.toList());
                        Preconditions.checkArgument(healthExpressions.size() <= 1);
                        Health health = Health.NOT_COMPUTED;
                        MetricSeries.Builder seriesBuilder = metricSeriesMap.computeIfAbsent(metadata.getColumnName(), k -> getMetricSeriesBuilder(timeAggregation));
                        seriesBuilder.addValue(Interval.newBuilder(intervalBuilder.build()).setValue(convertedValue).setHealth(health));
                    }
                } else {
                    LOG.warn("Was expecting STRING values only but received valueType: {}", value.getValueType());
                }
            }
        }
    }
    Map<EntityKey, Entity.Builder> resultMap = new LinkedHashMap<>();
    for (Map.Entry<EntityKey, Map<String, MetricSeries.Builder>> entry : entityMetricSeriesMap.entrySet()) {
        Entity.Builder entityBuilder = Entity.newBuilder().setEntityType(entitiesRequest.getEntityType()).setId(entry.getKey().toString()).putAllMetricSeries(entry.getValue().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> getSortedMetricSeries(e.getValue()))));
        for (int i = 0; i < idColumns.size(); i++) {
            entityBuilder.putAttribute(idColumns.get(i), Value.newBuilder().setString(entry.getKey().getAttributes().get(i)).setValueType(ValueType.STRING).build());
        }
        resultMap.put(entry.getKey(), entityBuilder);
    }
    return new EntityFetcherResponse(resultMap);
}
Also used : Entity(org.hypertrace.gateway.service.v1.entity.Entity) ColumnMetadata(org.hypertrace.core.query.service.api.ColumnMetadata) Builder(org.hypertrace.gateway.service.v1.entity.Entity.Builder) LinkedHashMap(java.util.LinkedHashMap) EntityKey(org.hypertrace.gateway.service.entity.EntityKey) MetricSeries(org.hypertrace.gateway.service.v1.common.MetricSeries) List(java.util.List) TimeAggregation(org.hypertrace.gateway.service.v1.common.TimeAggregation) Builder(org.hypertrace.gateway.service.v1.entity.Entity.Builder) QueryRequest(org.hypertrace.core.query.service.api.QueryRequest) Health(org.hypertrace.gateway.service.v1.common.Health) FunctionType(org.hypertrace.gateway.service.v1.common.FunctionType) Period(org.hypertrace.gateway.service.v1.common.Period) QueryRequestUtil.createTimeColumnGroupByExpression(org.hypertrace.gateway.service.common.converters.QueryRequestUtil.createTimeColumnGroupByExpression) QueryAndGatewayDtoConverter.convertToQueryExpression(org.hypertrace.gateway.service.common.converters.QueryAndGatewayDtoConverter.convertToQueryExpression) QueryRequestUtil.createStringNullLiteralExpression(org.hypertrace.gateway.service.common.converters.QueryRequestUtil.createStringNullLiteralExpression) Expression(org.hypertrace.core.query.service.api.Expression) FunctionExpression(org.hypertrace.gateway.service.v1.common.FunctionExpression) AttributeMetadata(org.hypertrace.core.attribute.service.v1.AttributeMetadata) Value(org.hypertrace.gateway.service.v1.common.Value) AggregatedMetricValue(org.hypertrace.gateway.service.v1.common.AggregatedMetricValue) Row(org.hypertrace.core.query.service.api.Row) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ChronoUnit(java.time.temporal.ChronoUnit) ResultSetChunk(org.hypertrace.core.query.service.api.ResultSetChunk) Interval(org.hypertrace.gateway.service.v1.common.Interval)

Example 2 with FunctionType

use of org.hypertrace.gateway.service.v1.common.FunctionType in project gateway-service by hypertrace.

the class MetricAggregationFunctionUtilTest method createFunctionAndVerifyKind.

private void createFunctionAndVerifyKind(String metricName, FunctionType functionType, String alias, AttributeKind expectedKind) {
    Expression expr = QueryExpressionUtil.getAggregateFunctionExpression(metricName, functionType, alias, true).build();
    Map<String, AttributeKind> aliasToKind = MetricAggregationFunctionUtil.getValueTypeForFunctionType(Collections.singletonMap(alias, expr.getFunction()), attributeMetadataMap);
    Assertions.assertEquals(expectedKind, aliasToKind.get(alias));
}
Also used : Expression(org.hypertrace.gateway.service.v1.common.Expression) AttributeKind(org.hypertrace.core.attribute.service.v1.AttributeKind)

Example 3 with FunctionType

use of org.hypertrace.gateway.service.v1.common.FunctionType in project gateway-service by hypertrace.

the class BaselineServiceImplTest method getFunctionExpressionForAvgRate.

private static Stream<Arguments> getFunctionExpressionForAvgRate() {
    FunctionType type = FunctionType.AVGRATE;
    String columnName = "SERVICE.numCalls";
    String alias = "numCalls";
    // for iso support
    FunctionExpression functionExpression1 = FunctionExpression.newBuilder().setFunction(type).setAlias(alias).addArguments(Expression.newBuilder().setColumnIdentifier(ColumnIdentifier.newBuilder().setColumnName(columnName).setAlias(alias))).addArguments(Expression.newBuilder().setLiteral(LiteralConstant.newBuilder().setValue(Value.newBuilder().setString("PT1M").setValueType(ValueType.STRING)))).build();
    // for long support
    FunctionExpression functionExpression2 = FunctionExpression.newBuilder().setFunction(type).setAlias(alias).addArguments(Expression.newBuilder().setColumnIdentifier(ColumnIdentifier.newBuilder().setColumnName(columnName).setAlias(alias))).addArguments(Expression.newBuilder().setLiteral(LiteralConstant.newBuilder().setValue(Value.newBuilder().setLong(60).setValueType(ValueType.LONG)))).build();
    return Stream.of(Arguments.arguments(functionExpression1), Arguments.arguments(functionExpression2));
}
Also used : FunctionExpression(org.hypertrace.gateway.service.v1.common.FunctionExpression) FunctionType(org.hypertrace.gateway.service.v1.common.FunctionType)

Example 4 with FunctionType

use of org.hypertrace.gateway.service.v1.common.FunctionType in project gateway-service by hypertrace.

the class AggregationValidator method validate.

public void validate(Expression expression) {
    checkArgument(expression.hasFunction(), "Expression is not a FunctionExpression. Are you sure you are passing the correct Expression?");
    FunctionExpression functionExpression = expression.getFunction();
    checkArgument(functionExpression.getFunction() != FunctionType.NONE, "FunctionType should be specified");
    validateFunctionExpression(functionExpression);
}
Also used : FunctionExpression(org.hypertrace.gateway.service.v1.common.FunctionExpression)

Aggregations

FunctionExpression (org.hypertrace.gateway.service.v1.common.FunctionExpression)3 FunctionType (org.hypertrace.gateway.service.v1.common.FunctionType)2 ChronoUnit (java.time.temporal.ChronoUnit)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 AttributeKind (org.hypertrace.core.attribute.service.v1.AttributeKind)1 AttributeMetadata (org.hypertrace.core.attribute.service.v1.AttributeMetadata)1 ColumnMetadata (org.hypertrace.core.query.service.api.ColumnMetadata)1 Expression (org.hypertrace.core.query.service.api.Expression)1 QueryRequest (org.hypertrace.core.query.service.api.QueryRequest)1 ResultSetChunk (org.hypertrace.core.query.service.api.ResultSetChunk)1 Row (org.hypertrace.core.query.service.api.Row)1 QueryAndGatewayDtoConverter.convertToQueryExpression (org.hypertrace.gateway.service.common.converters.QueryAndGatewayDtoConverter.convertToQueryExpression)1 QueryRequestUtil.createStringNullLiteralExpression (org.hypertrace.gateway.service.common.converters.QueryRequestUtil.createStringNullLiteralExpression)1 QueryRequestUtil.createTimeColumnGroupByExpression (org.hypertrace.gateway.service.common.converters.QueryRequestUtil.createTimeColumnGroupByExpression)1 EntityKey (org.hypertrace.gateway.service.entity.EntityKey)1 AggregatedMetricValue (org.hypertrace.gateway.service.v1.common.AggregatedMetricValue)1 Expression (org.hypertrace.gateway.service.v1.common.Expression)1 Health (org.hypertrace.gateway.service.v1.common.Health)1