datasource.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. // Libraries
  2. import { cloneDeep, isEmpty, map as lodashMap } from 'lodash';
  3. import Prism from 'prismjs';
  4. import { lastValueFrom, merge, Observable, of, throwError } from 'rxjs';
  5. import { catchError, map, switchMap } from 'rxjs/operators';
  6. // Types
  7. import {
  8. AnnotationEvent,
  9. AnnotationQueryRequest,
  10. CoreApp,
  11. DataFrame,
  12. DataFrameView,
  13. DataQueryError,
  14. DataQueryRequest,
  15. DataQueryResponse,
  16. DataSourceInstanceSettings,
  17. DataSourceWithLogsContextSupport,
  18. DataSourceWithLogsVolumeSupport,
  19. DataSourceWithQueryExportSupport,
  20. DataSourceWithQueryImportSupport,
  21. dateMath,
  22. DateTime,
  23. FieldCache,
  24. AbstractQuery,
  25. FieldType,
  26. getLogLevelFromKey,
  27. Labels,
  28. LoadingState,
  29. LogLevel,
  30. LogRowModel,
  31. QueryResultMeta,
  32. ScopedVars,
  33. TimeRange,
  34. rangeUtil,
  35. toUtc,
  36. } from '@grafana/data';
  37. import { BackendSrvRequest, FetchError, getBackendSrv, config, DataSourceWithBackend } from '@grafana/runtime';
  38. import { RowContextOptions } from '@grafana/ui/src/components/Logs/LogRowContextProvider';
  39. import { queryLogsVolume } from 'app/core/logs_model';
  40. import { convertToWebSocketUrl } from 'app/core/utils/explore';
  41. import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  42. import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
  43. import { serializeParams } from '../../../core/utils/fetch';
  44. import { renderLegendFormat } from '../prometheus/legend';
  45. import { addLabelToQuery } from './add_label_to_query';
  46. import { transformBackendResult } from './backendResultTransformer';
  47. import { DEFAULT_RESOLUTION } from './components/LokiOptionFields';
  48. import LanguageProvider from './language_provider';
  49. import { escapeLabelValueInSelector } from './language_utils';
  50. import { LiveStreams, LokiLiveTarget } from './live_streams';
  51. import { addParsedLabelToQuery, getNormalizedLokiQuery, queryHasPipeParser } from './query_utils';
  52. import { lokiResultsToTableModel, lokiStreamsToDataFrames, processRangeQueryResponse } from './result_transformer';
  53. import { sortDataFrameByTime } from './sortDataFrame';
  54. import { doLokiChannelStream } from './streaming';
  55. import syntax from './syntax';
  56. import {
  57. LokiOptions,
  58. LokiQuery,
  59. LokiQueryDirection,
  60. LokiQueryType,
  61. LokiRangeQueryRequest,
  62. LokiResultType,
  63. LokiStreamResponse,
  64. } from './types';
  65. export type RangeQueryOptions = DataQueryRequest<LokiQuery> | AnnotationQueryRequest<LokiQuery>;
  66. export const DEFAULT_MAX_LINES = 1000;
  67. export const LOKI_ENDPOINT = '/loki/api/v1';
  68. const NS_IN_MS = 1000000;
  69. const RANGE_QUERY_ENDPOINT = `${LOKI_ENDPOINT}/query_range`;
  70. const INSTANT_QUERY_ENDPOINT = `${LOKI_ENDPOINT}/query`;
  71. const DEFAULT_QUERY_PARAMS: Partial<LokiRangeQueryRequest> = {
  72. limit: DEFAULT_MAX_LINES,
  73. query: '',
  74. };
  75. function makeRequest(query: LokiQuery, range: TimeRange, app: CoreApp, requestId: string): DataQueryRequest<LokiQuery> {
  76. const intervalInfo = rangeUtil.calculateInterval(range, 1);
  77. return {
  78. targets: [query],
  79. requestId,
  80. interval: intervalInfo.interval,
  81. intervalMs: intervalInfo.intervalMs,
  82. range: range,
  83. scopedVars: {},
  84. timezone: 'UTC',
  85. app,
  86. startTime: Date.now(),
  87. };
  88. }
  89. export class LokiDatasource
  90. extends DataSourceWithBackend<LokiQuery, LokiOptions>
  91. implements
  92. DataSourceWithLogsContextSupport,
  93. DataSourceWithLogsVolumeSupport<LokiQuery>,
  94. DataSourceWithQueryImportSupport<LokiQuery>,
  95. DataSourceWithQueryExportSupport<LokiQuery>
  96. {
  97. private streams = new LiveStreams();
  98. languageProvider: LanguageProvider;
  99. maxLines: number;
  100. useBackendMode: boolean;
  101. constructor(
  102. private instanceSettings: DataSourceInstanceSettings<LokiOptions>,
  103. private readonly templateSrv: TemplateSrv = getTemplateSrv(),
  104. private readonly timeSrv: TimeSrv = getTimeSrv()
  105. ) {
  106. super(instanceSettings);
  107. this.languageProvider = new LanguageProvider(this);
  108. const settingsData = instanceSettings.jsonData || {};
  109. this.maxLines = parseInt(settingsData.maxLines ?? '0', 10) || DEFAULT_MAX_LINES;
  110. const keepCookiesUsed = (settingsData.keepCookies ?? []).length > 0;
  111. // only use backend-mode when keep-cookies is not used
  112. this.useBackendMode = !keepCookiesUsed && (config.featureToggles.lokiBackendMode ?? false);
  113. }
  114. _request(apiUrl: string, data?: any, options?: Partial<BackendSrvRequest>): Observable<Record<string, any>> {
  115. const baseUrl = this.instanceSettings.url;
  116. const params = data ? serializeParams(data) : '';
  117. const url = `${baseUrl}${apiUrl}${params.length ? `?${params}` : ''}`;
  118. if (this.instanceSettings.withCredentials || this.instanceSettings.basicAuth) {
  119. options = { ...options, withCredentials: true };
  120. if (this.instanceSettings.basicAuth) {
  121. options.headers = { ...options.headers, Authorization: this.instanceSettings.basicAuth };
  122. }
  123. }
  124. const req = {
  125. ...options,
  126. url,
  127. };
  128. return getBackendSrv().fetch<Record<string, any>>(req);
  129. }
  130. getLogsVolumeDataProvider(request: DataQueryRequest<LokiQuery>): Observable<DataQueryResponse> | undefined {
  131. const isQuerySuitable = (query: LokiQuery) => {
  132. const normalized = getNormalizedLokiQuery(query);
  133. const { expr } = normalized;
  134. // it has to be a logs-producing range-query
  135. return expr && !isMetricsQuery(expr) && normalized.queryType === LokiQueryType.Range;
  136. };
  137. const isLogsVolumeAvailable = request.targets.some(isQuerySuitable);
  138. if (!isLogsVolumeAvailable) {
  139. return undefined;
  140. }
  141. const logsVolumeRequest = cloneDeep(request);
  142. logsVolumeRequest.targets = logsVolumeRequest.targets.filter(isQuerySuitable).map((target) => {
  143. return {
  144. ...target,
  145. instant: false,
  146. volumeQuery: true,
  147. expr: `sum by (level) (count_over_time(${target.expr}[$__interval]))`,
  148. };
  149. });
  150. return queryLogsVolume(this, logsVolumeRequest, {
  151. extractLevel,
  152. range: request.range,
  153. targets: request.targets,
  154. });
  155. }
  156. query(request: DataQueryRequest<LokiQuery>): Observable<DataQueryResponse> {
  157. const subQueries: Array<Observable<DataQueryResponse>> = [];
  158. const scopedVars = {
  159. ...request.scopedVars,
  160. ...this.getRangeScopedVars(request.range),
  161. };
  162. if (this.useBackendMode) {
  163. const queries = request.targets
  164. .map(getNormalizedLokiQuery) // "fix" the `.queryType` prop
  165. .map((q) => ({ ...q, maxLines: q.maxLines || this.maxLines })); // set maxLines if not set
  166. const fixedRequest = {
  167. ...request,
  168. targets: queries,
  169. };
  170. const streamQueries = fixedRequest.targets.filter((q) => q.queryType === LokiQueryType.Stream);
  171. if (config.featureToggles.lokiLive && streamQueries.length > 0 && fixedRequest.rangeRaw?.to === 'now') {
  172. // this is still an in-development feature,
  173. // we do not support mixing stream-queries with normal-queries for now.
  174. const streamRequest = {
  175. ...fixedRequest,
  176. targets: streamQueries,
  177. };
  178. return merge(...streamQueries.map((q) => doLokiChannelStream(q, this, streamRequest)));
  179. }
  180. if (fixedRequest.liveStreaming) {
  181. return this.runLiveQueryThroughBackend(fixedRequest);
  182. } else {
  183. return super
  184. .query(fixedRequest)
  185. .pipe(
  186. map((response) =>
  187. transformBackendResult(response, fixedRequest.targets, this.instanceSettings.jsonData.derivedFields ?? [])
  188. )
  189. );
  190. }
  191. }
  192. const filteredTargets = request.targets
  193. .filter((target) => target.expr && !target.hide)
  194. .map((target) => {
  195. const expr = this.addAdHocFilters(target.expr);
  196. return {
  197. ...target,
  198. expr: this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr),
  199. };
  200. });
  201. for (const target of filteredTargets) {
  202. if (target.instant || target.queryType === LokiQueryType.Instant) {
  203. subQueries.push(this.runInstantQuery(target, request, filteredTargets.length));
  204. } else if (
  205. config.featureToggles.lokiLive &&
  206. target.queryType === LokiQueryType.Stream &&
  207. request.rangeRaw?.to === 'now'
  208. ) {
  209. subQueries.push(doLokiChannelStream(target, this, request));
  210. } else {
  211. subQueries.push(this.runRangeQuery(target, request));
  212. }
  213. }
  214. // No valid targets, return the empty result to save a round trip.
  215. if (isEmpty(subQueries)) {
  216. return of({
  217. data: [],
  218. state: LoadingState.Done,
  219. });
  220. }
  221. return merge(...subQueries);
  222. }
  223. runLiveQueryThroughBackend(request: DataQueryRequest<LokiQuery>): Observable<DataQueryResponse> {
  224. // this only works in explore-mode, so variables don't need to be handled,
  225. // and only for logs-queries, not metric queries
  226. const logsQueries = request.targets.filter((query) => query.expr !== '' && !isMetricsQuery(query.expr));
  227. if (logsQueries.length === 0) {
  228. return of({
  229. data: [],
  230. state: LoadingState.Done,
  231. });
  232. }
  233. const subQueries = logsQueries.map((query) => {
  234. const maxDataPoints = query.maxLines || this.maxLines;
  235. // FIXME: currently we are running it through the frontend still.
  236. return this.runLiveQuery(query, maxDataPoints);
  237. });
  238. return merge(...subQueries);
  239. }
  240. runInstantQuery = (
  241. target: LokiQuery,
  242. options: DataQueryRequest<LokiQuery>,
  243. responseListLength = 1
  244. ): Observable<DataQueryResponse> => {
  245. const timeNs = this.getTime(options.range.to, true);
  246. const queryLimit = isMetricsQuery(target.expr) ? options.maxDataPoints : target.maxLines;
  247. const query = {
  248. query: target.expr,
  249. time: `${timeNs + (1e9 - (timeNs % 1e9))}`,
  250. limit: Math.min(queryLimit || Infinity, this.maxLines),
  251. direction: target.direction === LokiQueryDirection.Forward ? 'FORWARD' : 'BACKWARD',
  252. };
  253. /** Used only for results of metrics instant queries */
  254. const meta: QueryResultMeta = {
  255. preferredVisualisationType: 'table',
  256. };
  257. return this._request(INSTANT_QUERY_ENDPOINT, query).pipe(
  258. map((response) => {
  259. if (response.data.data.resultType === LokiResultType.Stream) {
  260. return {
  261. data: response.data
  262. ? lokiStreamsToDataFrames(
  263. response.data as LokiStreamResponse,
  264. target,
  265. query.limit,
  266. this.instanceSettings.jsonData
  267. )
  268. : [],
  269. key: `${target.refId}_instant`,
  270. };
  271. }
  272. return {
  273. data: [lokiResultsToTableModel(response.data.data.result, responseListLength, target.refId, meta)],
  274. key: `${target.refId}_instant`,
  275. };
  276. }),
  277. catchError((err) => throwError(() => this.processError(err, target)))
  278. );
  279. };
  280. createRangeQuery(target: LokiQuery, options: RangeQueryOptions, limit: number): LokiRangeQueryRequest {
  281. const query = target.expr;
  282. let range: { start?: number; end?: number; step?: number } = {};
  283. if (options.range) {
  284. const startNs = this.getTime(options.range.from, false);
  285. const endNs = this.getTime(options.range.to, true);
  286. const rangeMs = Math.ceil((endNs - startNs) / 1e6);
  287. const resolution = target.resolution || (DEFAULT_RESOLUTION.value as number);
  288. const adjustedInterval =
  289. this.adjustInterval((options as DataQueryRequest<LokiQuery>).intervalMs || 1000, resolution, rangeMs) / 1000;
  290. // We want to ceil to 3 decimal places
  291. const step = Math.ceil(adjustedInterval * 1000) / 1000;
  292. range = {
  293. start: startNs,
  294. end: endNs,
  295. step,
  296. };
  297. }
  298. return {
  299. ...DEFAULT_QUERY_PARAMS,
  300. ...range,
  301. query,
  302. limit,
  303. direction: target.direction === LokiQueryDirection.Forward ? 'FORWARD' : 'BACKWARD',
  304. };
  305. }
  306. /**
  307. * Attempts to send a query to /loki/api/v1/query_range
  308. */
  309. runRangeQuery = (target: LokiQuery, options: RangeQueryOptions): Observable<DataQueryResponse> => {
  310. // For metric query we use maxDataPoints from the request options which should be something like width of the
  311. // visualisation in pixels. In case of logs request we either use lines limit defined in the query target or
  312. // global limit defined for the data source which ever is lower.
  313. let maxDataPoints = isMetricsQuery(target.expr)
  314. ? // We fallback to maxLines here because maxDataPoints is defined as possibly undefined. Not sure that can
  315. // actually happen both Dashboards and Explore should send some value here. If not maxLines does not make that
  316. // much sense but nor any other arbitrary value.
  317. (options as DataQueryRequest<LokiQuery>).maxDataPoints || this.maxLines
  318. : // If user wants maxLines 0 we still fallback to data source limit. I think that makes sense as why would anyone
  319. // want to do a query and not see any results?
  320. target.maxLines || this.maxLines;
  321. if ((options as DataQueryRequest<LokiQuery>).liveStreaming) {
  322. return this.runLiveQuery(target, maxDataPoints);
  323. }
  324. const query = this.createRangeQuery(target, options, maxDataPoints);
  325. const headers = target.volumeQuery ? { 'X-Query-Tags': 'Source=logvolhist' } : undefined;
  326. return this._request(RANGE_QUERY_ENDPOINT, query, { headers }).pipe(
  327. catchError((err) => throwError(() => this.processError(err, target))),
  328. switchMap((response) =>
  329. processRangeQueryResponse(
  330. response.data,
  331. target,
  332. query,
  333. maxDataPoints,
  334. this.instanceSettings.jsonData,
  335. (options as DataQueryRequest<LokiQuery>).scopedVars
  336. )
  337. )
  338. );
  339. };
  340. createLiveTarget(target: LokiQuery, maxDataPoints: number): LokiLiveTarget {
  341. const query = target.expr;
  342. const baseUrl = this.instanceSettings.url;
  343. const params = serializeParams({ query });
  344. return {
  345. query,
  346. url: convertToWebSocketUrl(`${baseUrl}/loki/api/v1/tail?${params}`),
  347. refId: target.refId,
  348. size: maxDataPoints,
  349. };
  350. }
  351. /**
  352. * Runs live queries which in this case means creating a websocket and listening on it for new logs.
  353. * This returns a bit different dataFrame than runQueries as it returns single dataframe even if there are multiple
  354. * Loki streams, sets only common labels on dataframe.labels and has additional dataframe.fields.labels for unique
  355. * labels per row.
  356. */
  357. runLiveQuery = (target: LokiQuery, maxDataPoints: number): Observable<DataQueryResponse> => {
  358. const liveTarget = this.createLiveTarget(target, maxDataPoints);
  359. return this.streams.getStream(liveTarget).pipe(
  360. map((data) => ({
  361. data: data || [],
  362. key: `loki-${liveTarget.refId}`,
  363. state: LoadingState.Streaming,
  364. })),
  365. catchError((err: any) => {
  366. return throwError(() => `Live tailing was stopped due to following error: ${err.reason}`);
  367. })
  368. );
  369. };
  370. getRangeScopedVars(range: TimeRange = this.timeSrv.timeRange()) {
  371. const msRange = range.to.diff(range.from);
  372. const sRange = Math.round(msRange / 1000);
  373. return {
  374. __range_ms: { text: msRange, value: msRange },
  375. __range_s: { text: sRange, value: sRange },
  376. __range: { text: sRange + 's', value: sRange + 's' },
  377. };
  378. }
  379. interpolateVariablesInQueries(queries: LokiQuery[], scopedVars: ScopedVars): LokiQuery[] {
  380. let expandedQueries = queries;
  381. if (queries && queries.length) {
  382. expandedQueries = queries.map((query) => ({
  383. ...query,
  384. datasource: this.getRef(),
  385. expr: this.templateSrv.replace(query.expr, scopedVars, this.interpolateQueryExpr),
  386. }));
  387. }
  388. return expandedQueries;
  389. }
  390. getQueryDisplayText(query: LokiQuery) {
  391. return query.expr;
  392. }
  393. getTimeRangeParams() {
  394. const timeRange = this.timeSrv.timeRange();
  395. return { start: timeRange.from.valueOf() * NS_IN_MS, end: timeRange.to.valueOf() * NS_IN_MS };
  396. }
  397. async importFromAbstractQueries(abstractQueries: AbstractQuery[]): Promise<LokiQuery[]> {
  398. await this.languageProvider.start();
  399. const existingKeys = this.languageProvider.labelKeys;
  400. if (existingKeys && existingKeys.length) {
  401. abstractQueries = abstractQueries.map((abstractQuery) => {
  402. abstractQuery.labelMatchers = abstractQuery.labelMatchers.filter((labelMatcher) => {
  403. return existingKeys.includes(labelMatcher.name);
  404. });
  405. return abstractQuery;
  406. });
  407. }
  408. return abstractQueries.map((abstractQuery) => this.languageProvider.importFromAbstractQuery(abstractQuery));
  409. }
  410. async exportToAbstractQueries(queries: LokiQuery[]): Promise<AbstractQuery[]> {
  411. return queries.map((query) => this.languageProvider.exportToAbstractQuery(query));
  412. }
  413. async metadataRequest(url: string, params?: Record<string, string | number>) {
  414. // url must not start with a `/`, otherwise the AJAX-request
  415. // going from the browser will contain `//`, which can cause problems.
  416. if (url.startsWith('/')) {
  417. throw new Error(`invalid metadata request url: ${url}`);
  418. }
  419. if (this.useBackendMode) {
  420. const res = await this.getResource(url, params);
  421. return res.data || [];
  422. } else {
  423. const lokiURL = `${LOKI_ENDPOINT}/${url}`;
  424. const res = await lastValueFrom(this._request(lokiURL, params, { hideFromInspector: true }));
  425. return res.data.data || [];
  426. }
  427. }
  428. async metricFindQuery(query: string) {
  429. if (!query) {
  430. return Promise.resolve([]);
  431. }
  432. const interpolated = this.templateSrv.replace(query, {}, this.interpolateQueryExpr);
  433. return await this.processMetricFindQuery(interpolated);
  434. }
  435. async processMetricFindQuery(query: string) {
  436. const labelNamesRegex = /^label_names\(\)\s*$/;
  437. const labelValuesRegex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/;
  438. const labelNames = query.match(labelNamesRegex);
  439. if (labelNames) {
  440. return await this.labelNamesQuery();
  441. }
  442. const labelValues = query.match(labelValuesRegex);
  443. if (labelValues) {
  444. // If we have query expr, use /series endpoint
  445. if (labelValues[1]) {
  446. return await this.labelValuesSeriesQuery(labelValues[1], labelValues[2]);
  447. }
  448. return await this.labelValuesQuery(labelValues[2]);
  449. }
  450. return Promise.resolve([]);
  451. }
  452. async labelNamesQuery() {
  453. const url = 'labels';
  454. const params = this.getTimeRangeParams();
  455. const result = await this.metadataRequest(url, params);
  456. return result.map((value: string) => ({ text: value }));
  457. }
  458. async labelValuesQuery(label: string) {
  459. const params = this.getTimeRangeParams();
  460. const url = `label/${label}/values`;
  461. const result = await this.metadataRequest(url, params);
  462. return result.map((value: string) => ({ text: value }));
  463. }
  464. async labelValuesSeriesQuery(expr: string, label: string) {
  465. const timeParams = this.getTimeRangeParams();
  466. const params = {
  467. ...timeParams,
  468. 'match[]': expr,
  469. };
  470. const url = 'series';
  471. const streams = new Set();
  472. const result = await this.metadataRequest(url, params);
  473. result.forEach((stream: { [key: string]: string }) => {
  474. if (stream[label]) {
  475. streams.add({ text: stream[label] });
  476. }
  477. });
  478. return Array.from(streams);
  479. }
  480. // By implementing getTagKeys and getTagValues we add ad-hoc filtters functionality
  481. async getTagKeys() {
  482. return await this.labelNamesQuery();
  483. }
  484. async getTagValues(options: any = {}) {
  485. return await this.labelValuesQuery(options.key);
  486. }
  487. interpolateQueryExpr(value: any, variable: any) {
  488. // if no multi or include all do not regexEscape
  489. if (!variable.multi && !variable.includeAll) {
  490. return lokiRegularEscape(value);
  491. }
  492. if (typeof value === 'string') {
  493. return lokiSpecialRegexEscape(value);
  494. }
  495. const escapedValues = lodashMap(value, lokiSpecialRegexEscape);
  496. return escapedValues.join('|');
  497. }
  498. modifyQuery(query: LokiQuery, action: any): LokiQuery {
  499. let expression = query.expr ?? '';
  500. switch (action.type) {
  501. case 'ADD_FILTER': {
  502. expression = this.addLabelToQuery(expression, action.key, action.value, '=');
  503. break;
  504. }
  505. case 'ADD_FILTER_OUT': {
  506. expression = this.addLabelToQuery(expression, action.key, action.value, '!=');
  507. break;
  508. }
  509. default:
  510. break;
  511. }
  512. return { ...query, expr: expression };
  513. }
  514. getTime(date: string | DateTime, roundUp: boolean) {
  515. if (typeof date === 'string') {
  516. date = dateMath.parse(date, roundUp)!;
  517. }
  518. return Math.ceil(date.valueOf() * 1e6);
  519. }
  520. getLogRowContext = (row: LogRowModel, options?: RowContextOptions): Promise<{ data: DataFrame[] }> => {
  521. const direction = (options && options.direction) || 'BACKWARD';
  522. const limit = (options && options.limit) || 10;
  523. const { query, range } = this.prepareLogRowContextQueryTarget(row, limit, direction);
  524. const processDataFrame = (frame: DataFrame): DataFrame => {
  525. // log-row-context requires specific field-names to work, so we set them here: "ts", "line", "id"
  526. const cache = new FieldCache(frame);
  527. const timestampField = cache.getFirstFieldOfType(FieldType.time);
  528. const lineField = cache.getFirstFieldOfType(FieldType.string);
  529. const idField = cache.getFieldByName('id');
  530. if (timestampField === undefined || lineField === undefined || idField === undefined) {
  531. // this should never really happen, but i want to keep typescript happy
  532. return { ...frame, fields: [] };
  533. }
  534. return {
  535. ...frame,
  536. fields: [
  537. {
  538. ...timestampField,
  539. name: 'ts',
  540. },
  541. {
  542. ...lineField,
  543. name: 'line',
  544. },
  545. {
  546. ...idField,
  547. name: 'id',
  548. },
  549. ],
  550. };
  551. };
  552. const processResults = (result: DataQueryResponse): DataQueryResponse => {
  553. const frames: DataFrame[] = result.data;
  554. const processedFrames = frames
  555. .map((frame) => sortDataFrameByTime(frame, 'DESCENDING'))
  556. .map((frame) => processDataFrame(frame)); // rename fields if needed
  557. return {
  558. ...result,
  559. data: processedFrames,
  560. };
  561. };
  562. // this can only be called from explore currently
  563. const app = CoreApp.Explore;
  564. return lastValueFrom(
  565. this.query(makeRequest(query, range, app, `log-row-context-query-${direction}`)).pipe(
  566. catchError((err) => {
  567. const error: DataQueryError = {
  568. message: 'Error during context query. Please check JS console logs.',
  569. status: err.status,
  570. statusText: err.statusText,
  571. };
  572. throw error;
  573. }),
  574. switchMap((res) => of(processResults(res)))
  575. )
  576. );
  577. };
  578. prepareLogRowContextQueryTarget = (
  579. row: LogRowModel,
  580. limit: number,
  581. direction: 'BACKWARD' | 'FORWARD'
  582. ): { query: LokiQuery; range: TimeRange } => {
  583. const labels = this.languageProvider.getLabelKeys();
  584. const expr = Object.keys(row.labels)
  585. .map((label: string) => {
  586. if (labels.includes(label)) {
  587. // escape backslashes in label as users can't escape them by themselves
  588. return `${label}="${row.labels[label].replace(/\\/g, '\\\\')}"`;
  589. }
  590. return '';
  591. })
  592. // Filter empty strings
  593. .filter((label) => !!label)
  594. .join(',');
  595. const contextTimeBuffer = 2 * 60 * 60 * 1000; // 2h buffer
  596. const queryDirection = direction === 'FORWARD' ? LokiQueryDirection.Forward : LokiQueryDirection.Backward;
  597. const query: LokiQuery = {
  598. expr: `{${expr}}`,
  599. queryType: LokiQueryType.Range,
  600. refId: '',
  601. maxLines: limit,
  602. direction: queryDirection,
  603. };
  604. const fieldCache = new FieldCache(row.dataFrame);
  605. const tsField = fieldCache.getFirstFieldOfType(FieldType.time);
  606. if (tsField === undefined) {
  607. throw new Error('loki: dataframe missing time-field, should never happen');
  608. }
  609. const tsValue = tsField.values.get(row.rowIndex);
  610. const timestamp = toUtc(tsValue);
  611. const range =
  612. queryDirection === LokiQueryDirection.Forward
  613. ? {
  614. // start param in Loki API is inclusive so we'll have to filter out the row that this request is based from
  615. // and any other that were logged in the same ns but before the row. Right now these rows will be lost
  616. // because the are before but came it he response that should return only rows after.
  617. from: timestamp,
  618. // convert to ns, we loose some precision here but it is not that important at the far points of the context
  619. to: toUtc(row.timeEpochMs + contextTimeBuffer),
  620. }
  621. : {
  622. // convert to ns, we loose some precision here but it is not that important at the far points of the context
  623. from: toUtc(row.timeEpochMs - contextTimeBuffer),
  624. to: timestamp,
  625. };
  626. return {
  627. query,
  628. range: {
  629. from: range.from,
  630. to: range.to,
  631. raw: range,
  632. },
  633. };
  634. };
  635. testDatasource(): Promise<{ status: string; message: string }> {
  636. // Consider only last 10 minutes otherwise request takes too long
  637. const nowMs = Date.now();
  638. const params = {
  639. start: (nowMs - 10 * 60 * 1000) * NS_IN_MS,
  640. end: nowMs * NS_IN_MS,
  641. };
  642. return this.metadataRequest('labels', params).then(
  643. (values) => {
  644. return values.length > 0
  645. ? { status: 'success', message: 'Data source connected and labels found.' }
  646. : {
  647. status: 'error',
  648. message:
  649. 'Data source connected, but no labels received. Verify that Loki and Promtail is configured properly.',
  650. };
  651. },
  652. (err) => {
  653. // we did a resource-call that failed.
  654. // the only info we have, if exists, is err.data.message
  655. // (when in development-mode, err.data.error exists too, but not in production-mode)
  656. // things like err.status & err.statusText does not help,
  657. // because those will only describe how the request between browser<>server failed
  658. const info: string = err?.data?.message ?? '';
  659. const infoInParentheses = info !== '' ? ` (${info})` : '';
  660. const message = `Unable to fetch labels from Loki${infoInParentheses}, please check the server logs for more details`;
  661. return { status: 'error', message: message };
  662. }
  663. );
  664. }
  665. async annotationQuery(options: any): Promise<AnnotationEvent[]> {
  666. const { expr, maxLines, instant, tagKeys = '', titleFormat = '', textFormat = '' } = options.annotation;
  667. if (!expr) {
  668. return [];
  669. }
  670. const id = `annotation-${options.annotation.name}`;
  671. const query: LokiQuery = {
  672. refId: id,
  673. expr,
  674. maxLines,
  675. instant,
  676. queryType: instant ? LokiQueryType.Instant : LokiQueryType.Range,
  677. };
  678. const request = makeRequest(query, options.range, CoreApp.Dashboard, id);
  679. const { data } = await lastValueFrom(this.query(request));
  680. const annotations: AnnotationEvent[] = [];
  681. const splitKeys: string[] = tagKeys.split(',').filter((v: string) => v !== '');
  682. for (const frame of data) {
  683. const view = new DataFrameView<{ Time: string; Line: string; labels: Labels }>(frame);
  684. view.forEach((row) => {
  685. const { labels } = row;
  686. const maybeDuplicatedTags = Object.entries(labels)
  687. .map(([key, val]) => [key, val.trim()]) // trim all label-values
  688. .filter(([key, val]) => {
  689. if (val === '') {
  690. // remove empty
  691. return false;
  692. }
  693. // if tags are specified, remove label if does not match tags
  694. if (splitKeys.length && !splitKeys.includes(key)) {
  695. return false;
  696. }
  697. return true;
  698. })
  699. .map(([key, val]) => val); // keep only the label-value
  700. // remove duplicates
  701. const tags = Array.from(new Set(maybeDuplicatedTags));
  702. annotations.push({
  703. time: new Date(row.Time).valueOf(),
  704. title: renderLegendFormat(titleFormat, labels),
  705. text: renderLegendFormat(textFormat, labels) || row.Line,
  706. tags,
  707. });
  708. });
  709. }
  710. return annotations;
  711. }
  712. showContextToggle(row?: LogRowModel): boolean {
  713. return (row && row.searchWords && row.searchWords.length > 0) === true;
  714. }
  715. processError(err: FetchError, target: LokiQuery) {
  716. let error: DataQueryError = cloneDeep(err);
  717. error.refId = target.refId;
  718. if (error.data && err.data.message.includes('escape') && target.expr.includes('\\')) {
  719. error.data.message = `Error: ${err.data.message}. Make sure that all special characters are escaped with \\. For more information on escaping of special characters visit LogQL documentation at https://grafana.com/docs/loki/latest/logql/.`;
  720. }
  721. return error;
  722. }
  723. adjustInterval(dynamicInterval: number, resolution: number, range: number) {
  724. // Loki will drop queries that might return more than 11000 data points.
  725. // Calibrate interval if it is too small.
  726. let safeInterval = range / 11000;
  727. if (safeInterval > 1) {
  728. safeInterval = Math.ceil(safeInterval);
  729. }
  730. let adjustedInterval = Math.max(resolution * dynamicInterval, safeInterval);
  731. return adjustedInterval;
  732. }
  733. addAdHocFilters(queryExpr: string) {
  734. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  735. let expr = queryExpr;
  736. expr = adhocFilters.reduce((acc: string, filter: { key?: any; operator?: any; value?: any }) => {
  737. const { key, operator } = filter;
  738. let { value } = filter;
  739. return this.addLabelToQuery(acc, key, value, operator, true);
  740. }, expr);
  741. return expr;
  742. }
  743. addLabelToQuery(
  744. queryExpr: string,
  745. key: string,
  746. value: string | number,
  747. operator: string,
  748. // Override to make sure that we use label as actual label and not parsed label
  749. notParsedLabelOverride?: boolean
  750. ) {
  751. let escapedValue = escapeLabelValueInSelector(value.toString(), operator);
  752. if (queryHasPipeParser(queryExpr) && !isMetricsQuery(queryExpr) && !notParsedLabelOverride) {
  753. // If query has parser, we treat all labels as parsed and use | key="value" syntax
  754. return addParsedLabelToQuery(queryExpr, key, escapedValue, operator);
  755. } else {
  756. return addLabelToQuery(queryExpr, key, escapedValue, operator, true);
  757. }
  758. }
  759. // Used when running queries through backend
  760. filterQuery(query: LokiQuery): boolean {
  761. if (query.hide || query.expr === '') {
  762. return false;
  763. }
  764. return true;
  765. }
  766. // Used when running queries through backend
  767. applyTemplateVariables(target: LokiQuery, scopedVars: ScopedVars): LokiQuery {
  768. // We want to interpolate these variables on backend
  769. const { __interval, __interval_ms, ...rest } = scopedVars;
  770. const exprWithAdHoc = this.addAdHocFilters(target.expr);
  771. return {
  772. ...target,
  773. legendFormat: this.templateSrv.replace(target.legendFormat, rest),
  774. expr: this.templateSrv.replace(exprWithAdHoc, rest, this.interpolateQueryExpr),
  775. };
  776. }
  777. interpolateString(string: string) {
  778. return this.templateSrv.replace(string, undefined, this.interpolateQueryExpr);
  779. }
  780. getVariables(): string[] {
  781. return this.templateSrv.getVariables().map((v) => `$${v.name}`);
  782. }
  783. }
  784. export function lokiRegularEscape(value: any) {
  785. if (typeof value === 'string') {
  786. return value.replace(/'/g, "\\\\'");
  787. }
  788. return value;
  789. }
  790. export function lokiSpecialRegexEscape(value: any) {
  791. if (typeof value === 'string') {
  792. return lokiRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()|]/g, '\\\\$&'));
  793. }
  794. return value;
  795. }
  796. /**
  797. * Checks if the query expression uses function and so should return a time series instead of logs.
  798. * Sometimes important to know that before we actually do the query.
  799. */
  800. export function isMetricsQuery(query: string): boolean {
  801. if (!query) {
  802. return false;
  803. }
  804. const tokens = Prism.tokenize(query, syntax);
  805. return tokens.some((t) => {
  806. // Not sure in which cases it can be string maybe if nothing matched which means it should not be a function
  807. return typeof t !== 'string' && t.type === 'function';
  808. });
  809. }
  810. function extractLevel(dataFrame: DataFrame): LogLevel {
  811. let valueField;
  812. try {
  813. valueField = new FieldCache(dataFrame).getFirstFieldOfType(FieldType.number);
  814. } catch {}
  815. return valueField?.labels ? getLogLevelFromLabels(valueField.labels) : LogLevel.unknown;
  816. }
  817. function getLogLevelFromLabels(labels: Labels): LogLevel {
  818. const labelNames = ['level', 'lvl', 'loglevel'];
  819. let levelLabel;
  820. for (let labelName of labelNames) {
  821. if (labelName in labels) {
  822. levelLabel = labelName;
  823. break;
  824. }
  825. }
  826. return levelLabel ? getLogLevelFromKey(labels[levelLabel]) : LogLevel.unknown;
  827. }