@grafana/data#TimeSeries TypeScript Examples

The following examples show how to use @grafana/data#TimeSeries. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: response_parser.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
parseTimeSeriesResult(query: { refId: string; query: any }, columns: any[], rows: any): TimeSeries[] {
    const data: TimeSeries[] = [];
    let timeIndex = -1;
    let metricIndex = -1;
    let valueIndex = -1;

    for (let i = 0; i < columns.length; i++) {
      if (timeIndex === -1 && columns[i].type === 'datetime') {
        timeIndex = i;
      }

      if (metricIndex === -1 && columns[i].type === 'string') {
        metricIndex = i;
      }

      if (valueIndex === -1 && ['int', 'long', 'real', 'double'].indexOf(columns[i].type) > -1) {
        valueIndex = i;
      }
    }

    if (timeIndex === -1) {
      throw new Error('No datetime column found in the result. The Time Series format requires a time column.');
    }

    _.forEach(rows, row => {
      const epoch = ResponseParser.dateTimeToEpoch(row[timeIndex]);
      const metricName = metricIndex > -1 ? row[metricIndex] : columns[valueIndex].name;
      const bucket = ResponseParser.findOrCreateBucket(data, metricName);
      bucket.datapoints.push([row[valueIndex], epoch]);
      bucket.refId = query.refId;
      bucket.meta = {
        query: query.query,
      };
    });

    return data;
  }
Example #2
Source File: response_parser.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
static findOrCreateBucket(data: TimeSeries[], target: any): TimeSeries {
    let dataTarget: any = _.find(data, ['target', target]);
    if (!dataTarget) {
      dataTarget = { target: target, datapoints: [], refId: '', query: '' };
      data.push(dataTarget);
    }

    return dataTarget;
  }
Example #3
Source File: result_transformer.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
export function rangeQueryResponseToTimeSeries(
  response: LokiResponse,
  query: LokiRangeQueryRequest,
  target: LokiQuery,
  responseListLength: number
): TimeSeries[] {
  const transformerOptions: TransformerOptions = {
    format: target.format,
    legendFormat: target.legendFormat,
    start: query.start,
    end: query.end,
    step: query.step,
    query: query.query,
    responseListLength,
    refId: target.refId,
    valueWithRefId: target.valueWithRefId,
  };

  switch (response.data.resultType) {
    case LokiResultType.Vector:
      return response.data.result.map(vecResult =>
        lokiMatrixToTimeSeries({ metric: vecResult.metric, values: [vecResult.value] }, transformerOptions)
      );
    case LokiResultType.Matrix:
      return response.data.result.map(matrixResult => lokiMatrixToTimeSeries(matrixResult, transformerOptions));
    default:
      return [];
  }
}
Example #4
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
private panelsQuery(queries: PromQueryRequest[], activeTargets: PromQuery[], end: number, requestId: string) {
    const observables: Array<Observable<Array<TableModel | TimeSeries>>> = queries.map((query, index) => {
      const target = activeTargets[index];
      let observable: Observable<any> = null;

      if (query.instant) {
        observable = from(this.performInstantQuery(query, end));
      } else {
        observable = from(this.performTimeSeriesQuery(query, query.start, query.end));
      }

      return observable.pipe(
        filter((response: any) => (response.cancelled ? false : true)),
        map((response: any) => {
          const data = this.processResult(response, query, target, queries.length);
          return data;
        })
      );
    });

    return forkJoin(observables).pipe(
      map((results: Array<Array<TableModel | TimeSeries>>) => {
        const data = results.reduce((result, current) => {
          return [...result, ...current];
        }, []);
        return {
          data,
          key: requestId,
          state: LoadingState.Done,
        };
      })
    );
  }
Example #5
Source File: result_transformer.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
transform(response: any, options: any): Array<TableModel | TimeSeries> {
    const prometheusResult = response.data.data.result;

    if (options.format === 'table') {
      return [
        this.transformMetricDataToTable(
          prometheusResult,
          options.responseListLength,
          options.refId,
          options.valueWithRefId
        ),
      ];
    } else if (prometheusResult && options.format === 'heatmap') {
      let seriesList = [];
      for (const metricData of prometheusResult) {
        seriesList.push(this.transformMetricData(metricData, options, options.start, options.end));
      }
      seriesList.sort(sortSeriesByLabel);
      seriesList = this.transformToHistogramOverTime(seriesList);
      return seriesList;
    } else if (prometheusResult) {
      const seriesList = [];
      for (const metricData of prometheusResult) {
        if (response.data.data.resultType === 'matrix') {
          seriesList.push(this.transformMetricData(metricData, options, options.start, options.end));
        } else if (response.data.data.resultType === 'vector') {
          seriesList.push(this.transformInstantMetricData(metricData, options));
        }
      }
      return seriesList;
    }
    return [];
  }
Example #6
Source File: result_transformer.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
transformToHistogramOverTime(seriesList: TimeSeries[]) {
    /*      t1 = timestamp1, t2 = timestamp2 etc.
            t1  t2  t3          t1  t2  t3
    le10    10  10  0     =>    10  10  0
    le20    20  10  30    =>    10  0   30
    le30    30  10  35    =>    10  0   5
    */
    for (let i = seriesList.length - 1; i > 0; i--) {
      const topSeries = seriesList[i].datapoints;
      const bottomSeries = seriesList[i - 1].datapoints;
      if (!topSeries || !bottomSeries) {
        throw new Error('Prometheus heatmap transform error: data should be a time series');
      }

      for (let j = 0; j < topSeries.length; j++) {
        const bottomPoint = bottomSeries[j] || [0];
        topSeries[j][0] -= bottomPoint[0];
      }
    }

    return seriesList;
  }
Example #7
Source File: result_transformer.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
function sortSeriesByLabel(s1: TimeSeries, s2: TimeSeries): number {
  let le1, le2;

  try {
    // fail if not integer. might happen with bad queries
    le1 = parseHistogramLabel(s1.target);
    le2 = parseHistogramLabel(s2.target);
  } catch (err) {
    console.log(err);
    return 0;
  }

  if (le1 > le2) {
    return 1;
  }

  if (le1 < le2) {
    return -1;
  }

  return 0;
}
Example #8
Source File: QueryEditor.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
onDataReceived(dataList: TimeSeries[]) {
    const series = dataList.find((item: any) => item.refId === this.props.target.refId);
    if (series) {
      this.setState({
        lastQuery: decodeURIComponent(series.meta.rawQuery),
        lastQueryError: '',
        usedAlignmentPeriod: series.meta.alignmentPeriod,
      });
    }
  }
Example #9
Source File: ResultProcessor.test.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
testContext = (options: any = {}) => {
  const timeSeries = toDataFrame({
    name: 'A-series',
    refId: 'A',
    fields: [
      { name: 'A-series', type: FieldType.number, values: [4, 5, 6] },
      { name: 'time', type: FieldType.time, values: [100, 200, 300] },
    ],
  });

  const table = toDataFrame({
    name: 'table-res',
    refId: 'A',
    fields: [
      { name: 'value', type: FieldType.number, values: [4, 5, 6] },
      { name: 'time', type: FieldType.time, values: [100, 200, 300] },
      { name: 'message', type: FieldType.string, values: ['this is a message', 'second message', 'third'] },
    ],
  });

  const emptyTable = toDataFrame({ name: 'empty-table', refId: 'A', fields: [] });

  const defaultOptions = {
    mode: ExploreMode.Metrics,
    dataFrames: [timeSeries, table, emptyTable],
    graphResult: [] as TimeSeries[],
    tableResult: new TableModel(),
    logsResult: { hasUniqueLabels: false, rows: [] as LogRowModel[] },
  };

  const combinedOptions = { ...defaultOptions, ...options };

  const state = ({
    mode: combinedOptions.mode,
    graphResult: combinedOptions.graphResult,
    tableResult: combinedOptions.tableResult,
    logsResult: combinedOptions.logsResult,
    queryIntervals: { intervalMs: 10 },
  } as any) as ExploreItemState;

  const resultProcessor = new ResultProcessor(state, combinedOptions.dataFrames, 60000, 'utc');

  return {
    dataFrames: combinedOptions.dataFrames,
    resultProcessor,
  };
}
Example #10
Source File: app_insights_datasource.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
async query(options: DataQueryRequest<AzureMonitorQuery>): Promise<DataQueryResponseData[]> {
    const queries = _.filter(options.targets, item => {
      return item.hide !== true;
    }).map((target: AzureMonitorQuery) => {
      const item = target.appInsights;
      let query: any;
      if (item.rawQuery) {
        query = this.createRawQueryRequest(item, options, target);
      } else {
        query = this.createMetricsRequest(item, options, target);
      }
      query.refId = target.refId;
      query.intervalMs = options.intervalMs;
      query.datasourceId = this.id;
      query.queryType = 'Application Insights';
      return query;
    });

    if (!queries || queries.length === 0) {
      // @ts-ignore
      return;
    }

    const { data } = await getBackendSrv().datasourceRequest({
      url: '/api/tsdb/query',
      method: 'POST',
      data: {
        from: options.range.from.valueOf().toString(),
        to: options.range.to.valueOf().toString(),
        queries,
      },
    });

    const result: DataQueryResponseData[] = [];
    if (data.results) {
      Object.values(data.results).forEach((queryRes: any) => {
        if (queryRes.meta && queryRes.meta.columns) {
          const columnNames = queryRes.meta.columns as string[];
          this.logAnalyticsColumns[queryRes.refId] = _.map(columnNames, n => ({ text: n, value: n }));
        }

        if (!queryRes.series) {
          return;
        }

        queryRes.series.forEach((series: any) => {
          const timeSerie: TimeSeries = {
            target: series.name,
            datapoints: series.points,
            refId: queryRes.refId,
            meta: queryRes.meta,
          };
          result.push(toDataFrame(timeSerie));
        });
      });
      return result;
    }

    return Promise.resolve([]);
  }
Example #11
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
function isTimeSeries(data: any): data is TimeSeries {
  return data.hasOwnProperty('datapoints');
}
Example #12
Source File: result_transformer.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
function lokiMatrixToTimeSeries(matrixResult: LokiMatrixResult, options: TransformerOptions): TimeSeries {
  return {
    target: createMetricLabel(matrixResult.metric, options),
    datapoints: lokiPointsToTimeseriesPoints(matrixResult.values, options),
    tags: matrixResult.metric,
  };
}
Example #13
Source File: azure_monitor_datasource.ts    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
async query(options: DataQueryRequest<AzureMonitorQuery>): Promise<DataQueryResponseData[]> {
    const queries = _.filter(options.targets, item => {
      return (
        item.hide !== true &&
        item.azureMonitor.resourceGroup &&
        item.azureMonitor.resourceGroup !== this.defaultDropdownValue &&
        item.azureMonitor.resourceName &&
        item.azureMonitor.resourceName !== this.defaultDropdownValue &&
        item.azureMonitor.metricDefinition &&
        item.azureMonitor.metricDefinition !== this.defaultDropdownValue &&
        item.azureMonitor.metricName &&
        item.azureMonitor.metricName !== this.defaultDropdownValue
      );
    }).map(target => {
      const item = target.azureMonitor;

      // fix for timeGrainUnit which is a deprecated/removed field name
      if (item.timeGrainUnit && item.timeGrain !== 'auto') {
        item.timeGrain = TimegrainConverter.createISO8601Duration(item.timeGrain, item.timeGrainUnit);
      }

      const subscriptionId = this.templateSrv.replace(target.subscription || this.subscriptionId, options.scopedVars);
      const resourceGroup = this.templateSrv.replace(item.resourceGroup, options.scopedVars);
      const resourceName = this.templateSrv.replace(item.resourceName, options.scopedVars);
      const metricNamespace = this.templateSrv.replace(item.metricNamespace, options.scopedVars);
      const metricDefinition = this.templateSrv.replace(item.metricDefinition, options.scopedVars);
      const timeGrain = this.templateSrv.replace((item.timeGrain || '').toString(), options.scopedVars);
      const aggregation = this.templateSrv.replace(item.aggregation, options.scopedVars);
      const top = this.templateSrv.replace(item.top || '', options.scopedVars);

      return {
        refId: target.refId,
        intervalMs: options.intervalMs,
        datasourceId: this.id,
        subscription: subscriptionId,
        queryType: 'Azure Monitor',
        type: 'timeSeriesQuery',
        raw: false,
        azureMonitor: {
          resourceGroup: resourceGroup,
          resourceName: resourceName,
          metricDefinition: metricDefinition,
          timeGrain: timeGrain,
          allowedTimeGrainsMs: item.allowedTimeGrainsMs,
          metricName: this.templateSrv.replace(item.metricName, options.scopedVars),
          metricNamespace:
            metricNamespace && metricNamespace !== this.defaultDropdownValue ? metricNamespace : metricDefinition,
          aggregation: aggregation,
          dimension: this.templateSrv.replace(item.dimension, options.scopedVars),
          top: top || '10',
          dimensionFilter: this.templateSrv.replace(item.dimensionFilter, options.scopedVars),
          alias: item.alias,
          format: target.format,
        },
      };
    });

    if (!queries || queries.length === 0) {
      return Promise.resolve([]);
    }

    const { data } = await getBackendSrv().datasourceRequest({
      url: '/api/tsdb/query',
      method: 'POST',
      data: {
        from: options.range.from.valueOf().toString(),
        to: options.range.to.valueOf().toString(),
        queries,
      },
    });

    const result: DataQueryResponseData[] = [];
    if (data.results) {
      Object['values'](data.results).forEach((queryRes: any) => {
        if (!queryRes.series) {
          return;
        }
        queryRes.series.forEach((series: any) => {
          const timeSerie: TimeSeries = {
            target: series.name,
            datapoints: series.points,
            refId: queryRes.refId,
            meta: queryRes.meta,
          };
          result.push(toDataFrame(timeSerie));
        });
      });
      return result;
    }

    return Promise.resolve([]);
  }