hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 8,
"code_window": [
"\t\t}\n",
"\n",
"\t\treturn new Promise<boolean>(async (resolve) => {\n",
"\t\t\tconst Registry = await import('vscode-windows-registry');\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tconst Registry = await import('vscode-windows-registry');\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./list';
import { IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { range } from 'vs/base/common/arrays';
import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent } from './list';
import { List, IListStyles, IListOptions, IListAccessibilityProvider, IListOptionsUpdate } from './listWidget';
import { IPagedModel } from 'vs/base/common/paging';
import { Event } from 'vs/base/common/event';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { IThemable } from 'vs/base/common/styler';
export interface IPagedRenderer<TElement, TTemplateData> extends IListRenderer<TElement, TTemplateData> {
renderPlaceholder(index: number, templateData: TTemplateData): void;
}
export interface ITemplateData<T> {
data?: T;
disposable?: IDisposable;
}
class PagedRenderer<TElement, TTemplateData> implements IListRenderer<number, ITemplateData<TTemplateData>> {
get templateId(): string { return this.renderer.templateId; }
constructor(
private renderer: IPagedRenderer<TElement, TTemplateData>,
private modelProvider: () => IPagedModel<TElement>
) { }
renderTemplate(container: HTMLElement): ITemplateData<TTemplateData> {
const data = this.renderer.renderTemplate(container);
return { data, disposable: Disposable.None };
}
renderElement(index: number, _: number, data: ITemplateData<TTemplateData>, height: number | undefined): void {
if (data.disposable) {
data.disposable.dispose();
}
if (!data.data) {
return;
}
const model = this.modelProvider();
if (model.isResolved(index)) {
return this.renderer.renderElement(model.get(index), index, data.data, height);
}
const cts = new CancellationTokenSource();
const promise = model.resolve(index, cts.token);
data.disposable = { dispose: () => cts.cancel() };
this.renderer.renderPlaceholder(index, data.data);
promise.then(entry => this.renderer.renderElement(entry, index, data.data!, height));
}
disposeTemplate(data: ITemplateData<TTemplateData>): void {
if (data.disposable) {
data.disposable.dispose();
data.disposable = undefined;
}
if (data.data) {
this.renderer.disposeTemplate(data.data);
data.data = undefined;
}
}
}
class PagedAccessibilityProvider<T> implements IListAccessibilityProvider<number> {
constructor(
private modelProvider: () => IPagedModel<T>,
private accessibilityProvider: IListAccessibilityProvider<T>
) { }
getWidgetAriaLabel(): string {
return this.accessibilityProvider.getWidgetAriaLabel();
}
getAriaLabel(index: number): string | null {
const model = this.modelProvider();
if (!model.isResolved(index)) {
return null;
}
return this.accessibilityProvider.getAriaLabel(model.get(index));
}
}
export interface IPagedListOptions<T> {
readonly enableKeyboardNavigation?: boolean;
readonly automaticKeyboardNavigation?: boolean;
readonly ariaLabel?: string;
readonly keyboardSupport?: boolean;
readonly multipleSelectionSupport?: boolean;
readonly accessibilityProvider?: IListAccessibilityProvider<T>;
// list view options
readonly useShadows?: boolean;
readonly verticalScrollMode?: ScrollbarVisibility;
readonly setRowLineHeight?: boolean;
readonly setRowHeight?: boolean;
readonly supportDynamicHeights?: boolean;
readonly mouseSupport?: boolean;
readonly horizontalScrolling?: boolean;
readonly additionalScrollHeight?: number;
}
function fromPagedListOptions<T>(modelProvider: () => IPagedModel<T>, options: IPagedListOptions<T>): IListOptions<number> {
return {
...options,
accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider)
};
}
export class PagedList<T> implements IThemable, IDisposable {
private list: List<number>;
private _model!: IPagedModel<T>;
constructor(
user: string,
container: HTMLElement,
virtualDelegate: IListVirtualDelegate<number>,
renderers: IPagedRenderer<T, any>[],
options: IPagedListOptions<T> = {}
) {
const modelProvider = () => this.model;
const pagedRenderers = renderers.map(r => new PagedRenderer<T, ITemplateData<T>>(r, modelProvider));
this.list = new List(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
}
updateOptions(options: IListOptionsUpdate) {
this.list.updateOptions(options);
}
getHTMLElement(): HTMLElement {
return this.list.getHTMLElement();
}
isDOMFocused(): boolean {
return this.list.getHTMLElement() === document.activeElement;
}
domFocus(): void {
this.list.domFocus();
}
get onDidFocus(): Event<void> {
return this.list.onDidFocus;
}
get onDidBlur(): Event<void> {
return this.list.onDidBlur;
}
get widget(): List<number> {
return this.list;
}
get onDidDispose(): Event<void> {
return this.list.onDidDispose;
}
get onMouseClick(): Event<IListMouseEvent<T>> {
return Event.map(this.list.onMouseClick, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
}
get onMouseDblClick(): Event<IListMouseEvent<T>> {
return Event.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
}
get onTap(): Event<IListMouseEvent<T>> {
return Event.map(this.list.onTap, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
}
get onPointer(): Event<IListMouseEvent<T>> {
return Event.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
}
get onDidChangeFocus(): Event<IListEvent<T>> {
return Event.map(this.list.onDidChangeFocus, ({ elements, indexes, browserEvent }) => ({ elements: elements.map(e => this._model.get(e)), indexes, browserEvent }));
}
get onDidChangeSelection(): Event<IListEvent<T>> {
return Event.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map(e => this._model.get(e)), indexes, browserEvent }));
}
get onContextMenu(): Event<IListContextMenuEvent<T>> {
return Event.map(this.list.onContextMenu, ({ element, index, anchor, browserEvent }) => (typeof element === 'undefined' ? { element, index, anchor, browserEvent } : { element: this._model.get(element), index, anchor, browserEvent }));
}
get model(): IPagedModel<T> {
return this._model;
}
set model(model: IPagedModel<T>) {
this._model = model;
this.list.splice(0, this.list.length, range(model.length));
}
get length(): number {
return this.list.length;
}
get scrollTop(): number {
return this.list.scrollTop;
}
set scrollTop(scrollTop: number) {
this.list.scrollTop = scrollTop;
}
get scrollLeft(): number {
return this.list.scrollLeft;
}
set scrollLeft(scrollLeft: number) {
this.list.scrollLeft = scrollLeft;
}
setFocus(indexes: number[]): void {
this.list.setFocus(indexes);
}
focusNext(n?: number, loop?: boolean): void {
this.list.focusNext(n, loop);
}
focusPrevious(n?: number, loop?: boolean): void {
this.list.focusPrevious(n, loop);
}
focusNextPage(): void {
this.list.focusNextPage();
}
focusPreviousPage(): void {
this.list.focusPreviousPage();
}
getFocus(): number[] {
return this.list.getFocus();
}
setSelection(indexes: number[], browserEvent?: UIEvent): void {
this.list.setSelection(indexes, browserEvent);
}
getSelection(): number[] {
return this.list.getSelection();
}
layout(height?: number, width?: number): void {
this.list.layout(height, width);
}
toggleKeyboardNavigation(): void {
this.list.toggleKeyboardNavigation();
}
reveal(index: number, relativeTop?: number): void {
this.list.reveal(index, relativeTop);
}
style(styles: IListStyles): void {
this.list.style(styles);
}
dispose(): void {
this.list.dispose();
}
}
| src/vs/base/browser/ui/list/listPaging.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00038701723678968847,
0.00018696734332479537,
0.00016551224689465016,
0.00017191722872667015,
0.00004849989272770472
] |
{
"id": 8,
"code_window": [
"\t\t}\n",
"\n",
"\t\treturn new Promise<boolean>(async (resolve) => {\n",
"\t\t\tconst Registry = await import('vscode-windows-registry');\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tconst Registry = await import('vscode-windows-registry');\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 48
} | [
{
"c": "let",
"t": "source.ts meta.var.expr.ts storage.type.ts",
"r": {
"dark_plus": "storage.type: #569CD6",
"light_plus": "storage.type: #0000FF",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "s1",
"t": "source.ts meta.var.expr.ts meta.var-single-variable.expr.ts meta.definition.variable.ts variable.other.readwrite.ts",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts meta.var-single-variable.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "=",
"t": "source.ts meta.var.expr.ts keyword.operator.assignment.ts",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "k",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": ":",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts punctuation.separator.key-value.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t\t",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "k1",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": ":",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts punctuation.separator.key-value.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "s",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts variable.other.readwrite.ts",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE"
}
},
{
"c": ",",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts punctuation.separator.comma.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\t\t",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "k2",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": ":",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts meta.object-literal.key.ts punctuation.separator.key-value.ts",
"r": {
"dark_plus": "meta.object-literal.key: #9CDCFE",
"light_plus": "meta.object-literal.key: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "meta.object-literal.key: #9CDCFE"
}
},
{
"c": " ",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "1",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts constant.numeric.decimal.ts",
"r": {
"dark_plus": "constant.numeric: #B5CEA8",
"light_plus": "constant.numeric: #098658",
"dark_vs": "constant.numeric: #B5CEA8",
"light_vs": "constant.numeric: #098658",
"hc_black": "constant.numeric: #B5CEA8"
}
},
{
"c": "\t",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts meta.object.member.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts meta.object.member.ts meta.objectliteral.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.ts meta.var.expr.ts meta.objectliteral.ts punctuation.definition.block.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.ts punctuation.terminator.statement.ts",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
}
]
| extensions/typescript-basics/test/colorize-results/test-object-literals_ts.json | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017353503790218383,
0.00017033383483067155,
0.00016728673654142767,
0.00017022431711666286,
0.0000015668480273234309
] |
{
"id": 9,
"code_window": [
"\n",
"\t\t\tlet value;\n",
"\t\t\ttry {\n",
"\t\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t\t} catch {\n",
"\t\t\t\tresolve(false);\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tlet value: string | undefined = undefined;\n",
"\t\ttry {\n",
"\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t} catch {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Database, Statement } from 'vscode-sqlite3';
import { Event } from 'vs/base/common/event';
import { timeout } from 'vs/base/common/async';
import { mapToString, setToString } from 'vs/base/common/map';
import { basename } from 'vs/base/common/path';
import { copy, renameIgnoreError, unlink } from 'vs/base/node/pfs';
import { IStorageDatabase, IStorageItemsChangeEvent, IUpdateRequest } from 'vs/base/parts/storage/common/storage';
interface IDatabaseConnection {
readonly db: Database;
readonly isInMemory: boolean;
isErroneous?: boolean;
lastError?: string;
}
export interface ISQLiteStorageDatabaseOptions {
readonly logging?: ISQLiteStorageDatabaseLoggingOptions;
}
export interface ISQLiteStorageDatabaseLoggingOptions {
logError?: (error: string | Error) => void;
logTrace?: (msg: string) => void;
}
export class SQLiteStorageDatabase implements IStorageDatabase {
static readonly IN_MEMORY_PATH = ':memory:';
get onDidChangeItemsExternal(): Event<IStorageItemsChangeEvent> { return Event.None; } // since we are the only client, there can be no external changes
private static readonly BUSY_OPEN_TIMEOUT = 2000; // timeout in ms to retry when opening DB fails with SQLITE_BUSY
private static readonly MAX_HOST_PARAMETERS = 256; // maximum number of parameters within a statement
private readonly name = basename(this.path);
private readonly logger = new SQLiteStorageDatabaseLogger(this.options.logging);
private readonly whenConnected = this.connect(this.path);
constructor(private readonly path: string, private readonly options: ISQLiteStorageDatabaseOptions = Object.create(null)) { }
async getItems(): Promise<Map<string, string>> {
const connection = await this.whenConnected;
const items = new Map<string, string>();
const rows = await this.all(connection, 'SELECT * FROM ItemTable');
rows.forEach(row => items.set(row.key, row.value));
if (this.logger.isTracing) {
this.logger.trace(`[storage ${this.name}] getItems(): ${items.size} rows`);
}
return items;
}
async updateItems(request: IUpdateRequest): Promise<void> {
const connection = await this.whenConnected;
return this.doUpdateItems(connection, request);
}
private doUpdateItems(connection: IDatabaseConnection, request: IUpdateRequest): Promise<void> {
if (this.logger.isTracing) {
this.logger.trace(`[storage ${this.name}] updateItems(): insert(${request.insert ? mapToString(request.insert) : '0'}), delete(${request.delete ? setToString(request.delete) : '0'})`);
}
return this.transaction(connection, () => {
const toInsert = request.insert;
const toDelete = request.delete;
// INSERT
if (toInsert && toInsert.size > 0) {
const keysValuesChunks: (string[])[] = [];
keysValuesChunks.push([]); // seed with initial empty chunk
// Split key/values into chunks of SQLiteStorageDatabase.MAX_HOST_PARAMETERS
// so that we can efficiently run the INSERT with as many HOST parameters as possible
let currentChunkIndex = 0;
toInsert.forEach((value, key) => {
let keyValueChunk = keysValuesChunks[currentChunkIndex];
if (keyValueChunk.length > SQLiteStorageDatabase.MAX_HOST_PARAMETERS) {
currentChunkIndex++;
keyValueChunk = [];
keysValuesChunks.push(keyValueChunk);
}
keyValueChunk.push(key, value);
});
keysValuesChunks.forEach(keysValuesChunk => {
this.prepare(connection, `INSERT INTO ItemTable VALUES ${new Array(keysValuesChunk.length / 2).fill('(?,?)').join(',')}`, stmt => stmt.run(keysValuesChunk), () => {
const keys: string[] = [];
let length = 0;
toInsert.forEach((value, key) => {
keys.push(key);
length += value.length;
});
return `Keys: ${keys.join(', ')} Length: ${length}`;
});
});
}
// DELETE
if (toDelete && toDelete.size) {
const keysChunks: (string[])[] = [];
keysChunks.push([]); // seed with initial empty chunk
// Split keys into chunks of SQLiteStorageDatabase.MAX_HOST_PARAMETERS
// so that we can efficiently run the DELETE with as many HOST parameters
// as possible
let currentChunkIndex = 0;
toDelete.forEach(key => {
let keyChunk = keysChunks[currentChunkIndex];
if (keyChunk.length > SQLiteStorageDatabase.MAX_HOST_PARAMETERS) {
currentChunkIndex++;
keyChunk = [];
keysChunks.push(keyChunk);
}
keyChunk.push(key);
});
keysChunks.forEach(keysChunk => {
this.prepare(connection, `DELETE FROM ItemTable WHERE key IN (${new Array(keysChunk.length).fill('?').join(',')})`, stmt => stmt.run(keysChunk), () => {
const keys: string[] = [];
toDelete.forEach(key => {
keys.push(key);
});
return `Keys: ${keys.join(', ')}`;
});
});
}
});
}
async close(recovery?: () => Map<string, string>): Promise<void> {
this.logger.trace(`[storage ${this.name}] close()`);
const connection = await this.whenConnected;
return this.doClose(connection, recovery);
}
private doClose(connection: IDatabaseConnection, recovery?: () => Map<string, string>): Promise<void> {
return new Promise((resolve, reject) => {
connection.db.close(closeError => {
if (closeError) {
this.handleSQLiteError(connection, `[storage ${this.name}] close(): ${closeError}`);
}
// Return early if this storage was created only in-memory
// e.g. when running tests we do not need to backup.
if (this.path === SQLiteStorageDatabase.IN_MEMORY_PATH) {
return resolve();
}
// If the DB closed successfully and we are not running in-memory
// and the DB did not get errors during runtime, make a backup
// of the DB so that we can use it as fallback in case the actual
// DB becomes corrupt in the future.
if (!connection.isErroneous && !connection.isInMemory) {
return this.backup().then(resolve, error => {
this.logger.error(`[storage ${this.name}] backup(): ${error}`);
return resolve(); // ignore failing backup
});
}
// Recovery: if we detected errors while using the DB or we are using
// an inmemory DB (as a fallback to not being able to open the DB initially)
// and we have a recovery function provided, we recreate the DB with this
// data to recover all known data without loss if possible.
if (typeof recovery === 'function') {
// Delete the existing DB. If the path does not exist or fails to
// be deleted, we do not try to recover anymore because we assume
// that the path is no longer writeable for us.
return unlink(this.path).then(() => {
// Re-open the DB fresh
return this.doConnect(this.path).then(recoveryConnection => {
const closeRecoveryConnection = () => {
return this.doClose(recoveryConnection, undefined /* do not attempt to recover again */);
};
// Store items
return this.doUpdateItems(recoveryConnection, { insert: recovery() }).then(() => closeRecoveryConnection(), error => {
// In case of an error updating items, still ensure to close the connection
// to prevent SQLITE_BUSY errors when the connection is reestablished
closeRecoveryConnection();
return Promise.reject(error);
});
});
}).then(resolve, reject);
}
// Finally without recovery we just reject
return reject(closeError || new Error('Database has errors or is in-memory without recovery option'));
});
});
}
private backup(): Promise<void> {
const backupPath = this.toBackupPath(this.path);
return copy(this.path, backupPath);
}
private toBackupPath(path: string): string {
return `${path}.backup`;
}
async checkIntegrity(full: boolean): Promise<string> {
this.logger.trace(`[storage ${this.name}] checkIntegrity(full: ${full})`);
const connection = await this.whenConnected;
const row = await this.get(connection, full ? 'PRAGMA integrity_check' : 'PRAGMA quick_check');
const integrity = full ? (row as any)['integrity_check'] : (row as any)['quick_check'];
if (connection.isErroneous) {
return `${integrity} (last error: ${connection.lastError})`;
}
if (connection.isInMemory) {
return `${integrity} (in-memory!)`;
}
return integrity;
}
private async connect(path: string, retryOnBusy: boolean = true): Promise<IDatabaseConnection> {
this.logger.trace(`[storage ${this.name}] open(${path}, retryOnBusy: ${retryOnBusy})`);
try {
return await this.doConnect(path);
} catch (error) {
this.logger.error(`[storage ${this.name}] open(): Unable to open DB due to ${error}`);
// SQLITE_BUSY should only arise if another process is locking the same DB we want
// to open at that time. This typically never happens because a DB connection is
// limited per window. However, in the event of a window reload, it may be possible
// that the previous connection was not properly closed while the new connection is
// already established.
//
// In this case we simply wait for some time and retry once to establish the connection.
//
if (error.code === 'SQLITE_BUSY' && retryOnBusy) {
await timeout(SQLiteStorageDatabase.BUSY_OPEN_TIMEOUT);
return this.connect(path, false /* not another retry */);
}
// Otherwise, best we can do is to recover from a backup if that exists, as such we
// move the DB to a different filename and try to load from backup. If that fails,
// a new empty DB is being created automatically.
//
// The final fallback is to use an in-memory DB which should only happen if the target
// folder is really not writeable for us.
//
try {
await unlink(path);
await renameIgnoreError(this.toBackupPath(path), path);
return await this.doConnect(path);
} catch (error) {
this.logger.error(`[storage ${this.name}] open(): Unable to use backup due to ${error}`);
// In case of any error to open the DB, use an in-memory
// DB so that we always have a valid DB to talk to.
return this.doConnect(SQLiteStorageDatabase.IN_MEMORY_PATH);
}
}
}
private handleSQLiteError(connection: IDatabaseConnection, msg: string): void {
connection.isErroneous = true;
connection.lastError = msg;
this.logger.error(msg);
}
private doConnect(path: string): Promise<IDatabaseConnection> {
return new Promise((resolve, reject) => {
import('vscode-sqlite3').then(sqlite3 => {
const connection: IDatabaseConnection = {
db: new (this.logger.isTracing ? sqlite3.verbose().Database : sqlite3.Database)(path, error => {
if (error) {
return connection.db ? connection.db.close(() => reject(error)) : reject(error);
}
// The following exec() statement serves two purposes:
// - create the DB if it does not exist yet
// - validate that the DB is not corrupt (the open() call does not throw otherwise)
return this.exec(connection, [
'PRAGMA user_version = 1;',
'CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)'
].join('')).then(() => {
return resolve(connection);
}, error => {
return connection.db.close(() => reject(error));
});
}),
isInMemory: path === SQLiteStorageDatabase.IN_MEMORY_PATH
};
// Errors
connection.db.on('error', error => this.handleSQLiteError(connection, `[storage ${this.name}] Error (event): ${error}`));
// Tracing
if (this.logger.isTracing) {
connection.db.on('trace', sql => this.logger.trace(`[storage ${this.name}] Trace (event): ${sql}`));
}
}, reject);
});
}
private exec(connection: IDatabaseConnection, sql: string): Promise<void> {
return new Promise((resolve, reject) => {
connection.db.exec(sql, error => {
if (error) {
this.handleSQLiteError(connection, `[storage ${this.name}] exec(): ${error}`);
return reject(error);
}
return resolve();
});
});
}
private get(connection: IDatabaseConnection, sql: string): Promise<object> {
return new Promise((resolve, reject) => {
connection.db.get(sql, (error, row) => {
if (error) {
this.handleSQLiteError(connection, `[storage ${this.name}] get(): ${error}`);
return reject(error);
}
return resolve(row);
});
});
}
private all(connection: IDatabaseConnection, sql: string): Promise<{ key: string, value: string }[]> {
return new Promise((resolve, reject) => {
connection.db.all(sql, (error, rows) => {
if (error) {
this.handleSQLiteError(connection, `[storage ${this.name}] all(): ${error}`);
return reject(error);
}
return resolve(rows);
});
});
}
private transaction(connection: IDatabaseConnection, transactions: () => void): Promise<void> {
return new Promise((resolve, reject) => {
connection.db.serialize(() => {
connection.db.run('BEGIN TRANSACTION');
transactions();
connection.db.run('END TRANSACTION', error => {
if (error) {
this.handleSQLiteError(connection, `[storage ${this.name}] transaction(): ${error}`);
return reject(error);
}
return resolve();
});
});
});
}
private prepare(connection: IDatabaseConnection, sql: string, runCallback: (stmt: Statement) => void, errorDetails: () => string): void {
const stmt = connection.db.prepare(sql);
const statementErrorListener = (error: Error) => {
this.handleSQLiteError(connection, `[storage ${this.name}] prepare(): ${error} (${sql}). Details: ${errorDetails()}`);
};
stmt.on('error', statementErrorListener);
runCallback(stmt);
stmt.finalize(error => {
if (error) {
statementErrorListener(error);
}
stmt.removeListener('error', statementErrorListener);
});
}
}
class SQLiteStorageDatabaseLogger {
private readonly logTrace: ((msg: string) => void) | undefined;
private readonly logError: ((error: string | Error) => void) | undefined;
constructor(options?: ISQLiteStorageDatabaseLoggingOptions) {
if (options && typeof options.logTrace === 'function') {
this.logTrace = options.logTrace;
}
if (options && typeof options.logError === 'function') {
this.logError = options.logError;
}
}
get isTracing(): boolean {
return !!this.logTrace;
}
trace(msg: string): void {
if (this.logTrace) {
this.logTrace(msg);
}
}
error(error: string | Error): void {
if (this.logError) {
this.logError(error);
}
}
}
| src/vs/base/parts/storage/node/storage.ts | 1 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.9778011441230774,
0.0739729106426239,
0.00015987700317054987,
0.00017104377911891788,
0.24139653146266937
] |
{
"id": 9,
"code_window": [
"\n",
"\t\t\tlet value;\n",
"\t\t\ttry {\n",
"\t\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t\t} catch {\n",
"\t\t\t\tresolve(false);\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tlet value: string | undefined = undefined;\n",
"\t\ttry {\n",
"\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t} catch {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI as uri } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { guessMimeTypes, MIME_TEXT } from 'vs/base/common/mime';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { DEBUG_SCHEME, IDebugService, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
/**
* Debug URI format
*
* a debug URI represents a Source object and the debug session where the Source comes from.
*
* debug:arbitrary_path?session=123e4567-e89b-12d3-a456-426655440000&ref=1016
* \___/ \____________/ \__________________________________________/ \______/
* | | | |
* scheme source.path session id source.reference
*
* the arbitrary_path and the session id are encoded with 'encodeURIComponent'
*
*/
export class DebugContentProvider implements IWorkbenchContribution, ITextModelContentProvider {
private static INSTANCE: DebugContentProvider;
private readonly pendingUpdates = new Map<string, CancellationTokenSource>();
constructor(
@ITextModelService textModelResolverService: ITextModelService,
@IDebugService private readonly debugService: IDebugService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IEditorWorkerService private readonly editorWorkerService: IEditorWorkerService
) {
textModelResolverService.registerTextModelContentProvider(DEBUG_SCHEME, this);
DebugContentProvider.INSTANCE = this;
}
dispose(): void {
this.pendingUpdates.forEach(cancellationSource => cancellationSource.dispose());
}
provideTextContent(resource: uri): Promise<ITextModel> | null {
return this.createOrUpdateContentModel(resource, true);
}
/**
* Reload the model content of the given resource.
* If there is no model for the given resource, this method does nothing.
*/
static refreshDebugContent(resource: uri): void {
if (DebugContentProvider.INSTANCE) {
DebugContentProvider.INSTANCE.createOrUpdateContentModel(resource, false);
}
}
/**
* Create or reload the model content of the given resource.
*/
private createOrUpdateContentModel(resource: uri, createIfNotExists: boolean): Promise<ITextModel> | null {
const model = this.modelService.getModel(resource);
if (!model && !createIfNotExists) {
// nothing to do
return null;
}
let session: IDebugSession | undefined;
if (resource.query) {
const data = Source.getEncodedDebugData(resource);
session = this.debugService.getModel().getSession(data.sessionId);
}
if (!session) {
// fallback: use focused session
session = this.debugService.getViewModel().focusedSession;
}
if (!session) {
return Promise.reject(new Error(localize('unable', "Unable to resolve the resource without a debug session")));
}
const createErrModel = (errMsg?: string) => {
this.debugService.sourceIsNotAvailable(resource);
const languageSelection = this.modeService.create(MIME_TEXT);
const message = errMsg
? localize('canNotResolveSourceWithError', "Could not load source '{0}': {1}.", resource.path, errMsg)
: localize('canNotResolveSource', "Could not load source '{0}'.", resource.path);
return this.modelService.createModel(message, languageSelection, resource);
};
return session.loadSource(resource).then(response => {
if (response && response.body) {
if (model) {
const newContent = response.body.content;
// cancel and dispose an existing update
const cancellationSource = this.pendingUpdates.get(model.id);
if (cancellationSource) {
cancellationSource.cancel();
}
// create and keep update token
const myToken = new CancellationTokenSource();
this.pendingUpdates.set(model.id, myToken);
// update text model
return this.editorWorkerService.computeMoreMinimalEdits(model.uri, [{ text: newContent, range: model.getFullModelRange() }]).then(edits => {
// remove token
this.pendingUpdates.delete(model.id);
if (!myToken.token.isCancellationRequested && edits && edits.length > 0) {
// use the evil-edit as these models show in readonly-editor only
model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
}
return model;
});
} else {
// create text model
const mime = response.body.mimeType || guessMimeTypes(resource)[0];
const languageSelection = this.modeService.create(mime);
return this.modelService.createModel(response.body.content, languageSelection, resource);
}
}
return createErrModel();
}, (err: DebugProtocol.ErrorResponse) => createErrModel(err.message));
}
}
| src/vs/workbench/contrib/debug/common/debugContentProvider.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017628599016461521,
0.00017189716163557023,
0.00016541065997444093,
0.00017244326591026038,
0.0000027206931463297224
] |
{
"id": 9,
"code_window": [
"\n",
"\t\t\tlet value;\n",
"\t\t\ttry {\n",
"\t\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t\t} catch {\n",
"\t\t\t\tresolve(false);\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tlet value: string | undefined = undefined;\n",
"\t\ttry {\n",
"\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t} catch {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { ExtHostFileSystemEventService } from 'vs/workbench/api/common/extHostFileSystemEventService';
import { IMainContext } from 'vs/workbench/api/common/extHost.protocol';
import { NullLogService } from 'vs/platform/log/common/log';
suite('ExtHostFileSystemEventService', () => {
test('FileSystemWatcher ignore events properties are reversed #26851', function () {
const protocol: IMainContext = {
getProxy: () => { return undefined!; },
set: undefined!,
assertRegistered: undefined!,
drain: undefined!
};
const watcher1 = new ExtHostFileSystemEventService(protocol, new NullLogService(), undefined!).createFileSystemWatcher('**/somethingInteresting', false, false, false);
assert.equal(watcher1.ignoreChangeEvents, false);
assert.equal(watcher1.ignoreCreateEvents, false);
assert.equal(watcher1.ignoreDeleteEvents, false);
const watcher2 = new ExtHostFileSystemEventService(protocol, new NullLogService(), undefined!).createFileSystemWatcher('**/somethingBoring', true, true, true);
assert.equal(watcher2.ignoreChangeEvents, true);
assert.equal(watcher2.ignoreCreateEvents, true);
assert.equal(watcher2.ignoreDeleteEvents, true);
});
});
| src/vs/workbench/test/browser/api/extHostFileSystemEventService.test.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017890645540319383,
0.00017387050320394337,
0.0001688989723334089,
0.00017383828526362777,
0.0000036720996376971016
] |
{
"id": 9,
"code_window": [
"\n",
"\t\t\tlet value;\n",
"\t\t\ttry {\n",
"\t\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t\t} catch {\n",
"\t\t\t\tresolve(false);\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tlet value: string | undefined = undefined;\n",
"\t\ttry {\n",
"\t\t\tvalue = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\\\Accessibility\\\\Keyboard Preference', 'On');\n",
"\t\t} catch {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Dimension } from 'vs/base/browser/dom';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IView } from 'vs/workbench/common/views';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { Composite } from 'vs/workbench/browser/composite';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { ViewPaneContainer } from './parts/views/viewPaneContainer';
import { IPaneComposite } from 'vs/workbench/common/panecomposite';
import { IAction, IActionViewItem, Separator } from 'vs/base/common/actions';
import { ViewContainerMenuActions } from 'vs/workbench/browser/parts/views/viewMenuActions';
import { MenuId } from 'vs/platform/actions/common/actions';
export class PaneComposite extends Composite implements IPaneComposite {
private menuActions: ViewContainerMenuActions;
constructor(
id: string,
protected readonly viewPaneContainer: ViewPaneContainer,
@ITelemetryService telemetryService: ITelemetryService,
@IStorageService protected storageService: IStorageService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IContextMenuService protected contextMenuService: IContextMenuService,
@IExtensionService protected extensionService: IExtensionService,
@IWorkspaceContextService protected contextService: IWorkspaceContextService
) {
super(id, telemetryService, themeService, storageService);
this.menuActions = this._register(this.instantiationService.createInstance(ViewContainerMenuActions, this.getId(), MenuId.ViewContainerTitleContext));
this._register(this.viewPaneContainer.onTitleAreaUpdate(() => this.updateTitleArea()));
}
create(parent: HTMLElement): void {
this.viewPaneContainer.create(parent);
}
setVisible(visible: boolean): void {
super.setVisible(visible);
this.viewPaneContainer.setVisible(visible);
}
layout(dimension: Dimension): void {
this.viewPaneContainer.layout(dimension);
}
getOptimalWidth(): number {
return this.viewPaneContainer.getOptimalWidth();
}
openView<T extends IView>(id: string, focus?: boolean): T | undefined {
return this.viewPaneContainer.openView(id, focus) as T;
}
getViewPaneContainer(): ViewPaneContainer {
return this.viewPaneContainer;
}
getActionsContext(): unknown {
return this.getViewPaneContainer().getActionsContext();
}
getContextMenuActions(): ReadonlyArray<IAction> {
const result = [];
result.push(...this.menuActions.getContextMenuActions());
if (result.length) {
result.push(new Separator());
}
result.push(...this.viewPaneContainer.getContextMenuActions());
return result;
}
getActions(): ReadonlyArray<IAction> {
return this.viewPaneContainer.getActions();
}
getSecondaryActions(): ReadonlyArray<IAction> {
return this.viewPaneContainer.getSecondaryActions();
}
getActionViewItem(action: IAction): IActionViewItem | undefined {
return this.viewPaneContainer.getActionViewItem(action);
}
getTitle(): string {
return this.viewPaneContainer.getTitle();
}
saveState(): void {
super.saveState();
}
focus(): void {
this.viewPaneContainer.focus();
}
}
| src/vs/workbench/browser/panecomposite.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017708858649712056,
0.0001714263780741021,
0.0001658830587984994,
0.00017271196702495217,
0.0000038332277654262725
] |
{
"id": 10,
"code_window": [
"\n",
"\t\t\tresolve(value === '1');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tsetAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {\n",
"\t\tsuper.setAccessibilitySupport(accessibilitySupport);\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn value === '1';\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { isWindows } from 'vs/base/common/platform';
suite('Windows Native Helpers', () => {
if (!isWindows) {
return;
}
test('windows-mutex', async () => {
const mutex = await import('windows-mutex');
assert.ok(mutex && typeof mutex.isActive === 'function', 'Unable to load windows-mutex dependency.');
assert.ok(typeof mutex.isActive === 'function', 'Unable to load windows-mutex dependency.');
});
test('windows-foreground-love', async () => {
const foregroundLove = await import('windows-foreground-love');
assert.ok(foregroundLove && typeof foregroundLove.allowSetForegroundWindow === 'function', 'Unable to load windows-foreground-love dependency.');
});
test('windows-process-tree', async () => {
const processTree = await import('windows-process-tree');
assert.ok(processTree && typeof processTree.getProcessTree === 'function', 'Unable to load windows-process-tree dependency.');
});
test('vscode-windows-ca-certs', async () => {
const windowsCerts = await new Promise<any>((resolve, reject) => {
require(['vscode-windows-ca-certs'], resolve, reject);
});
assert.ok(windowsCerts, 'Unable to load vscode-windows-ca-certs dependency.');
});
test('vscode-windows-registry', async () => {
const windowsRegistry = await import('vscode-windows-registry');
assert.ok(windowsRegistry && typeof windowsRegistry.GetStringRegKey === 'function', 'Unable to load vscode-windows-registry dependency.');
});
});
| src/vs/code/test/electron-main/nativeHelpers.test.ts | 1 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.0001790238602552563,
0.00017390595166943967,
0.00016673955542501062,
0.00017515502986498177,
0.000004043292392452713
] |
{
"id": 10,
"code_window": [
"\n",
"\t\t\tresolve(value === '1');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tsetAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {\n",
"\t\tsuper.setAccessibilitySupport(accessibilitySupport);\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn value === '1';\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { TerminalValidatedLocalLinkProvider } from 'vs/workbench/contrib/terminal/browser/links/terminalValidatedLocalLinkProvider';
import { Terminal, ILink } from 'xterm';
import { OperatingSystem } from 'vs/base/common/platform';
import { format } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
const unixLinks = [
'/foo',
'~/foo',
'./foo',
'../foo',
'/foo/bar',
'foo/bar'
];
const windowsLinks = [
'c:\\foo',
'\\\\?\\c:\\foo',
'c:/foo',
'.\\foo',
'./foo',
'..\\foo',
'~\\foo',
'~/foo',
'c:/foo/bar',
'c:\\foo\\bar',
'c:\\foo/bar\\baz',
'foo/bar',
'foo/bar',
'foo\\bar'
];
interface LinkFormatInfo {
urlFormat: string;
line?: string;
column?: string;
}
const supportedLinkFormats: LinkFormatInfo[] = [
{ urlFormat: '{0}' },
{ urlFormat: '{0} on line {1}', line: '5' },
{ urlFormat: '{0} on line {1}, column {2}', line: '5', column: '3' },
{ urlFormat: '{0}:line {1}', line: '5' },
{ urlFormat: '{0}:line {1}, column {2}', line: '5', column: '3' },
{ urlFormat: '{0}({1})', line: '5' },
{ urlFormat: '{0} ({1})', line: '5' },
{ urlFormat: '{0}({1},{2})', line: '5', column: '3' },
{ urlFormat: '{0} ({1},{2})', line: '5', column: '3' },
{ urlFormat: '{0}({1}, {2})', line: '5', column: '3' },
{ urlFormat: '{0} ({1}, {2})', line: '5', column: '3' },
{ urlFormat: '{0}:{1}', line: '5' },
{ urlFormat: '{0}:{1}:{2}', line: '5', column: '3' },
{ urlFormat: '{0}[{1}]', line: '5' },
{ urlFormat: '{0} [{1}]', line: '5' },
{ urlFormat: '{0}[{1},{2}]', line: '5', column: '3' },
{ urlFormat: '{0} [{1},{2}]', line: '5', column: '3' },
{ urlFormat: '{0}[{1}, {2}]', line: '5', column: '3' },
{ urlFormat: '{0} [{1}, {2}]', line: '5', column: '3' },
{ urlFormat: '{0}",{1}', line: '5' }
];
suite('Workbench - TerminalValidatedLocalLinkProvider', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService = new TestInstantiationService();
instantiationService.stub(IConfigurationService, TestConfigurationService);
});
async function assertLink(text: string, os: OperatingSystem, expected: { text: string, range: [number, number][] }[]) {
const xterm = new Terminal();
const provider = instantiationService.createInstance(TerminalValidatedLocalLinkProvider, xterm, os, () => { }, () => { }, () => { }, (_: string, cb: (result: { uri: URI, isDirectory: boolean } | undefined) => void) => { cb({ uri: URI.file('/'), isDirectory: false }); });
// Write the text and wait for the parser to finish
await new Promise<void>(r => xterm.write(text, r));
// Ensure all links are provided
const links = (await new Promise<ILink[] | undefined>(r => provider.provideLinks(1, r)))!;
assert.equal(links.length, expected.length);
const actual = links.map(e => ({
text: e.text,
range: e.range
}));
const expectedVerbose = expected.map(e => ({
text: e.text,
range: {
start: { x: e.range[0][0], y: e.range[0][1] },
end: { x: e.range[1][0], y: e.range[1][1] },
}
}));
assert.deepEqual(actual, expectedVerbose);
}
suite('Linux/macOS', () => {
unixLinks.forEach(baseLink => {
suite(`Link: ${baseLink}`, () => {
for (let i = 0; i < supportedLinkFormats.length; i++) {
const linkFormat = supportedLinkFormats[i];
test(`Format: ${linkFormat.urlFormat}`, async () => {
const formattedLink = format(linkFormat.urlFormat, baseLink, linkFormat.line, linkFormat.column);
await assertLink(formattedLink, OperatingSystem.Linux, [{ text: formattedLink, range: [[1, 1], [formattedLink.length, 1]] }]);
await assertLink(` ${formattedLink} `, OperatingSystem.Linux, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
await assertLink(`(${formattedLink})`, OperatingSystem.Linux, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
await assertLink(`[${formattedLink}]`, OperatingSystem.Linux, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
});
}
});
});
test('Git diff links', async () => {
await assertLink(`diff --git a/foo/bar b/foo/bar`, OperatingSystem.Linux, [
{ text: 'foo/bar', range: [[14, 1], [20, 1]] },
{ text: 'foo/bar', range: [[24, 1], [30, 1]] }
]);
await assertLink(`--- a/foo/bar`, OperatingSystem.Linux, [{ text: 'foo/bar', range: [[7, 1], [13, 1]] }]);
await assertLink(`+++ b/foo/bar`, OperatingSystem.Linux, [{ text: 'foo/bar', range: [[7, 1], [13, 1]] }]);
});
});
suite('Windows', () => {
windowsLinks.forEach(baseLink => {
suite(`Link "${baseLink}"`, () => {
for (let i = 0; i < supportedLinkFormats.length; i++) {
const linkFormat = supportedLinkFormats[i];
test(`Format: ${linkFormat.urlFormat}`, async () => {
const formattedLink = format(linkFormat.urlFormat, baseLink, linkFormat.line, linkFormat.column);
await assertLink(formattedLink, OperatingSystem.Windows, [{ text: formattedLink, range: [[1, 1], [formattedLink.length, 1]] }]);
await assertLink(` ${formattedLink} `, OperatingSystem.Windows, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
await assertLink(`(${formattedLink})`, OperatingSystem.Windows, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
await assertLink(`[${formattedLink}]`, OperatingSystem.Windows, [{ text: formattedLink, range: [[2, 1], [formattedLink.length + 1, 1]] }]);
});
}
});
});
test('Git diff links', async () => {
await assertLink(`diff --git a/foo/bar b/foo/bar`, OperatingSystem.Linux, [
{ text: 'foo/bar', range: [[14, 1], [20, 1]] },
{ text: 'foo/bar', range: [[24, 1], [30, 1]] }
]);
await assertLink(`--- a/foo/bar`, OperatingSystem.Linux, [{ text: 'foo/bar', range: [[7, 1], [13, 1]] }]);
await assertLink(`+++ b/foo/bar`, OperatingSystem.Linux, [{ text: 'foo/bar', range: [[7, 1], [13, 1]] }]);
});
});
test('should support multiple link results', async () => {
await assertLink('./foo ./bar', OperatingSystem.Linux, [
{ range: [[1, 1], [5, 1]], text: './foo' },
{ range: [[7, 1], [11, 1]], text: './bar' }
]);
});
});
| src/vs/workbench/contrib/terminal/test/browser/links/terminalValidatedLocalLinkProvider.test.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00023341675114352256,
0.00017533882055431604,
0.0001671824575169012,
0.00017138768453150988,
0.00001520441765023861
] |
{
"id": 10,
"code_window": [
"\n",
"\t\t\tresolve(value === '1');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tsetAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {\n",
"\t\tsuper.setAccessibilitySupport(accessibilitySupport);\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn value === '1';\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Constants } from 'vs/base/common/uint';
import { HorizontalRange } from 'vs/editor/common/view/renderingContext';
class FloatHorizontalRange {
_floatHorizontalRangeBrand: void;
public readonly left: number;
public readonly width: number;
constructor(left: number, width: number) {
this.left = left;
this.width = width;
}
public toString(): string {
return `[${this.left},${this.width}]`;
}
public static compare(a: FloatHorizontalRange, b: FloatHorizontalRange): number {
return a.left - b.left;
}
}
export class RangeUtil {
/**
* Reusing the same range here
* because IE is buggy and constantly freezes when using a large number
* of ranges and calling .detach on them
*/
private static _handyReadyRange: Range;
private static _createRange(): Range {
if (!this._handyReadyRange) {
this._handyReadyRange = document.createRange();
}
return this._handyReadyRange;
}
private static _detachRange(range: Range, endNode: HTMLElement): void {
// Move range out of the span node, IE doesn't like having many ranges in
// the same spot and will act badly for lines containing dashes ('-')
range.selectNodeContents(endNode);
}
private static _readClientRects(startElement: Node, startOffset: number, endElement: Node, endOffset: number, endNode: HTMLElement): ClientRectList | DOMRectList | null {
const range = this._createRange();
try {
range.setStart(startElement, startOffset);
range.setEnd(endElement, endOffset);
return range.getClientRects();
} catch (e) {
// This is life ...
return null;
} finally {
this._detachRange(range, endNode);
}
}
private static _mergeAdjacentRanges(ranges: FloatHorizontalRange[]): HorizontalRange[] {
if (ranges.length === 1) {
// There is nothing to merge
return [new HorizontalRange(ranges[0].left, ranges[0].width)];
}
ranges.sort(FloatHorizontalRange.compare);
let result: HorizontalRange[] = [], resultLen = 0;
let prevLeft = ranges[0].left;
let prevWidth = ranges[0].width;
for (let i = 1, len = ranges.length; i < len; i++) {
const range = ranges[i];
const myLeft = range.left;
const myWidth = range.width;
if (prevLeft + prevWidth + 0.9 /* account for browser's rounding errors*/ >= myLeft) {
prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft);
} else {
result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);
prevLeft = myLeft;
prevWidth = myWidth;
}
}
result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);
return result;
}
private static _createHorizontalRangesFromClientRects(clientRects: ClientRectList | DOMRectList | null, clientRectDeltaLeft: number): HorizontalRange[] | null {
if (!clientRects || clientRects.length === 0) {
return null;
}
// We go through FloatHorizontalRange because it has been observed in bi-di text
// that the clientRects are not coming in sorted from the browser
const result: FloatHorizontalRange[] = [];
for (let i = 0, len = clientRects.length; i < len; i++) {
const clientRect = clientRects[i];
result[i] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width);
}
return this._mergeAdjacentRanges(result);
}
public static readHorizontalRanges(domNode: HTMLElement, startChildIndex: number, startOffset: number, endChildIndex: number, endOffset: number, clientRectDeltaLeft: number, endNode: HTMLElement): HorizontalRange[] | null {
// Panic check
const min = 0;
const max = domNode.children.length - 1;
if (min > max) {
return null;
}
startChildIndex = Math.min(max, Math.max(min, startChildIndex));
endChildIndex = Math.min(max, Math.max(min, endChildIndex));
if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0) {
// We must find the position at the beginning of a <span>
// To cover cases of empty <span>s, aboid using a range and use the <span>'s bounding box
const clientRects = domNode.children[startChildIndex].getClientRects();
return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
}
// If crossing over to a span only to select offset 0, then use the previous span's maximum offset
// Chrome is buggy and doesn't handle 0 offsets well sometimes.
if (startChildIndex !== endChildIndex) {
if (endChildIndex > 0 && endOffset === 0) {
endChildIndex--;
endOffset = Constants.MAX_SAFE_SMALL_INTEGER;
}
}
let startElement = domNode.children[startChildIndex].firstChild;
let endElement = domNode.children[endChildIndex].firstChild;
if (!startElement || !endElement) {
// When having an empty <span> (without any text content), try to move to the previous <span>
if (!startElement && startOffset === 0 && startChildIndex > 0) {
startElement = domNode.children[startChildIndex - 1].firstChild;
startOffset = Constants.MAX_SAFE_SMALL_INTEGER;
}
if (!endElement && endOffset === 0 && endChildIndex > 0) {
endElement = domNode.children[endChildIndex - 1].firstChild;
endOffset = Constants.MAX_SAFE_SMALL_INTEGER;
}
}
if (!startElement || !endElement) {
return null;
}
startOffset = Math.min(startElement.textContent!.length, Math.max(0, startOffset));
endOffset = Math.min(endElement.textContent!.length, Math.max(0, endOffset));
const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode);
return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
}
}
| src/vs/editor/browser/viewParts/lines/rangeUtil.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017550092888996005,
0.0001713947276584804,
0.00016697710088919848,
0.0001708613708615303,
0.0000022731589979230193
] |
{
"id": 10,
"code_window": [
"\n",
"\t\t\tresolve(value === '1');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\tsetAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {\n",
"\t\tsuper.setAccessibilitySupport(accessibilitySupport);\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn value === '1';\n"
],
"file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts",
"type": "replace",
"edit_start_line_idx": 58
} | {
"displayName": "Quiet Light Theme",
"description": "Quiet light theme for Visual Studio Code"
} | extensions/theme-quietlight/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017365736130159348,
0.00017365736130159348,
0.00017365736130159348,
0.00017365736130159348,
0
] |
{
"id": 11,
"code_window": [
"\treturn undefined;\n",
"}\n",
"\n",
"async function readWindowsCaCertificates() {\n",
"\tconst winCA = await new Promise<any>((resolve, reject) => {\n",
"\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n",
"\t});\n",
"\n",
"\tlet ders: any[] = [];\n",
"\tconst store = winCA();\n",
"\ttry {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// @ts-ignore Windows only\n",
"\tconst winCA = await import('vscode-windows-ca-certs');\n"
],
"file_path": "src/vs/workbench/services/extensions/node/proxyResolver.ts",
"type": "replace",
"edit_start_line_idx": 495
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility';
import { isWindows, isLinux } from 'vs/base/common/platform';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Registry } from 'vs/platform/registry/common/platform';
import { AccessibilityService } from 'vs/platform/accessibility/common/accessibilityService';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService';
interface AccessibilityMetrics {
enabled: boolean;
}
type AccessibilityMetricsClassification = {
enabled: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService {
declare readonly _serviceBrand: undefined;
private didSendTelemetry = false;
constructor(
@IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService,
@IContextKeyService contextKeyService: IContextKeyService,
@IConfigurationService configurationService: IConfigurationService,
@ITelemetryService private readonly _telemetryService: ITelemetryService
) {
super(contextKeyService, configurationService);
this.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);
}
alwaysUnderlineAccessKeys(): Promise<boolean> {
if (!isWindows) {
return Promise.resolve(false);
}
return new Promise<boolean>(async (resolve) => {
const Registry = await import('vscode-windows-registry');
let value;
try {
value = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On');
} catch {
resolve(false);
}
resolve(value === '1');
});
}
setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void {
super.setAccessibilitySupport(accessibilitySupport);
if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) {
this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true });
this.didSendTelemetry = true;
}
}
}
registerSingleton(IAccessibilityService, NativeAccessibilityService, true);
// On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings
class LinuxAccessibilityContribution implements IWorkbenchContribution {
constructor(
@IJSONEditingService jsonEditingService: IJSONEditingService,
@IAccessibilityService accessibilityService: AccessibilityService,
@IEnvironmentService environmentService: IEnvironmentService
) {
const forceRendererAccessibility = () => {
if (accessibilityService.isScreenReaderOptimized()) {
jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true);
}
};
forceRendererAccessibility();
accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility);
}
}
if (isLinux) {
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready);
}
| src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts | 1 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.000240058041526936,
0.00018052736413665116,
0.000167965074069798,
0.0001748295035213232,
0.000020080415197298862
] |
{
"id": 11,
"code_window": [
"\treturn undefined;\n",
"}\n",
"\n",
"async function readWindowsCaCertificates() {\n",
"\tconst winCA = await new Promise<any>((resolve, reject) => {\n",
"\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n",
"\t});\n",
"\n",
"\tlet ders: any[] = [];\n",
"\tconst store = winCA();\n",
"\ttry {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// @ts-ignore Windows only\n",
"\tconst winCA = await import('vscode-windows-ca-certs');\n"
],
"file_path": "src/vs/workbench/services/extensions/node/proxyResolver.ts",
"type": "replace",
"edit_start_line_idx": 495
} | {
this.foo = 9;
} | extensions/typescript-basics/test/colorize-fixtures/test-this.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017564372683409601,
0.00017564372683409601,
0.00017564372683409601,
0.00017564372683409601,
0
] |
{
"id": 11,
"code_window": [
"\treturn undefined;\n",
"}\n",
"\n",
"async function readWindowsCaCertificates() {\n",
"\tconst winCA = await new Promise<any>((resolve, reject) => {\n",
"\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n",
"\t});\n",
"\n",
"\tlet ders: any[] = [];\n",
"\tconst store = winCA();\n",
"\ttry {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// @ts-ignore Windows only\n",
"\tconst winCA = await import('vscode-windows-ca-certs');\n"
],
"file_path": "src/vs/workbench/services/extensions/node/proxyResolver.ts",
"type": "replace",
"edit_start_line_idx": 495
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IAnchor } from 'vs/base/browser/ui/contextview/contextview';
import { IAction, Separator, SubmenuAction } from 'vs/base/common/actions';
import { KeyCode, KeyMod, ResolvedKeybinding } from 'vs/base/common/keyCodes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { EditorAction, ServicesAccessor, registerEditorAction, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { IEditorContribution, ScrollType } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { IMenuService, MenuId, SubmenuItemAction } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ITextModel } from 'vs/editor/common/model';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { ActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems';
export class ContextMenuController implements IEditorContribution {
public static readonly ID = 'editor.contrib.contextmenu';
public static get(editor: ICodeEditor): ContextMenuController {
return editor.getContribution<ContextMenuController>(ContextMenuController.ID);
}
private readonly _toDispose = new DisposableStore();
private _contextMenuIsBeingShownCount: number = 0;
private readonly _editor: ICodeEditor;
constructor(
editor: ICodeEditor,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IContextViewService private readonly _contextViewService: IContextViewService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IMenuService private readonly _menuService: IMenuService
) {
this._editor = editor;
this._toDispose.add(this._editor.onContextMenu((e: IEditorMouseEvent) => this._onContextMenu(e)));
this._toDispose.add(this._editor.onMouseWheel((e: IMouseWheelEvent) => {
if (this._contextMenuIsBeingShownCount > 0) {
const view = this._contextViewService.getContextViewElement();
const target = e.srcElement as HTMLElement;
// Event triggers on shadow root host first
// Check if the context view is under this host before hiding it #103169
if (!(target.shadowRoot && dom.getShadowRoot(view) === target.shadowRoot)) {
this._contextViewService.hideContextView();
}
}
}));
this._toDispose.add(this._editor.onKeyDown((e: IKeyboardEvent) => {
if (e.keyCode === KeyCode.ContextMenu) {
// Chrome is funny like that
e.preventDefault();
e.stopPropagation();
this.showContextMenu();
}
}));
}
private _onContextMenu(e: IEditorMouseEvent): void {
if (!this._editor.hasModel()) {
return;
}
if (!this._editor.getOption(EditorOption.contextmenu)) {
this._editor.focus();
// Ensure the cursor is at the position of the mouse click
if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) {
this._editor.setPosition(e.target.position);
}
return; // Context menu is turned off through configuration
}
if (e.target.type === MouseTargetType.OVERLAY_WIDGET) {
return; // allow native menu on widgets to support right click on input field for example in find
}
e.event.preventDefault();
if (e.target.type !== MouseTargetType.CONTENT_TEXT && e.target.type !== MouseTargetType.CONTENT_EMPTY && e.target.type !== MouseTargetType.TEXTAREA) {
return; // only support mouse click into text or native context menu key for now
}
// Ensure the editor gets focus if it hasn't, so the right events are being sent to other contributions
this._editor.focus();
// Ensure the cursor is at the position of the mouse click
if (e.target.position) {
let hasSelectionAtPosition = false;
for (const selection of this._editor.getSelections()) {
if (selection.containsPosition(e.target.position)) {
hasSelectionAtPosition = true;
break;
}
}
if (!hasSelectionAtPosition) {
this._editor.setPosition(e.target.position);
}
}
// Unless the user triggerd the context menu through Shift+F10, use the mouse position as menu position
let anchor: IAnchor | null = null;
if (e.target.type !== MouseTargetType.TEXTAREA) {
anchor = { x: e.event.posx - 1, width: 2, y: e.event.posy - 1, height: 2 };
}
// Show the context menu
this.showContextMenu(anchor);
}
public showContextMenu(anchor?: IAnchor | null): void {
if (!this._editor.getOption(EditorOption.contextmenu)) {
return; // Context menu is turned off through configuration
}
if (!this._editor.hasModel()) {
return;
}
if (!this._contextMenuService) {
this._editor.focus();
return; // We need the context menu service to function
}
// Find actions available for menu
const menuActions = this._getMenuActions(this._editor.getModel(), MenuId.EditorContext);
// Show menu if we have actions to show
if (menuActions.length > 0) {
this._doShowContextMenu(menuActions, anchor);
}
}
private _getMenuActions(model: ITextModel, menuId: MenuId): IAction[] {
const result: IAction[] = [];
// get menu groups
const menu = this._menuService.createMenu(menuId, this._contextKeyService);
const groups = menu.getActions({ arg: model.uri });
menu.dispose();
// translate them into other actions
for (let group of groups) {
const [, actions] = group;
let addedItems = 0;
for (const action of actions) {
if (action instanceof SubmenuItemAction) {
const subActions = this._getMenuActions(model, action.item.submenu);
if (subActions.length > 0) {
result.push(new SubmenuAction(action.id, action.label, subActions));
addedItems++;
}
} else {
result.push(action);
addedItems++;
}
}
if (addedItems) {
result.push(new Separator());
}
}
if (result.length) {
result.pop(); // remove last separator
}
return result;
}
private _doShowContextMenu(actions: IAction[], anchor: IAnchor | null = null): void {
if (!this._editor.hasModel()) {
return;
}
// Disable hover
const oldHoverSetting = this._editor.getOption(EditorOption.hover);
this._editor.updateOptions({
hover: {
enabled: false
}
});
if (!anchor) {
// Ensure selection is visible
this._editor.revealPosition(this._editor.getPosition(), ScrollType.Immediate);
this._editor.render();
const cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
// Translate to absolute editor position
const editorCoords = dom.getDomNodePagePosition(this._editor.getDomNode());
const posx = editorCoords.left + cursorCoords.left;
const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
anchor = { x: posx, y: posy };
}
// Show menu
this._contextMenuIsBeingShownCount++;
this._contextMenuService.showContextMenu({
domForShadowRoot: this._editor.getDomNode(),
getAnchor: () => anchor!,
getActions: () => actions,
getActionViewItem: (action) => {
const keybinding = this._keybindingFor(action);
if (keybinding) {
return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
}
const customActionViewItem = <any>action;
if (typeof customActionViewItem.getActionViewItem === 'function') {
return customActionViewItem.getActionViewItem();
}
return new ActionViewItem(action, action, { icon: true, label: true, isMenu: true });
},
getKeyBinding: (action): ResolvedKeybinding | undefined => {
return this._keybindingFor(action);
},
onHide: (wasCancelled: boolean) => {
this._contextMenuIsBeingShownCount--;
this._editor.focus();
this._editor.updateOptions({
hover: oldHoverSetting
});
}
});
}
private _keybindingFor(action: IAction): ResolvedKeybinding | undefined {
return this._keybindingService.lookupKeybinding(action.id);
}
public dispose(): void {
if (this._contextMenuIsBeingShownCount > 0) {
this._contextViewService.hideContextView();
}
this._toDispose.dispose();
}
}
class ShowContextMenu extends EditorAction {
constructor() {
super({
id: 'editor.action.showContextMenu',
label: nls.localize('action.showContextMenu.label', "Show Editor Context Menu"),
alias: 'Show Editor Context Menu',
precondition: undefined,
kbOpts: {
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.Shift | KeyCode.F10,
weight: KeybindingWeight.EditorContrib
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let contribution = ContextMenuController.get(editor);
contribution.showContextMenu();
}
}
registerEditorContribution(ContextMenuController.ID, ContextMenuController);
registerEditorAction(ShowContextMenu);
| src/vs/editor/contrib/contextmenu/contextmenu.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.0001794461568351835,
0.00017549954645801336,
0.00016847594815772027,
0.0001760566810844466,
0.00000214111832974595
] |
{
"id": 11,
"code_window": [
"\treturn undefined;\n",
"}\n",
"\n",
"async function readWindowsCaCertificates() {\n",
"\tconst winCA = await new Promise<any>((resolve, reject) => {\n",
"\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n",
"\t});\n",
"\n",
"\tlet ders: any[] = [];\n",
"\tconst store = winCA();\n",
"\ttry {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// @ts-ignore Windows only\n",
"\tconst winCA = await import('vscode-windows-ca-certs');\n"
],
"file_path": "src/vs/workbench/services/extensions/node/proxyResolver.ts",
"type": "replace",
"edit_start_line_idx": 495
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { WrappingIndent, EditorOptions } from 'vs/editor/common/config/editorOptions';
import { MonospaceLineBreaksComputerFactory } from 'vs/editor/common/viewModel/monospaceLineBreaksComputer';
import { ILineBreaksComputerFactory, LineBreakData } from 'vs/editor/common/viewModel/splitLinesCollection';
import { FontInfo } from 'vs/editor/common/config/fontInfo';
function parseAnnotatedText(annotatedText: string): { text: string; indices: number[]; } {
let text = '';
let currentLineIndex = 0;
let indices: number[] = [];
for (let i = 0, len = annotatedText.length; i < len; i++) {
if (annotatedText.charAt(i) === '|') {
currentLineIndex++;
} else {
text += annotatedText.charAt(i);
indices[text.length - 1] = currentLineIndex;
}
}
return { text: text, indices: indices };
}
function toAnnotatedText(text: string, lineBreakData: LineBreakData | null): string {
// Insert line break markers again, according to algorithm
let actualAnnotatedText = '';
if (lineBreakData) {
let previousLineIndex = 0;
for (let i = 0, len = text.length; i < len; i++) {
let r = LineBreakData.getOutputPositionOfInputOffset(lineBreakData.breakOffsets, i);
if (previousLineIndex !== r.outputLineIndex) {
previousLineIndex = r.outputLineIndex;
actualAnnotatedText += '|';
}
actualAnnotatedText += text.charAt(i);
}
} else {
// No wrapping
actualAnnotatedText = text;
}
return actualAnnotatedText;
}
function getLineBreakData(factory: ILineBreaksComputerFactory, tabSize: number, breakAfter: number, columnsForFullWidthChar: number, wrappingIndent: WrappingIndent, text: string, previousLineBreakData: LineBreakData | null): LineBreakData | null {
const fontInfo = new FontInfo({
zoomLevel: 0,
fontFamily: 'testFontFamily',
fontWeight: 'normal',
fontSize: 14,
fontFeatureSettings: '',
lineHeight: 19,
letterSpacing: 0,
isMonospace: true,
typicalHalfwidthCharacterWidth: 7,
typicalFullwidthCharacterWidth: 14,
canUseHalfwidthRightwardsArrow: true,
spaceWidth: 7,
middotWidth: 7,
wsmiddotWidth: 7,
maxDigitWidth: 7
}, false);
const lineBreaksComputer = factory.createLineBreaksComputer(fontInfo, tabSize, breakAfter, wrappingIndent);
const previousLineBreakDataClone = previousLineBreakData ? new LineBreakData(previousLineBreakData.breakOffsets.slice(0), previousLineBreakData.breakOffsetsVisibleColumn.slice(0), previousLineBreakData.wrappedTextIndentLength) : null;
lineBreaksComputer.addRequest(text, previousLineBreakDataClone);
return lineBreaksComputer.finalize()[0];
}
function assertLineBreaks(factory: ILineBreaksComputerFactory, tabSize: number, breakAfter: number, annotatedText: string, wrappingIndent = WrappingIndent.None): LineBreakData | null {
// Create version of `annotatedText` with line break markers removed
const text = parseAnnotatedText(annotatedText).text;
const lineBreakData = getLineBreakData(factory, tabSize, breakAfter, 2, wrappingIndent, text, null);
const actualAnnotatedText = toAnnotatedText(text, lineBreakData);
assert.equal(actualAnnotatedText, annotatedText);
return lineBreakData;
}
suite('Editor ViewModel - MonospaceLineBreaksComputer', () => {
test('MonospaceLineBreaksComputer', () => {
let factory = new MonospaceLineBreaksComputerFactory('(', '\t).');
// Empty string
assertLineBreaks(factory, 4, 5, '');
// No wrapping if not necessary
assertLineBreaks(factory, 4, 5, 'aaa');
assertLineBreaks(factory, 4, 5, 'aaaaa');
assertLineBreaks(factory, 4, -1, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
// Acts like hard wrapping if no char found
assertLineBreaks(factory, 4, 5, 'aaaaa|a');
// Honors wrapping character
assertLineBreaks(factory, 4, 5, 'aaaaa|.');
assertLineBreaks(factory, 4, 5, 'aaaaa|a.|aaa.|aa');
assertLineBreaks(factory, 4, 5, 'aaaaa|a..|aaa.|aa');
assertLineBreaks(factory, 4, 5, 'aaaaa|a...|aaa.|aa');
assertLineBreaks(factory, 4, 5, 'aaaaa|a....|aaa.|aa');
// Honors tabs when computing wrapping position
assertLineBreaks(factory, 4, 5, '\t');
assertLineBreaks(factory, 4, 5, '\t|aaa');
assertLineBreaks(factory, 4, 5, '\t|a\t|aa');
assertLineBreaks(factory, 4, 5, 'aa\ta');
assertLineBreaks(factory, 4, 5, 'aa\t|aa');
// Honors wrapping before characters (& gives it priority)
assertLineBreaks(factory, 4, 5, 'aaa.|aa');
assertLineBreaks(factory, 4, 5, 'aaa(.|aa');
// Honors wrapping after characters (& gives it priority)
assertLineBreaks(factory, 4, 5, 'aaa))|).aaa');
assertLineBreaks(factory, 4, 5, 'aaa))|).|aaaa');
assertLineBreaks(factory, 4, 5, 'aaa)|().|aaa');
assertLineBreaks(factory, 4, 5, 'aaa(|().|aaa');
assertLineBreaks(factory, 4, 5, 'aa.(|().|aaa');
assertLineBreaks(factory, 4, 5, 'aa.(.|).aaa');
});
function assertIncrementalLineBreaks(factory: ILineBreaksComputerFactory, text: string, tabSize: number, breakAfter1: number, annotatedText1: string, breakAfter2: number, annotatedText2: string, wrappingIndent = WrappingIndent.None): void {
// sanity check the test
assert.equal(text, parseAnnotatedText(annotatedText1).text);
assert.equal(text, parseAnnotatedText(annotatedText2).text);
// check that the direct mapping is ok for 1
const directLineBreakData1 = getLineBreakData(factory, tabSize, breakAfter1, 2, wrappingIndent, text, null);
assert.equal(toAnnotatedText(text, directLineBreakData1), annotatedText1);
// check that the direct mapping is ok for 2
const directLineBreakData2 = getLineBreakData(factory, tabSize, breakAfter2, 2, wrappingIndent, text, null);
assert.equal(toAnnotatedText(text, directLineBreakData2), annotatedText2);
// check that going from 1 to 2 is ok
const lineBreakData2from1 = getLineBreakData(factory, tabSize, breakAfter2, 2, wrappingIndent, text, directLineBreakData1);
assert.equal(toAnnotatedText(text, lineBreakData2from1), annotatedText2);
assert.deepEqual(lineBreakData2from1, directLineBreakData2);
// check that going from 2 to 1 is ok
const lineBreakData1from2 = getLineBreakData(factory, tabSize, breakAfter1, 2, wrappingIndent, text, directLineBreakData2);
assert.equal(toAnnotatedText(text, lineBreakData1from2), annotatedText1);
assert.deepEqual(lineBreakData1from2, directLineBreakData1);
}
test('MonospaceLineBreaksComputer incremental 1', () => {
const factory = new MonospaceLineBreaksComputerFactory(EditorOptions.wordWrapBreakBeforeCharacters.defaultValue, EditorOptions.wordWrapBreakAfterCharacters.defaultValue);
assertIncrementalLineBreaks(
factory, 'just some text and more', 4,
10, 'just some |text and |more',
15, 'just some text |and more'
);
assertIncrementalLineBreaks(
factory, 'Cu scripserit suscipiantur eos, in affert pericula contentiones sed, cetero sanctus et pro. Ius vidit magna regione te, sit ei elaboraret liberavisse. Mundi verear eu mea, eam vero scriptorem in, vix in menandri assueverit. Natum definiebas cu vim. Vim doming vocibus efficiantur id. In indoctum deseruisse voluptatum vim, ad debitis verterem sed.', 4,
47, 'Cu scripserit suscipiantur eos, in affert |pericula contentiones sed, cetero sanctus et |pro. Ius vidit magna regione te, sit ei |elaboraret liberavisse. Mundi verear eu mea, |eam vero scriptorem in, vix in menandri |assueverit. Natum definiebas cu vim. Vim |doming vocibus efficiantur id. In indoctum |deseruisse voluptatum vim, ad debitis verterem |sed.',
142, 'Cu scripserit suscipiantur eos, in affert pericula contentiones sed, cetero sanctus et pro. Ius vidit magna regione te, sit ei elaboraret |liberavisse. Mundi verear eu mea, eam vero scriptorem in, vix in menandri assueverit. Natum definiebas cu vim. Vim doming vocibus efficiantur |id. In indoctum deseruisse voluptatum vim, ad debitis verterem sed.',
);
assertIncrementalLineBreaks(
factory, 'An his legere persecuti, oblique delicata efficiantur ex vix, vel at graecis officiis maluisset. Et per impedit voluptua, usu discere maiorum at. Ut assum ornatus temporibus vis, an sea melius pericula. Ea dicunt oblique phaedrum nam, eu duo movet nobis. His melius facilis eu, vim malorum temporibus ne. Nec no sale regione, meliore civibus placerat id eam. Mea alii fabulas definitionem te, agam volutpat ad vis, et per bonorum nonumes repudiandae.', 4,
57, 'An his legere persecuti, oblique delicata efficiantur ex |vix, vel at graecis officiis maluisset. Et per impedit |voluptua, usu discere maiorum at. Ut assum ornatus |temporibus vis, an sea melius pericula. Ea dicunt |oblique phaedrum nam, eu duo movet nobis. His melius |facilis eu, vim malorum temporibus ne. Nec no sale |regione, meliore civibus placerat id eam. Mea alii |fabulas definitionem te, agam volutpat ad vis, et per |bonorum nonumes repudiandae.',
58, 'An his legere persecuti, oblique delicata efficiantur ex |vix, vel at graecis officiis maluisset. Et per impedit |voluptua, usu discere maiorum at. Ut assum ornatus |temporibus vis, an sea melius pericula. Ea dicunt oblique |phaedrum nam, eu duo movet nobis. His melius facilis eu, |vim malorum temporibus ne. Nec no sale regione, meliore |civibus placerat id eam. Mea alii fabulas definitionem |te, agam volutpat ad vis, et per bonorum nonumes |repudiandae.'
);
assertIncrementalLineBreaks(
factory, '\t\t"owner": "vscode",', 4,
14, '\t\t"owner|": |"vscod|e",',
16, '\t\t"owner":| |"vscode"|,',
WrappingIndent.Same
);
assertIncrementalLineBreaks(
factory, '🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇&👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬', 4,
51, '🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇&|👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬',
50, '🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇|&|👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬',
WrappingIndent.Same
);
assertIncrementalLineBreaks(
factory, '🐇👬&🌞🌖', 4,
5, '🐇👬&|🌞🌖',
4, '🐇👬|&|🌞🌖',
WrappingIndent.Same
);
assertIncrementalLineBreaks(
factory, '\t\tfunc(\'🌞🏇🍼🌞🏇🍼🐇&👬🌖🌞👬🌖🌞🏇🍼🐇👬\', WrappingIndent.Same);', 4,
26, '\t\tfunc|(\'🌞🏇🍼🌞🏇🍼🐇&|👬🌖🌞👬🌖🌞🏇🍼🐇|👬\', |WrappingIndent.|Same);',
27, '\t\tfunc|(\'🌞🏇🍼🌞🏇🍼🐇&|👬🌖🌞👬🌖🌞🏇🍼🐇|👬\', |WrappingIndent.|Same);',
WrappingIndent.Same
);
assertIncrementalLineBreaks(
factory, 'factory, "xtxtfunc(x"🌞🏇🍼🌞🏇🍼🐇&👬🌖🌞👬🌖🌞🏇🍼🐇👬x"', 4,
16, 'factory, |"xtxtfunc|(x"🌞🏇🍼🌞🏇🍼|🐇&|👬🌖🌞👬🌖🌞🏇🍼|🐇👬x"',
17, 'factory, |"xtxtfunc|(x"🌞🏇🍼🌞🏇🍼🐇|&👬🌖🌞👬🌖🌞🏇🍼|🐇👬x"',
WrappingIndent.Same
);
});
test('issue #95686: CRITICAL: loop forever on the monospaceLineBreaksComputer', () => {
const factory = new MonospaceLineBreaksComputerFactory(EditorOptions.wordWrapBreakBeforeCharacters.defaultValue, EditorOptions.wordWrapBreakAfterCharacters.defaultValue);
assertIncrementalLineBreaks(
factory,
' <tr dmx-class:table-danger="(alt <= 50)" dmx-class:table-warning="(alt <= 200)" dmx-class:table-primary="(alt <= 400)" dmx-class:table-info="(alt <= 800)" dmx-class:table-success="(alt >= 400)">',
4,
179, ' <tr dmx-class:table-danger="(alt <= 50)" dmx-class:table-warning="(alt <= 200)" dmx-class:table-primary="(alt <= 400)" dmx-class:table-info="(alt <= 800)" |dmx-class:table-success="(alt >= 400)">',
1, ' | | | | | |<|t|r| |d|m|x|-|c|l|a|s|s|:|t|a|b|l|e|-|d|a|n|g|e|r|=|"|(|a|l|t| |<|=| |5|0|)|"| |d|m|x|-|c|l|a|s|s|:|t|a|b|l|e|-|w|a|r|n|i|n|g|=|"|(|a|l|t| |<|=| |2|0|0|)|"| |d|m|x|-|c|l|a|s|s|:|t|a|b|l|e|-|p|r|i|m|a|r|y|=|"|(|a|l|t| |<|=| |4|0|0|)|"| |d|m|x|-|c|l|a|s|s|:|t|a|b|l|e|-|i|n|f|o|=|"|(|a|l|t| |<|=| |8|0|0|)|"| |d|m|x|-|c|l|a|s|s|:|t|a|b|l|e|-|s|u|c|c|e|s|s|=|"|(|a|l|t| |>|=| |4|0|0|)|"|>',
WrappingIndent.Same
);
});
test('MonospaceLineBreaksComputer - CJK and Kinsoku Shori', () => {
let factory = new MonospaceLineBreaksComputerFactory('(', '\t)');
assertLineBreaks(factory, 4, 5, 'aa \u5b89|\u5b89');
assertLineBreaks(factory, 4, 5, '\u3042 \u5b89|\u5b89');
assertLineBreaks(factory, 4, 5, '\u3042\u3042|\u5b89\u5b89');
assertLineBreaks(factory, 4, 5, 'aa |\u5b89)\u5b89|\u5b89');
assertLineBreaks(factory, 4, 5, 'aa \u3042|\u5b89\u3042)|\u5b89');
assertLineBreaks(factory, 4, 5, 'aa |(\u5b89aa|\u5b89');
});
test('MonospaceLineBreaksComputer - WrappingIndent.Same', () => {
let factory = new MonospaceLineBreaksComputerFactory('', '\t ');
assertLineBreaks(factory, 4, 38, ' *123456789012345678901234567890123456|7890', WrappingIndent.Same);
});
test('issue #16332: Scroll bar overlaying on top of text', () => {
let factory = new MonospaceLineBreaksComputerFactory('', '\t ');
assertLineBreaks(factory, 4, 24, 'a/ very/long/line/of/tex|t/that/expands/beyon|d/your/typical/line/|of/code/', WrappingIndent.Indent);
});
test('issue #35162: wrappingIndent not consistently working', () => {
let factory = new MonospaceLineBreaksComputerFactory('', '\t ');
let mapper = assertLineBreaks(factory, 4, 24, ' t h i s |i s |a l |o n |g l |i n |e', WrappingIndent.Indent);
assert.equal(mapper!.wrappedTextIndentLength, ' '.length);
});
test('issue #75494: surrogate pairs', () => {
let factory = new MonospaceLineBreaksComputerFactory('\t', ' ');
assertLineBreaks(factory, 4, 49, '🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼|🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼🐇👬🌖🌞🏇🍼|🐇👬', WrappingIndent.Same);
});
test('issue #75494: surrogate pairs overrun 1', () => {
const factory = new MonospaceLineBreaksComputerFactory(EditorOptions.wordWrapBreakBeforeCharacters.defaultValue, EditorOptions.wordWrapBreakAfterCharacters.defaultValue);
assertLineBreaks(factory, 4, 4, '🐇👬|&|🌞🌖', WrappingIndent.Same);
});
test('issue #75494: surrogate pairs overrun 2', () => {
const factory = new MonospaceLineBreaksComputerFactory(EditorOptions.wordWrapBreakBeforeCharacters.defaultValue, EditorOptions.wordWrapBreakAfterCharacters.defaultValue);
assertLineBreaks(factory, 4, 17, 'factory, |"xtxtfunc|(x"🌞🏇🍼🌞🏇🍼🐇|&👬🌖🌞👬🌖🌞🏇🍼|🐇👬x"', WrappingIndent.Same);
});
test('MonospaceLineBreaksComputer - WrappingIndent.DeepIndent', () => {
let factory = new MonospaceLineBreaksComputerFactory('', '\t ');
let mapper = assertLineBreaks(factory, 4, 26, ' W e A r e T e s t |i n g D e |e p I n d |e n t a t |i o n', WrappingIndent.DeepIndent);
assert.equal(mapper!.wrappedTextIndentLength, ' '.length);
});
test('issue #33366: Word wrap algorithm behaves differently around punctuation', () => {
const factory = new MonospaceLineBreaksComputerFactory(EditorOptions.wordWrapBreakBeforeCharacters.defaultValue, EditorOptions.wordWrapBreakAfterCharacters.defaultValue);
assertLineBreaks(factory, 4, 23, 'this is a line of |text, text that sits |on a line', WrappingIndent.Same);
});
});
| src/vs/editor/test/common/viewModel/monospaceLineBreaksComputer.test.ts | 0 | https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb | [
0.00017954918439500034,
0.00017506134463474154,
0.0001659338449826464,
0.00017591995128896087,
0.000003274900791438995
] |
{
"id": 0,
"code_window": [
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/expr\"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/eval\"\n",
"\tngmodels \"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "add",
"edit_start_line_idx": 12
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.04281631112098694,
0.001229630084708333,
0.00016142308595590293,
0.00017015085904859006,
0.00635900953784585
] |
{
"id": 0,
"code_window": [
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/expr\"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/eval\"\n",
"\tngmodels \"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "add",
"edit_start_line_idx": 12
} | package sqlstore
import (
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/util/errutil"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/securejsondata"
"github.com/grafana/grafana/pkg/infra/metrics"
)
func init() {
bus.AddHandler("sql", GetDataSources)
bus.AddHandler("sql", GetDataSourcesByType)
bus.AddHandler("sql", GetDataSource)
bus.AddHandler("sql", AddDataSource)
bus.AddHandler("sql", DeleteDataSource)
bus.AddHandler("sql", UpdateDataSource)
bus.AddHandler("sql", GetDefaultDataSource)
}
// GetDataSource returns a datasource by org_id and either uid (preferred), id, or name.
// Zero values (0, or "") should be used for the parameters that will not be queried.
func (ss *SQLStore) GetDataSource(uid string, id int64, name string, orgID int64) (*models.DataSource, error) {
query := &models.GetDataSourceQuery{
Id: id,
Uid: uid,
Name: name,
OrgId: orgID,
}
if err := GetDataSource(query); err != nil {
return nil, err
}
return query.Result, nil
}
// GetDataSource adds a datasource to the query model by querying by org_id as well as
// either uid (preferred), id, or name and is added to the bus.
func GetDataSource(query *models.GetDataSourceQuery) error {
metrics.MDBDataSourceQueryByID.Inc()
if query.OrgId == 0 || (query.Id == 0 && len(query.Name) == 0 && len(query.Uid) == 0) {
return models.ErrDataSourceIdentifierNotSet
}
datasource := models.DataSource{Name: query.Name, OrgId: query.OrgId, Id: query.Id, Uid: query.Uid}
has, err := x.Get(&datasource)
if err != nil {
sqlog.Error("Failed getting data source", "err", err, "uid", query.Uid, "id", query.Id, "name", query.Name, "orgId", query.OrgId)
return err
} else if !has {
return models.ErrDataSourceNotFound
}
query.Result = &datasource
return nil
}
func GetDataSources(query *models.GetDataSourcesQuery) error {
var sess *xorm.Session
if query.DataSourceLimit <= 0 {
sess = x.Where("org_id=?", query.OrgId).Asc("name")
} else {
sess = x.Limit(query.DataSourceLimit, 0).Where("org_id=?", query.OrgId).Asc("name")
}
query.Result = make([]*models.DataSource, 0)
return sess.Find(&query.Result)
}
// GetDataSourcesByType returns all datasources for a given type or an error if the specified type is an empty string
func GetDataSourcesByType(query *models.GetDataSourcesByTypeQuery) error {
if query.Type == "" {
return fmt.Errorf("datasource type cannot be empty")
}
query.Result = make([]*models.DataSource, 0)
return x.Where("type=?", query.Type).Asc("id").Find(&query.Result)
}
// GetDefaultDataSource is used to get the default datasource of organization
func GetDefaultDataSource(query *models.GetDefaultDataSourceQuery) error {
datasource := models.DataSource{}
exists, err := x.Where("org_id=? AND is_default=?", query.OrgId, true).Get(&datasource)
if !exists {
return models.ErrDataSourceNotFound
}
query.Result = &datasource
return err
}
// DeleteDataSource deletes a datasource by org_id and either uid (preferred), id, or name.
// Zero values (0, or "") should be used for the parameters that will not be queried.
func (ss *SQLStore) DeleteDataSource(uid string, id int64, name string, orgID int64) (int64, error) {
cmd := &models.DeleteDataSourceCommand{
ID: id,
UID: uid,
Name: name,
OrgID: orgID,
}
if err := DeleteDataSource(cmd); err != nil {
return 0, err
}
return cmd.DeletedDatasourcesCount, nil
}
// DeleteDataSource removes a datasource by org_id as well as either uid (preferred), id, or name
// and is added to the bus.
func DeleteDataSource(cmd *models.DeleteDataSourceCommand) error {
params := make([]interface{}, 0)
makeQuery := func(sql string, p ...interface{}) {
params = append(params, sql)
params = append(params, p...)
}
switch {
case cmd.OrgID == 0:
return models.ErrDataSourceIdentifierNotSet
case cmd.UID != "":
makeQuery("DELETE FROM data_source WHERE uid=? and org_id=?", cmd.UID, cmd.OrgID)
case cmd.ID != 0:
makeQuery("DELETE FROM data_source WHERE id=? and org_id=?", cmd.ID, cmd.OrgID)
case cmd.Name != "":
makeQuery("DELETE FROM data_source WHERE name=? and org_id=?", cmd.Name, cmd.OrgID)
default:
return models.ErrDataSourceIdentifierNotSet
}
return inTransaction(func(sess *DBSession) error {
result, err := sess.Exec(params...)
cmd.DeletedDatasourcesCount, _ = result.RowsAffected()
return err
})
}
func AddDataSource(cmd *models.AddDataSourceCommand) error {
return inTransaction(func(sess *DBSession) error {
existing := models.DataSource{OrgId: cmd.OrgId, Name: cmd.Name}
has, _ := sess.Get(&existing)
if has {
return models.ErrDataSourceNameExists
}
if cmd.JsonData == nil {
cmd.JsonData = simplejson.New()
}
if cmd.Uid == "" {
uid, err := generateNewDatasourceUid(sess, cmd.OrgId)
if err != nil {
return errutil.Wrapf(err, "Failed to generate UID for datasource %q", cmd.Name)
}
cmd.Uid = uid
}
ds := &models.DataSource{
OrgId: cmd.OrgId,
Name: cmd.Name,
Type: cmd.Type,
Access: cmd.Access,
Url: cmd.Url,
User: cmd.User,
Password: cmd.Password,
Database: cmd.Database,
IsDefault: cmd.IsDefault,
BasicAuth: cmd.BasicAuth,
BasicAuthUser: cmd.BasicAuthUser,
BasicAuthPassword: cmd.BasicAuthPassword,
WithCredentials: cmd.WithCredentials,
JsonData: cmd.JsonData,
SecureJsonData: securejsondata.GetEncryptedJsonData(cmd.SecureJsonData),
Created: time.Now(),
Updated: time.Now(),
Version: 1,
ReadOnly: cmd.ReadOnly,
Uid: cmd.Uid,
}
if _, err := sess.Insert(ds); err != nil {
if dialect.IsUniqueConstraintViolation(err) && strings.Contains(strings.ToLower(dialect.ErrorMessage(err)), "uid") {
return models.ErrDataSourceUidExists
}
return err
}
if err := updateIsDefaultFlag(ds, sess); err != nil {
return err
}
cmd.Result = ds
return nil
})
}
func updateIsDefaultFlag(ds *models.DataSource, sess *DBSession) error {
// Handle is default flag
if ds.IsDefault {
rawSQL := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
if _, err := sess.Exec(rawSQL, false, ds.OrgId, ds.Id); err != nil {
return err
}
}
return nil
}
func UpdateDataSource(cmd *models.UpdateDataSourceCommand) error {
return inTransaction(func(sess *DBSession) error {
if cmd.JsonData == nil {
cmd.JsonData = simplejson.New()
}
ds := &models.DataSource{
Id: cmd.Id,
OrgId: cmd.OrgId,
Name: cmd.Name,
Type: cmd.Type,
Access: cmd.Access,
Url: cmd.Url,
User: cmd.User,
Password: cmd.Password,
Database: cmd.Database,
IsDefault: cmd.IsDefault,
BasicAuth: cmd.BasicAuth,
BasicAuthUser: cmd.BasicAuthUser,
BasicAuthPassword: cmd.BasicAuthPassword,
WithCredentials: cmd.WithCredentials,
JsonData: cmd.JsonData,
SecureJsonData: securejsondata.GetEncryptedJsonData(cmd.SecureJsonData),
Updated: time.Now(),
ReadOnly: cmd.ReadOnly,
Version: cmd.Version + 1,
Uid: cmd.Uid,
}
sess.UseBool("is_default")
sess.UseBool("basic_auth")
sess.UseBool("with_credentials")
sess.UseBool("read_only")
// Make sure password are zeroed out if empty. We do this as we want to migrate passwords from
// plain text fields to SecureJsonData.
sess.MustCols("password")
sess.MustCols("basic_auth_password")
sess.MustCols("user")
var updateSession *xorm.Session
if cmd.Version != 0 {
// the reason we allow cmd.version > db.version is make it possible for people to force
// updates to datasources using the datasource.yaml file without knowing exactly what version
// a datasource have in the db.
updateSession = sess.Where("id=? and org_id=? and version < ?", ds.Id, ds.OrgId, ds.Version)
} else {
updateSession = sess.Where("id=? and org_id=?", ds.Id, ds.OrgId)
}
affected, err := updateSession.Update(ds)
if err != nil {
return err
}
if affected == 0 {
return models.ErrDataSourceUpdatingOldVersion
}
err = updateIsDefaultFlag(ds, sess)
cmd.Result = ds
return err
})
}
func generateNewDatasourceUid(sess *DBSession, orgId int64) (string, error) {
for i := 0; i < 3; i++ {
uid := generateNewUid()
exists, err := sess.Where("org_id=? AND uid=?", orgId, uid).Get(&models.DataSource{})
if err != nil {
return "", err
}
if !exists {
return uid, nil
}
}
return "", models.ErrDataSourceFailedGenerateUniqueUid
}
| pkg/services/sqlstore/datasource.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0077811661176383495,
0.0004568028962239623,
0.00016558564675506204,
0.00016963802045211196,
0.0013546737609431148
] |
{
"id": 0,
"code_window": [
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/expr\"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/eval\"\n",
"\tngmodels \"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "add",
"edit_start_line_idx": 12
} | import { ConfirmModal, useStyles2 } from '@grafana/ui';
import { AlertManagerCortexConfig } from 'app/plugins/datasource/alertmanager/types';
import React, { FC, Fragment, useMemo, useState } from 'react';
import { getAlertTableStyles } from '../../styles/table';
import { CollapseToggle } from '../CollapseToggle';
import { DetailsField } from '../DetailsField';
import { ActionIcon } from '../rules/ActionIcon';
import { ReceiversSection } from './ReceiversSection';
import { makeAMLink } from '../../utils/misc';
import { useDispatch } from 'react-redux';
import { deleteTemplateAction } from '../../state/actions';
interface Props {
config: AlertManagerCortexConfig;
alertManagerName: string;
}
export const TemplatesTable: FC<Props> = ({ config, alertManagerName }) => {
const dispatch = useDispatch();
const [expandedTemplates, setExpandedTemplates] = useState<Record<string, boolean>>({});
const tableStyles = useStyles2(getAlertTableStyles);
const templateRows = useMemo(() => Object.entries(config.template_files), [config]);
const [templateToDelete, setTemplateToDelete] = useState<string>();
const deleteTemplate = () => {
if (templateToDelete) {
dispatch(deleteTemplateAction(templateToDelete, alertManagerName));
}
setTemplateToDelete(undefined);
};
return (
<ReceiversSection
title="Message templates"
description="Templates construct the messages that get sent to the contact points."
addButtonLabel="New template"
addButtonTo={makeAMLink('/alerting/notifications/templates/new', alertManagerName)}
>
<table className={tableStyles.table} data-testid="templates-table">
<colgroup>
<col className={tableStyles.colExpand} />
<col />
<col />
</colgroup>
<thead>
<tr>
<th></th>
<th>Template</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{!templateRows.length && (
<tr className={tableStyles.evenRow}>
<td colSpan={3}>No templates defined.</td>
</tr>
)}
{templateRows.map(([name, content], idx) => {
const isExpanded = !!expandedTemplates[name];
return (
<Fragment key={name}>
<tr key={name} className={idx % 2 === 0 ? tableStyles.evenRow : undefined}>
<td>
<CollapseToggle
isCollapsed={!expandedTemplates[name]}
onToggle={() => setExpandedTemplates({ ...expandedTemplates, [name]: !isExpanded })}
/>
</td>
<td>{name}</td>
<td className={tableStyles.actionsCell}>
<ActionIcon
to={makeAMLink(
`/alerting/notifications/templates/${encodeURIComponent(name)}/edit`,
alertManagerName
)}
tooltip="edit template"
icon="pen"
/>
<ActionIcon onClick={() => setTemplateToDelete(name)} tooltip="delete template" icon="trash-alt" />
</td>
</tr>
{isExpanded && (
<tr className={idx % 2 === 0 ? tableStyles.evenRow : undefined}>
<td></td>
<td colSpan={2}>
<DetailsField label="Description" horizontal={true}>
<pre>{content}</pre>
</DetailsField>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
{!!templateToDelete && (
<ConfirmModal
isOpen={true}
title="Delete template"
body={`Are you sure you want to delete template "${templateToDelete}"?`}
confirmText="Yes, delete"
onConfirm={deleteTemplate}
onDismiss={() => setTemplateToDelete(undefined)}
/>
)}
</ReceiversSection>
);
};
| public/app/features/alerting/unified/components/receivers/TemplatesTable.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001754090772010386,
0.00017063191626220942,
0.0001648273173486814,
0.00017172947991639376,
0.000003568549118426745
] |
{
"id": 0,
"code_window": [
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/expr\"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/eval\"\n",
"\tngmodels \"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "add",
"edit_start_line_idx": 12
} | import { PanelOptionsEditorBuilder, standardEditorsRegistry, StatsPickerConfigSettings } from '@grafana/data';
import { LegendDisplayMode } from '../../index';
import { OptionsWithLegend } from '../models.gen';
/**
* @alpha
*/
export function addLegendOptions<T extends OptionsWithLegend>(
builder: PanelOptionsEditorBuilder<T>,
includeLegendCalcs = true
) {
builder
.addRadio({
path: 'legend.displayMode',
name: 'Legend mode',
category: ['Legend'],
description: '',
defaultValue: LegendDisplayMode.List,
settings: {
options: [
{ value: LegendDisplayMode.List, label: 'List' },
{ value: LegendDisplayMode.Table, label: 'Table' },
{ value: LegendDisplayMode.Hidden, label: 'Hidden' },
],
},
})
.addRadio({
path: 'legend.placement',
name: 'Legend placement',
category: ['Legend'],
description: '',
defaultValue: 'bottom',
settings: {
options: [
{ value: 'bottom', label: 'Bottom' },
{ value: 'right', label: 'Right' },
],
},
showIf: (c) => c.legend.displayMode !== LegendDisplayMode.Hidden,
});
if (includeLegendCalcs) {
builder.addCustomEditor<StatsPickerConfigSettings, string[]>({
id: 'legend.calcs',
path: 'legend.calcs',
name: 'Legend values',
category: ['Legend'],
description: 'Select values or calculations to show in legend',
editor: standardEditorsRegistry.get('stats-picker').editor as any,
defaultValue: [],
settings: {
allowMultiple: true,
},
showIf: (currentConfig) => currentConfig.legend.displayMode !== LegendDisplayMode.Hidden,
});
}
}
| packages/grafana-ui/src/options/builder/legend.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00019234941282775253,
0.0001768630463629961,
0.0001724628236843273,
0.00017423037206754088,
0.000007004792678344529
] |
{
"id": 1,
"code_window": [
"\tngCond, err := oldCond.GetNew(orgID)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true}, ngCond.Data, time.Unix(500, 0))\n",
"\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true, Log: log.New(\"translate\")}, ngCond.Data, time.Unix(500, 0))\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "replace",
"edit_start_line_idx": 37
} | package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/util"
"github.com/pkg/errors"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3"
)
var searchRegex = regexp.MustCompile(`\{(\w+)\}`)
var NotImplementedResp = ErrResp(http.StatusNotImplemented, errors.New("endpoint not implemented"), "")
func toMacaronPath(path string) string {
return string(searchRegex.ReplaceAllFunc([]byte(path), func(s []byte) []byte {
m := string(s[1 : len(s)-1])
return []byte(fmt.Sprintf(":%s", m))
}))
}
func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) {
recipient := ctx.Params("Recipient")
if recipient == apimodels.GrafanaBackend.String() {
return apimodels.GrafanaBackend, nil
}
if datasourceID, err := strconv.ParseInt(recipient, 10, 64); err == nil {
if ds, err := cache.GetDatasource(datasourceID, ctx.SignedInUser, ctx.SkipCache); err == nil {
switch ds.Type {
case "loki", "prometheus":
return apimodels.LoTexRulerBackend, nil
case "alertmanager":
return apimodels.AlertmanagerBackend, nil
default:
return 0, fmt.Errorf("unexpected backend type (%v)", ds.Type)
}
}
}
return 0, fmt.Errorf("unexpected backend type (%v)", recipient)
}
// macaron unsafely asserts the http.ResponseWriter is an http.CloseNotifier, which will panic.
// Here we impl it, which will ensure this no longer happens, but neither will we take
// advantage cancelling upstream requests when the downstream has closed.
// NB: http.CloseNotifier is a deprecated ifc from before the context pkg.
type safeMacaronWrapper struct {
http.ResponseWriter
}
func (w *safeMacaronWrapper) CloseNotify() <-chan bool {
return make(chan bool)
}
// replacedResponseWriter overwrites the underlying responsewriter used by a *models.ReqContext.
// It's ugly because it needs to replace a value behind a few nested pointers.
func replacedResponseWriter(ctx *models.ReqContext) (*models.ReqContext, *response.NormalResponse) {
resp := response.CreateNormalResponse(make(http.Header), nil, 0)
cpy := *ctx
cpyMCtx := *cpy.Context
cpyMCtx.Resp = macaron.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{resp})
cpy.Context = &cpyMCtx
return &cpy, resp
}
type AlertingProxy struct {
DataProxy *datasourceproxy.DatasourceProxyService
}
// withReq proxies a different request
func (p *AlertingProxy) withReq(
ctx *models.ReqContext,
method string,
u *url.URL,
body io.Reader,
extractor func(*response.NormalResponse) (interface{}, error),
headers map[string]string,
) response.Response {
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
for h, v := range headers {
req.Header.Add(h, v)
}
newCtx, resp := replacedResponseWriter(ctx)
newCtx.Req.Request = req
p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64("Recipient"))
status := resp.Status()
if status >= 400 {
errMessage := string(resp.Body())
// if Content-Type is application/json
// and it is successfully decoded and contains a message
// return this as response error message
if strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json") {
var m map[string]interface{}
if err := json.Unmarshal(resp.Body(), &m); err == nil {
if message, ok := m["message"]; ok {
errMessage = message.(string)
}
}
} else if strings.HasPrefix(resp.Header().Get("Content-Type"), "text/html") {
// if Content-Type is text/html
// do not return the body
errMessage = "redacted html"
}
return ErrResp(status, errors.New(errMessage), "")
}
t, err := extractor(resp)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
b, err := json.Marshal(t)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(status, b)
}
func yamlExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "yaml") {
return nil, fmt.Errorf("unexpected content type from upstream. expected YAML, got %v", contentType)
}
decoder := yaml.NewDecoder(bytes.NewReader(resp.Body()))
decoder.KnownFields(true)
err := decoder.Decode(v)
return v, err
}
}
func jsonExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
if v == nil {
// json unmarshal expects a pointer
v = &map[string]interface{}{}
}
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "json") {
return nil, fmt.Errorf("unexpected content type from upstream. expected JSON, got %v", contentType)
}
return v, json.Unmarshal(resp.Body(), v)
}
}
func messageExtractor(resp *response.NormalResponse) (interface{}, error) {
return map[string]string{"message": string(resp.Body())}, nil
}
func validateCondition(c ngmodels.Condition, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) error {
if len(c.Data) == 0 {
return nil
}
refIDs, err := validateQueriesAndExpressions(c.Data, user, skipCache, datasourceCache)
if err != nil {
return err
}
t := make([]string, 0, len(refIDs))
for refID := range refIDs {
t = append(t, refID)
}
if _, ok := refIDs[c.Condition]; !ok {
return fmt.Errorf("condition %s not found in any query or expression: it should be one of: [%s]", c.Condition, strings.Join(t, ","))
}
return nil
}
func validateQueriesAndExpressions(data []ngmodels.AlertQuery, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) (map[string]struct{}, error) {
refIDs := make(map[string]struct{})
if len(data) == 0 {
return nil, nil
}
for _, query := range data {
datasourceUID, err := query.GetDatasource()
if err != nil {
return nil, err
}
isExpression, err := query.IsExpression()
if err != nil {
return nil, err
}
if isExpression {
refIDs[query.RefID] = struct{}{}
continue
}
_, err = datasourceCache.GetDatasourceByUID(datasourceUID, user, skipCache)
if err != nil {
return nil, fmt.Errorf("invalid query %s: %w: %s", query.RefID, err, datasourceUID)
}
refIDs[query.RefID] = struct{}{}
}
return refIDs, nil
}
func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {
evalCond := ngmodels.Condition{
Condition: cmd.Condition,
OrgID: c.SignedInUser.OrgId,
Data: cmd.Data,
}
if err := validateCondition(evalCond, c.SignedInUser, c.SkipCache, datasourceCache); err != nil {
return ErrResp(http.StatusBadRequest, err, "invalid condition")
}
now := cmd.Now
if now.IsZero() {
now = timeNow()
}
evaluator := eval.Evaluator{Cfg: cfg}
evalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "Failed to evaluate conditions")
}
frame := evalResults.AsDataFrame()
return response.JSONStreaming(http.StatusOK, util.DynMap{
"instances": []*data.Frame{&frame},
})
}
// ErrorResp creates a response with a visible error
func ErrResp(status int, err error, msg string, args ...interface{}) *response.NormalResponse {
if msg != "" {
err = errors.WithMessagef(err, msg, args...)
}
return response.Error(status, err.Error(), nil)
}
| pkg/services/ngalert/api/util.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.007190529722720385,
0.0005955706001259387,
0.00016308917838614434,
0.00016928225522860885,
0.0014106400776654482
] |
{
"id": 1,
"code_window": [
"\tngCond, err := oldCond.GetNew(orgID)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true}, ngCond.Data, time.Unix(500, 0))\n",
"\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true, Log: log.New(\"translate\")}, ngCond.Data, time.Unix(500, 0))\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "replace",
"edit_start_line_idx": 37
} | import React, { PureComponent } from 'react';
import store from '../../store';
export interface Props<T> {
storageKey: string;
defaultValue?: T;
children: (value: T, onSaveToStore: (value: T) => void) => React.ReactNode;
}
interface State<T> {
value: T;
}
export class LocalStorageValueProvider<T> extends PureComponent<Props<T>, State<T>> {
constructor(props: Props<T>) {
super(props);
const { storageKey, defaultValue } = props;
this.state = {
value: store.getObject(storageKey, defaultValue),
};
}
onSaveToStore = (value: T) => {
const { storageKey } = this.props;
try {
store.setObject(storageKey, value);
} catch (error) {
console.error(error);
}
this.setState({ value });
};
render() {
const { children } = this.props;
const { value } = this.state;
return <>{children(value, this.onSaveToStore)}</>;
}
}
| public/app/core/components/LocalStorageValueProvider/LocalStorageValueProvider.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001809619861887768,
0.00017710911924950778,
0.00017375772586092353,
0.0001778351579559967,
0.0000026455484203324886
] |
{
"id": 1,
"code_window": [
"\tngCond, err := oldCond.GetNew(orgID)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true}, ngCond.Data, time.Unix(500, 0))\n",
"\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true, Log: log.New(\"translate\")}, ngCond.Data, time.Unix(500, 0))\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "replace",
"edit_start_line_idx": 37
} | package api
import (
"errors"
"fmt"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func GetPendingOrgInvites(c *models.ReqContext) response.Response {
query := models.GetTempUsersQuery{OrgId: c.OrgId, Status: models.TmpUserInvitePending}
if err := bus.Dispatch(&query); err != nil {
return response.Error(500, "Failed to get invites from db", err)
}
for _, invite := range query.Result {
invite.Url = setting.ToAbsUrl("invite/" + invite.Code)
}
return response.JSON(200, query.Result)
}
func AddOrgInvite(c *models.ReqContext, inviteDto dtos.AddInviteForm) response.Response {
if !inviteDto.Role.IsValid() {
return response.Error(400, "Invalid role specified", nil)
}
// first try get existing user
userQuery := models.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
if !errors.Is(err, models.ErrUserNotFound) {
return response.Error(500, "Failed to query db for existing user check", err)
}
} else {
return inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)
}
if setting.DisableLoginForm {
return response.Error(400, "Cannot invite when login is disabled.", nil)
}
cmd := models.CreateTempUserCommand{}
cmd.OrgId = c.OrgId
cmd.Email = inviteDto.LoginOrEmail
cmd.Name = inviteDto.Name
cmd.Status = models.TmpUserInvitePending
cmd.InvitedByUserId = c.UserId
var err error
cmd.Code, err = util.GetRandomString(30)
if err != nil {
return response.Error(500, "Could not generate random string", err)
}
cmd.Role = inviteDto.Role
cmd.RemoteAddr = c.Req.RemoteAddr
if err := bus.Dispatch(&cmd); err != nil {
return response.Error(500, "Failed to save invite to database", err)
}
// send invite email
if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) {
emailCmd := models.SendEmailCommand{
To: []string{inviteDto.LoginOrEmail},
Template: "new_user_invite.html",
Data: map[string]interface{}{
"Name": util.StringsFallback2(cmd.Name, cmd.Email),
"OrgName": c.OrgName,
"Email": c.Email,
"LinkUrl": setting.ToAbsUrl("invite/" + cmd.Code),
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
if errors.Is(err, models.ErrSmtpNotEnabled) {
return response.Error(412, err.Error(), err)
}
return response.Error(500, "Failed to send email invite", err)
}
emailSentCmd := models.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code}
if err := bus.Dispatch(&emailSentCmd); err != nil {
return response.Error(500, "Failed to update invite with email sent info", err)
}
return response.Success(fmt.Sprintf("Sent invite to %s", inviteDto.LoginOrEmail))
}
return response.Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail))
}
func inviteExistingUserToOrg(c *models.ReqContext, user *models.User, inviteDto *dtos.AddInviteForm) response.Response {
// user exists, add org role
createOrgUserCmd := models.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role}
if err := bus.Dispatch(&createOrgUserCmd); err != nil {
if errors.Is(err, models.ErrOrgUserAlreadyAdded) {
return response.Error(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
}
return response.Error(500, "Error while trying to create org user", err)
}
if inviteDto.SendEmail && util.IsEmail(user.Email) {
emailCmd := models.SendEmailCommand{
To: []string{user.Email},
Template: "invited_to_org.html",
Data: map[string]interface{}{
"Name": user.NameOrFallback(),
"OrgName": c.OrgName,
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
return response.Error(500, "Failed to send email invited_to_org", err)
}
}
return response.JSON(200, util.DynMap{
"message": fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName),
"userId": user.Id,
})
}
func RevokeInvite(c *models.ReqContext) response.Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), models.TmpUserRevoked); !ok {
return rsp
}
return response.Success("Invite revoked")
}
// GetInviteInfoByCode gets a pending user invite corresponding to a certain code.
// A response containing an InviteInfo object is returned if the invite is found.
// If a (pending) invite is not found, 404 is returned.
func GetInviteInfoByCode(c *models.ReqContext) response.Response {
query := models.GetTempUserByCodeQuery{Code: c.Params(":code")}
if err := bus.Dispatch(&query); err != nil {
if errors.Is(err, models.ErrTempUserNotFound) {
return response.Error(404, "Invite not found", nil)
}
return response.Error(500, "Failed to get invite", err)
}
invite := query.Result
if invite.Status != models.TmpUserInvitePending {
return response.Error(404, "Invite not found", nil)
}
return response.JSON(200, dtos.InviteInfo{
Email: invite.Email,
Name: invite.Name,
Username: invite.Email,
InvitedBy: util.StringsFallback3(invite.InvitedByName, invite.InvitedByLogin, invite.InvitedByEmail),
})
}
func (hs *HTTPServer) CompleteInvite(c *models.ReqContext, completeInvite dtos.CompleteInviteForm) response.Response {
query := models.GetTempUserByCodeQuery{Code: completeInvite.InviteCode}
if err := bus.Dispatch(&query); err != nil {
if errors.Is(err, models.ErrTempUserNotFound) {
return response.Error(404, "Invite not found", nil)
}
return response.Error(500, "Failed to get invite", err)
}
invite := query.Result
if invite.Status != models.TmpUserInvitePending {
return response.Error(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil)
}
cmd := models.CreateUserCommand{
Email: completeInvite.Email,
Name: completeInvite.Name,
Login: completeInvite.Username,
Password: completeInvite.Password,
SkipOrgSetup: true,
}
user, err := hs.Login.CreateUser(cmd)
if err != nil {
if errors.Is(err, models.ErrUserAlreadyExists) {
return response.Error(412, fmt.Sprintf("User with email '%s' or username '%s' already exists", completeInvite.Email, completeInvite.Username), err)
}
return response.Error(500, "failed to create user", err)
}
if err := bus.Publish(&events.SignUpCompleted{
Name: user.NameOrFallback(),
Email: user.Email,
}); err != nil {
return response.Error(500, "failed to publish event", err)
}
if ok, rsp := applyUserInvite(user, invite, true); !ok {
return rsp
}
err = hs.loginUserWithUser(user, c)
if err != nil {
return response.Error(500, "failed to accept invite", err)
}
metrics.MApiUserSignUpCompleted.Inc()
metrics.MApiUserSignUpInvite.Inc()
return response.JSON(200, util.DynMap{
"message": "User created and logged in",
"id": user.Id,
})
}
func updateTempUserStatus(code string, status models.TempUserStatus) (bool, response.Response) {
// update temp user status
updateTmpUserCmd := models.UpdateTempUserStatusCommand{Code: code, Status: status}
if err := bus.Dispatch(&updateTmpUserCmd); err != nil {
return false, response.Error(500, "Failed to update invite status", err)
}
return true, nil
}
func applyUserInvite(user *models.User, invite *models.TempUserDTO, setActive bool) (bool, response.Response) {
// add to org
addOrgUserCmd := models.AddOrgUserCommand{OrgId: invite.OrgId, UserId: user.Id, Role: invite.Role}
if err := bus.Dispatch(&addOrgUserCmd); err != nil {
if !errors.Is(err, models.ErrOrgUserAlreadyAdded) {
return false, response.Error(500, "Error while trying to create org user", err)
}
}
// update temp user status
if ok, rsp := updateTempUserStatus(invite.Code, models.TmpUserCompleted); !ok {
return false, rsp
}
if setActive {
// set org to active
if err := bus.Dispatch(&models.SetUsingOrgCommand{OrgId: invite.OrgId, UserId: user.Id}); err != nil {
return false, response.Error(500, "Failed to set org as active", err)
}
}
return true, nil
}
| pkg/api/org_invite.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001774599659256637,
0.00017045560525730252,
0.00016488737310282886,
0.0001702173613011837,
0.0000034341449008934433
] |
{
"id": 1,
"code_window": [
"\tngCond, err := oldCond.GetNew(orgID)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true}, ngCond.Data, time.Unix(500, 0))\n",
"\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tbackendReq, err := eval.GetExprRequest(eval.AlertExecCtx{ExpressionsEnabled: true, Log: log.New(\"translate\")}, ngCond.Data, time.Unix(500, 0))\n"
],
"file_path": "pkg/expr/translate/translate.go",
"type": "replace",
"edit_start_line_idx": 37
} | //
// Navs
// --------------------------------------------------
// BASE CLASS
// ----------
.nav {
margin: 0;
list-style: none;
}
// Make links block level
.nav > li > a {
display: block;
}
// Redeclare pull classes because of specificity
.nav > .pull-right {
float: right;
}
// TABS AND PILLS
// -------------
// Common styles
.nav-tabs {
@include clearfix();
}
.nav-tabs > li {
float: left;
}
.nav-tabs > li > a {
padding-right: 12px;
padding-left: 12px;
margin-right: 2px;
line-height: 14px; // keeps the overall height an even number
}
// TABS
// ----
// Give the tabs something to sit on
.nav-tabs {
border-bottom: 1px solid $divider-border-color;
padding-left: 10px;
margin: 0 0 10px 0;
}
// Make the list-items overlay the bottom border
.nav-tabs > li {
margin-bottom: -1px;
}
// Active state, and it's :hover/:focus to override normal :hover/:focus
.nav-tabs > .active > a,
.nav-tabs > .active > a:hover,
.nav-tabs > .active > a:focus {
@include border-radius(3px);
border-color: $divider-border-color;
border-bottom: 1px solid $panel-bg;
color: $link-color;
}
// Show/hide tabbable areas
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
// temp hack
.modal-body {
.nav-tabs {
border-bottom: none;
}
.nav-tabs > li > a {
border: none;
border-radius: 0;
&:hover,
&:focus {
border-bottom: 1px solid $blue;
}
}
.nav-tabs > .active > a,
.nav-tabs > .active > a:hover,
.nav-tabs > .active > a:focus {
border: none;
border-bottom: 1px solid $blue;
color: $link-color;
}
}
| public/sass/components/_navs.scss | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017866320558823645,
0.00017626601038500667,
0.00017346390814054757,
0.00017622628365643322,
0.000001512934659331222
] |
{
"id": 2,
"code_window": [
"\trecipient := c.Params(\"Recipient\")\n",
"\tif recipient == apimodels.GrafanaBackend.String() {\n",
"\t\tif body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {\n",
"\t\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n",
"\t\t}\n",
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg)\n",
"\t}\n",
"\n",
"\tif body.Type() != apimodels.LoTexRulerBackend {\n",
"\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg, srv.log)\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 39
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0010711621725931764,
0.00020421088265720755,
0.00016338771092705429,
0.000172140818904154,
0.00015507449279539287
] |
{
"id": 2,
"code_window": [
"\trecipient := c.Params(\"Recipient\")\n",
"\tif recipient == apimodels.GrafanaBackend.String() {\n",
"\t\tif body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {\n",
"\t\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n",
"\t\t}\n",
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg)\n",
"\t}\n",
"\n",
"\tif body.Type() != apimodels.LoTexRulerBackend {\n",
"\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg, srv.log)\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 39
} | package definitions
import (
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
amv2 "github.com/prometheus/alertmanager/api/v2/models"
"github.com/prometheus/alertmanager/config"
"gopkg.in/yaml.v3"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
// swagger:route POST /api/alertmanager/{Recipient}/config/api/v1/alerts alertmanager RoutePostAlertingConfig
//
// sets an Alerting config
//
// Responses:
// 201: Ack
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/config/api/v1/alerts alertmanager RouteGetAlertingConfig
//
// gets an Alerting config
//
// Responses:
// 200: GettableUserConfig
// 400: ValidationError
// swagger:route DELETE /api/alertmanager/{Recipient}/config/api/v1/alerts alertmanager RouteDeleteAlertingConfig
//
// deletes the Alerting config for a tenant
//
// Responses:
// 200: Ack
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/api/v2/status alertmanager RouteGetAMStatus
//
// get alertmanager status and configuration
//
// Responses:
// 200: GettableStatus
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/api/v2/alerts alertmanager RouteGetAMAlerts
//
// get alertmanager alerts
//
// Responses:
// 200: GettableAlerts
// 400: ValidationError
// swagger:route POST /api/alertmanager/{Recipient}/api/v2/alerts alertmanager RoutePostAMAlerts
//
// create alertmanager alerts
//
// Responses:
// 200: Ack
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/api/v2/alerts/groups alertmanager RouteGetAMAlertGroups
//
// get alertmanager alerts
//
// Responses:
// 200: AlertGroups
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/api/v2/silences alertmanager RouteGetSilences
//
// get silences
//
// Responses:
// 200: GettableSilences
// 400: ValidationError
// swagger:route POST /api/alertmanager/{Recipient}/api/v2/silences alertmanager RouteCreateSilence
//
// create silence
//
// Responses:
// 201: GettableSilence
// 400: ValidationError
// swagger:route GET /api/alertmanager/{Recipient}/api/v2/silence/{SilenceId} alertmanager RouteGetSilence
//
// get silence
//
// Responses:
// 200: GettableSilence
// 400: ValidationError
// swagger:route DELETE /api/alertmanager/{Recipient}/api/v2/silence/{SilenceId} alertmanager RouteDeleteSilence
//
// delete silence
//
// Responses:
// 200: Ack
// 400: ValidationError
// swagger:parameters RouteCreateSilence
type CreateSilenceParams struct {
// in:body
Silence PostableSilence
}
// swagger:parameters RouteGetSilence RouteDeleteSilence
type GetDeleteSilenceParams struct {
// in:path
SilenceId string
}
// swagger:parameters RouteGetSilences
type GetSilencesParams struct {
// in:query
Filter []string `json:"filter"`
}
// swagger:model
type GettableStatus struct {
// cluster
// Required: true
Cluster *amv2.ClusterStatus `json:"cluster"`
// config
// Required: true
Config *PostableApiAlertingConfig `json:"config"`
// uptime
// Required: true
// Format: date-time
Uptime *strfmt.DateTime `json:"uptime"`
// version info
// Required: true
VersionInfo *amv2.VersionInfo `json:"versionInfo"`
}
func (s *GettableStatus) UnmarshalJSON(b []byte) error {
amStatus := amv2.AlertmanagerStatus{}
if err := json.Unmarshal(b, &amStatus); err != nil {
return err
}
c := config.Config{}
if err := yaml.Unmarshal([]byte(*amStatus.Config.Original), &c); err != nil {
return err
}
s.Cluster = amStatus.Cluster
s.Config = &PostableApiAlertingConfig{Config: Config{
Global: c.Global,
Route: c.Route,
InhibitRules: c.InhibitRules,
Templates: c.Templates,
}}
s.Uptime = amStatus.Uptime
s.VersionInfo = amStatus.VersionInfo
type overrides struct {
Receivers *[]*PostableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}
if err := yaml.Unmarshal([]byte(*amStatus.Config.Original), &overrides{Receivers: &s.Config.Receivers}); err != nil {
return err
}
return nil
}
func NewGettableStatus(cfg *PostableApiAlertingConfig) *GettableStatus {
// In Grafana, the only field we support is Config.
cs := amv2.ClusterStatusStatusDisabled
na := "N/A"
return &GettableStatus{
Cluster: &amv2.ClusterStatus{
Status: &cs,
Peers: []*amv2.PeerStatus{},
},
VersionInfo: &amv2.VersionInfo{
Branch: &na,
BuildDate: &na,
BuildUser: &na,
GoVersion: &na,
Revision: &na,
Version: &na,
},
Config: cfg,
}
}
// swagger:model
type PostableSilence = amv2.PostableSilence
// swagger:model
type GettableSilences = amv2.GettableSilences
// swagger:model
type GettableSilence = amv2.GettableSilence
// swagger:model
type GettableAlerts = amv2.GettableAlerts
// swagger:model
type GettableAlert = amv2.GettableAlert
// swagger:model
type AlertGroups = amv2.AlertGroups
// swagger:model
type AlertGroup = amv2.AlertGroup
// swagger:model
type Receiver = amv2.Receiver
// swagger:parameters RouteGetAMAlerts RouteGetAMAlertGroups
type AlertsParams struct {
// Show active alerts
// in: query
// required: false
// default: true
Active bool `json:"active"`
// Show silenced alerts
// in: query
// required: false
// default: true
Silenced bool `json:"silenced"`
// Show inhibited alerts
// in: query
// required: false
// default: true
Inhibited bool `json:"inhibited"`
// A list of matchers to filter alerts by
// in: query
// required: false
Matchers []string `json:"filter"`
// A regex matching receivers to filter alerts by
// in: query
// required: false
Receivers string `json:"receiver"`
}
// swagger:parameters RoutePostAMAlerts
type PostableAlerts struct {
// in:body
PostableAlerts []amv2.PostableAlert `yaml:"" json:""`
}
// swagger:parameters RoutePostAlertingConfig
type BodyAlertingConfig struct {
// in:body
Body PostableUserConfig
}
// alertmanager routes
// swagger:parameters RoutePostAlertingConfig RouteGetAlertingConfig RouteDeleteAlertingConfig RouteGetAMStatus RouteGetAMAlerts RoutePostAMAlerts RouteGetAMAlertGroups RouteGetSilences RouteCreateSilence RouteGetSilence RouteDeleteSilence RoutePostAlertingConfig
// ruler routes
// swagger:parameters RouteGetRulesConfig RoutePostNameRulesConfig RouteGetNamespaceRulesConfig RouteDeleteNamespaceRulesConfig RouteGetRulegGroupConfig RouteDeleteRuleGroupConfig
// prom routes
// swagger:parameters RouteGetRuleStatuses RouteGetAlertStatuses
// testing routes
// swagger:parameters RouteTestReceiverConfig RouteTestRuleConfig
type DatasourceReference struct {
// Recipient should be "grafana" for requests to be handled by grafana
// and the numeric datasource id for requests to be forwarded to a datasource
// in:path
Recipient string
}
// swagger:model
type PostableUserConfig struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig PostableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
amSimple map[string]interface{} `yaml:"-" json:"-"`
}
func (c *PostableUserConfig) UnmarshalJSON(b []byte) error {
type plain PostableUserConfig
if err := json.Unmarshal(b, (*plain)(c)); err != nil {
return err
}
// validate first
if err := c.validate(); err != nil {
return err
}
type intermediate struct {
AlertmanagerConfig map[string]interface{} `yaml:"alertmanager_config" json:"alertmanager_config"`
}
var tmp intermediate
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
// store the map[string]interface{} variant for re-encoding later without redaction
c.amSimple = tmp.AlertmanagerConfig
return nil
}
func (c *PostableUserConfig) validate() error {
// Taken from https://github.com/prometheus/alertmanager/blob/master/config/config.go#L170-L191
// Check if we have a root route. We cannot check for it in the
// UnmarshalYAML method because it won't be called if the input is empty
// (e.g. the config file is empty or only contains whitespace).
if c.AlertmanagerConfig.Route == nil {
return fmt.Errorf("no route provided in config")
}
// Check if continue in root route.
if c.AlertmanagerConfig.Route.Continue {
return fmt.Errorf("cannot have continue in root route")
}
return nil
}
// GetGrafanaReceiverMap returns a map that associates UUIDs to grafana receivers
func (c *PostableUserConfig) GetGrafanaReceiverMap() map[string]*PostableGrafanaReceiver {
UIDs := make(map[string]*PostableGrafanaReceiver)
for _, r := range c.AlertmanagerConfig.Receivers {
switch r.Type() {
case GrafanaReceiverType:
for _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {
UIDs[gr.UID] = gr
}
default:
}
}
return UIDs
}
// ProcessConfig parses grafana receivers, encrypts secrets and assigns UUIDs (if they are missing)
func (c *PostableUserConfig) ProcessConfig() error {
seenUIDs := make(map[string]struct{})
// encrypt secure settings for storing them in DB
for _, r := range c.AlertmanagerConfig.Receivers {
switch r.Type() {
case GrafanaReceiverType:
for _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {
for k, v := range gr.SecureSettings {
encryptedData, err := util.Encrypt([]byte(v), setting.SecretKey)
if err != nil {
return fmt.Errorf("failed to encrypt secure settings: %w", err)
}
gr.SecureSettings[k] = base64.StdEncoding.EncodeToString(encryptedData)
}
if gr.UID == "" {
retries := 5
for i := 0; i < retries; i++ {
gen := util.GenerateShortUID()
_, ok := seenUIDs[gen]
if !ok {
gr.UID = gen
break
}
}
if gr.UID == "" {
return fmt.Errorf("all %d attempts to generate UID for receiver have failed; please retry", retries)
}
}
seenUIDs[gr.UID] = struct{}{}
}
default:
}
}
return nil
}
// MarshalYAML implements yaml.Marshaller.
func (c *PostableUserConfig) MarshalYAML() (interface{}, error) {
yml, err := yaml.Marshal(c.amSimple)
if err != nil {
return nil, err
}
// cortex/loki actually pass the AM config as a string.
cortexPostableUserConfig := struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config" json:"alertmanager_config"`
}{
TemplateFiles: c.TemplateFiles,
AlertmanagerConfig: string(yml),
}
return cortexPostableUserConfig, nil
}
func (c *PostableUserConfig) UnmarshalYAML(value *yaml.Node) error {
// cortex/loki actually pass the AM config as a string.
type cortexPostableUserConfig struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config" json:"alertmanager_config"`
}
var tmp cortexPostableUserConfig
if err := value.Decode(&tmp); err != nil {
return err
}
if err := yaml.Unmarshal([]byte(tmp.AlertmanagerConfig), &c.AlertmanagerConfig); err != nil {
return err
}
c.TemplateFiles = tmp.TemplateFiles
return nil
}
// swagger:model
type GettableUserConfig struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig GettableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
// amSimple stores a map[string]interface of the decoded alertmanager config.
// This enables circumventing the underlying alertmanager secret type
// which redacts itself during encoding.
amSimple map[string]interface{} `yaml:"-" json:"-"`
}
func (c *GettableUserConfig) UnmarshalYAML(value *yaml.Node) error {
// cortex/loki actually pass the AM config as a string.
type cortexGettableUserConfig struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config" json:"alertmanager_config"`
}
var tmp cortexGettableUserConfig
if err := value.Decode(&tmp); err != nil {
return err
}
if err := yaml.Unmarshal([]byte(tmp.AlertmanagerConfig), &c.AlertmanagerConfig); err != nil {
return err
}
if err := yaml.Unmarshal([]byte(tmp.AlertmanagerConfig), &c.amSimple); err != nil {
return err
}
c.TemplateFiles = tmp.TemplateFiles
return nil
}
func (c *GettableUserConfig) MarshalJSON() ([]byte, error) {
type plain struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig map[string]interface{} `yaml:"alertmanager_config" json:"alertmanager_config"`
}
tmp := plain{
TemplateFiles: c.TemplateFiles,
AlertmanagerConfig: c.amSimple,
}
return json.Marshal(tmp)
}
// GetGrafanaReceiverMap returns a map that associates UUIDs to grafana receivers
func (c *GettableUserConfig) GetGrafanaReceiverMap() map[string]*GettableGrafanaReceiver {
UIDs := make(map[string]*GettableGrafanaReceiver)
for _, r := range c.AlertmanagerConfig.Receivers {
switch r.Type() {
case GrafanaReceiverType:
for _, gr := range r.GettableGrafanaReceivers.GrafanaManagedReceivers {
UIDs[gr.UID] = gr
}
default:
}
}
return UIDs
}
type GettableApiAlertingConfig struct {
Config `yaml:",inline"`
// Override with our superset receiver type
Receivers []*GettableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}
func (c *GettableApiAlertingConfig) UnmarshalJSON(b []byte) error {
type plain GettableApiAlertingConfig
if err := json.Unmarshal(b, (*plain)(c)); err != nil {
return err
}
// Since Config implements json.Unmarshaler, we must handle _all_ other fields independently.
// Otherwise, the json decoder will detect this and only use the embedded type.
// Additionally, we'll use pointers to slices in order to reference the intended target.
type overrides struct {
Receivers *[]*GettableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}
if err := json.Unmarshal(b, &overrides{Receivers: &c.Receivers}); err != nil {
return err
}
return c.validate()
}
// validate ensures that the two routing trees use the correct receiver types.
func (c *GettableApiAlertingConfig) validate() error {
receivers := make(map[string]struct{}, len(c.Receivers))
var hasGrafReceivers, hasAMReceivers bool
for _, r := range c.Receivers {
receivers[r.Name] = struct{}{}
switch r.Type() {
case GrafanaReceiverType:
hasGrafReceivers = true
case AlertmanagerReceiverType:
hasAMReceivers = true
default:
continue
}
}
if hasGrafReceivers && hasAMReceivers {
return fmt.Errorf("cannot mix Alertmanager & Grafana receiver types")
}
for _, receiver := range AllReceivers(c.Route) {
_, ok := receivers[receiver]
if !ok {
return fmt.Errorf("unexpected receiver (%s) is undefined", receiver)
}
}
return nil
}
// Config is the top-level configuration for Alertmanager's config files.
type Config struct {
Global *config.GlobalConfig `yaml:"global,omitempty" json:"global,omitempty"`
Route *config.Route `yaml:"route,omitempty" json:"route,omitempty"`
InhibitRules []*config.InhibitRule `yaml:"inhibit_rules,omitempty" json:"inhibit_rules,omitempty"`
Templates []string `yaml:"templates" json:"templates"`
}
// Config is the entrypoint for the embedded Alertmanager config with the exception of receivers.
// Prometheus historically uses yaml files as the method of configuration and thus some
// post-validation is included in the UnmarshalYAML method. Here we simply run this with
// a noop unmarshaling function in order to benefit from said validation.
func (c *Config) UnmarshalJSON(b []byte) error {
type plain Config
if err := json.Unmarshal(b, (*plain)(c)); err != nil {
return err
}
noopUnmarshal := func(_ interface{}) error { return nil }
if c.Global != nil {
if err := c.Global.UnmarshalYAML(noopUnmarshal); err != nil {
return err
}
}
if c.Route == nil {
return fmt.Errorf("no routes provided")
}
// Route is a recursive structure that includes validation in the yaml unmarshaler.
// Therefore, we'll redirect json -> yaml to utilize these.
b, err := yaml.Marshal(c.Route)
if err != nil {
return errors.Wrap(err, "marshaling route to yaml for validation")
}
err = yaml.Unmarshal(b, c.Route)
if err != nil {
return errors.Wrap(err, "unmarshaling route for validations")
}
if len(c.Route.Receiver) == 0 {
return fmt.Errorf("root route must specify a default receiver")
}
if len(c.Route.Match) > 0 || len(c.Route.MatchRE) > 0 {
return fmt.Errorf("root route must not have any matchers")
}
for _, r := range c.InhibitRules {
if err := r.UnmarshalYAML(noopUnmarshal); err != nil {
return err
}
}
return nil
}
type PostableApiAlertingConfig struct {
Config `yaml:",inline"`
// Override with our superset receiver type
Receivers []*PostableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}
func (c *PostableApiAlertingConfig) UnmarshalJSON(b []byte) error {
type plain PostableApiAlertingConfig
if err := json.Unmarshal(b, (*plain)(c)); err != nil {
return err
}
// Since Config implements json.Unmarshaler, we must handle _all_ other fields independently.
// Otherwise, the json decoder will detect this and only use the embedded type.
// Additionally, we'll use pointers to slices in order to reference the intended target.
type overrides struct {
Receivers *[]*PostableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}
if err := json.Unmarshal(b, &overrides{Receivers: &c.Receivers}); err != nil {
return err
}
return c.validate()
}
// validate ensures that the two routing trees use the correct receiver types.
func (c *PostableApiAlertingConfig) validate() error {
receivers := make(map[string]struct{}, len(c.Receivers))
var hasGrafReceivers, hasAMReceivers bool
for _, r := range c.Receivers {
receivers[r.Name] = struct{}{}
switch r.Type() {
case GrafanaReceiverType:
hasGrafReceivers = true
case AlertmanagerReceiverType:
hasAMReceivers = true
default:
continue
}
}
if hasGrafReceivers && hasAMReceivers {
return fmt.Errorf("cannot mix Alertmanager & Grafana receiver types")
}
if hasGrafReceivers {
// Taken from https://github.com/prometheus/alertmanager/blob/master/config/config.go#L170-L191
// Check if we have a root route. We cannot check for it in the
// UnmarshalYAML method because it won't be called if the input is empty
// (e.g. the config file is empty or only contains whitespace).
if c.Route == nil {
return fmt.Errorf("no route provided in config")
}
// Check if continue in root route.
if c.Route.Continue {
return fmt.Errorf("cannot have continue in root route")
}
}
for _, receiver := range AllReceivers(c.Route) {
_, ok := receivers[receiver]
if !ok {
return fmt.Errorf("unexpected receiver (%s) is undefined", receiver)
}
}
return nil
}
// Type requires validate has been called and just checks the first receiver type
func (c *PostableApiAlertingConfig) ReceiverType() ReceiverType {
for _, r := range c.Receivers {
switch r.Type() {
case GrafanaReceiverType:
return GrafanaReceiverType
case AlertmanagerReceiverType:
return AlertmanagerReceiverType
default:
continue
}
}
return EmptyReceiverType
}
// AllReceivers will recursively walk a routing tree and return a list of all the
// referenced receiver names.
func AllReceivers(route *config.Route) (res []string) {
if route == nil {
return res
}
if route.Receiver != "" {
res = append(res, route.Receiver)
}
for _, subRoute := range route.Routes {
res = append(res, AllReceivers(subRoute)...)
}
return res
}
type GettableGrafanaReceiver struct {
UID string `json:"uid"`
Name string `json:"name"`
Type string `json:"type"`
DisableResolveMessage bool `json:"disableResolveMessage"`
Settings *simplejson.Json `json:"settings"`
SecureFields map[string]bool `json:"secureFields"`
}
type PostableGrafanaReceiver struct {
UID string `json:"uid"`
Name string `json:"name"`
Type string `json:"type"`
DisableResolveMessage bool `json:"disableResolveMessage"`
Settings *simplejson.Json `json:"settings"`
SecureSettings map[string]string `json:"secureSettings"`
}
func (r *PostableGrafanaReceiver) GetDecryptedSecret(key string) (string, error) {
storedValue, ok := r.SecureSettings[key]
if !ok {
return "", nil
}
decodeValue, err := base64.StdEncoding.DecodeString(storedValue)
if err != nil {
return "", err
}
decryptedValue, err := util.Decrypt(decodeValue, setting.SecretKey)
if err != nil {
return "", err
}
return string(decryptedValue), nil
}
type ReceiverType int
const (
GrafanaReceiverType ReceiverType = 1 << iota
AlertmanagerReceiverType
EmptyReceiverType = GrafanaReceiverType | AlertmanagerReceiverType
)
func (r ReceiverType) String() string {
switch r {
case GrafanaReceiverType:
return "grafana"
case AlertmanagerReceiverType:
return "alertmanager"
case EmptyReceiverType:
return "empty"
default:
return "unknown"
}
}
// Can determines whether a receiver type can implement another receiver type.
// This is useful as receivers with just names but no contact points
// are valid in all backends.
func (r ReceiverType) Can(other ReceiverType) bool { return r&other != 0 }
// MatchesBackend determines if a config payload can be sent to a particular backend type
func (r ReceiverType) MatchesBackend(backend Backend) error {
msg := func(backend Backend, receiver ReceiverType) error {
return fmt.Errorf(
"unexpected backend type (%s) for receiver type (%s)",
backend.String(),
receiver.String(),
)
}
var ok bool
switch backend {
case GrafanaBackend:
ok = r.Can(GrafanaReceiverType)
case AlertmanagerBackend:
ok = r.Can(AlertmanagerReceiverType)
default:
}
if !ok {
return msg(backend, r)
}
return nil
}
type GettableApiReceiver struct {
config.Receiver `yaml:",inline"`
GettableGrafanaReceivers `yaml:",inline"`
}
func (r *GettableApiReceiver) UnmarshalJSON(b []byte) error {
type plain GettableApiReceiver
if err := json.Unmarshal(b, (*plain)(r)); err != nil {
return err
}
hasGrafanaReceivers := len(r.GettableGrafanaReceivers.GrafanaManagedReceivers) > 0
if hasGrafanaReceivers {
if len(r.EmailConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager EmailConfigs & Grafana receivers together")
}
if len(r.PagerdutyConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager PagerdutyConfigs & Grafana receivers together")
}
if len(r.SlackConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager SlackConfigs & Grafana receivers together")
}
if len(r.WebhookConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager WebhookConfigs & Grafana receivers together")
}
if len(r.OpsGenieConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager OpsGenieConfigs & Grafana receivers together")
}
if len(r.WechatConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager WechatConfigs & Grafana receivers together")
}
if len(r.PushoverConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager PushoverConfigs & Grafana receivers together")
}
if len(r.VictorOpsConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager VictorOpsConfigs & Grafana receivers together")
}
}
return nil
}
func (r *GettableApiReceiver) Type() ReceiverType {
if len(r.GettableGrafanaReceivers.GrafanaManagedReceivers) > 0 {
return GrafanaReceiverType
}
return AlertmanagerReceiverType
}
type PostableApiReceiver struct {
config.Receiver `yaml:",inline"`
PostableGrafanaReceivers `yaml:",inline"`
}
func (r *PostableApiReceiver) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&r.PostableGrafanaReceivers); err != nil {
return err
}
if err := unmarshal(&r.Receiver); err != nil {
return err
}
return nil
}
func (r *PostableApiReceiver) UnmarshalJSON(b []byte) error {
type plain PostableApiReceiver
if err := json.Unmarshal(b, (*plain)(r)); err != nil {
return err
}
hasGrafanaReceivers := len(r.PostableGrafanaReceivers.GrafanaManagedReceivers) > 0
if hasGrafanaReceivers {
if len(r.EmailConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager EmailConfigs & Grafana receivers together")
}
if len(r.PagerdutyConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager PagerdutyConfigs & Grafana receivers together")
}
if len(r.SlackConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager SlackConfigs & Grafana receivers together")
}
if len(r.WebhookConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager WebhookConfigs & Grafana receivers together")
}
if len(r.OpsGenieConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager OpsGenieConfigs & Grafana receivers together")
}
if len(r.WechatConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager WechatConfigs & Grafana receivers together")
}
if len(r.PushoverConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager PushoverConfigs & Grafana receivers together")
}
if len(r.VictorOpsConfigs) > 0 {
return fmt.Errorf("cannot have both Alertmanager VictorOpsConfigs & Grafana receivers together")
}
}
return nil
}
func (r *PostableApiReceiver) Type() ReceiverType {
if len(r.PostableGrafanaReceivers.GrafanaManagedReceivers) > 0 {
return GrafanaReceiverType
}
cpy := r.Receiver
cpy.Name = ""
if reflect.ValueOf(cpy).IsZero() {
return EmptyReceiverType
}
return AlertmanagerReceiverType
}
type GettableGrafanaReceivers struct {
GrafanaManagedReceivers []*GettableGrafanaReceiver `yaml:"grafana_managed_receiver_configs,omitempty" json:"grafana_managed_receiver_configs,omitempty"`
}
type PostableGrafanaReceivers struct {
GrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:"grafana_managed_receiver_configs,omitempty" json:"grafana_managed_receiver_configs,omitempty"`
}
| pkg/services/ngalert/api/tooling/definitions/alertmanager.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.009136966429650784,
0.000583808112423867,
0.00016219945973716676,
0.00017252993711736053,
0.0014089049072936177
] |
{
"id": 2,
"code_window": [
"\trecipient := c.Params(\"Recipient\")\n",
"\tif recipient == apimodels.GrafanaBackend.String() {\n",
"\t\tif body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {\n",
"\t\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n",
"\t\t}\n",
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg)\n",
"\t}\n",
"\n",
"\tif body.Type() != apimodels.LoTexRulerBackend {\n",
"\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg, srv.log)\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 39
} | package dtos
type PlaylistDashboard struct {
Id int64 `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Uri string `json:"uri"`
Url string `json:"url"`
Order int `json:"order"`
}
type PlaylistDashboardsSlice []PlaylistDashboard
func (slice PlaylistDashboardsSlice) Len() int {
return len(slice)
}
func (slice PlaylistDashboardsSlice) Less(i, j int) bool {
return slice[i].Order < slice[j].Order
}
func (slice PlaylistDashboardsSlice) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
| pkg/api/dtos/playlist.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017258407024201006,
0.00016819439770188183,
0.00016065087402239442,
0.00017134821973741055,
0.000005357877853384707
] |
{
"id": 2,
"code_window": [
"\trecipient := c.Params(\"Recipient\")\n",
"\tif recipient == apimodels.GrafanaBackend.String() {\n",
"\t\tif body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {\n",
"\t\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n",
"\t\t}\n",
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg)\n",
"\t}\n",
"\n",
"\tif body.Type() != apimodels.LoTexRulerBackend {\n",
"\t\treturn ErrResp(http.StatusBadRequest, errors.New(\"unexpected payload\"), \"\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg, srv.log)\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 39
} | import { prompt } from 'inquirer';
import path from 'path';
import { promptConfirm } from '../utils/prompt';
import {
fetchTemplate,
formatPluginDetails,
getPluginIdFromName,
prepareJsonFiles,
printGrafanaTutorialsDetails,
promptPluginDetails,
promptPluginType,
removeGitFiles,
verifyGitExists,
} from './plugin/create';
import { Task, TaskRunner } from './task';
interface PluginCreateOptions {
name?: string;
}
const pluginCreateRunner: TaskRunner<PluginCreateOptions> = async ({ name }) => {
const destPath = path.resolve(process.cwd(), getPluginIdFromName(name || ''));
let pluginDetails;
// 1. Verifying if git exists in user's env as templates are cloned from git templates
await verifyGitExists();
// 2. Prompt plugin template
const { type } = await promptPluginType();
// 3. Fetch plugin template from GitHub
await fetchTemplate({ type, dest: destPath });
// 4. Prompt plugin details
do {
pluginDetails = await promptPluginDetails(name);
formatPluginDetails(pluginDetails);
} while ((await prompt<{ confirm: boolean }>(promptConfirm('confirm', 'Is that ok?'))).confirm === false);
// 5. Update json files (package.json, src/plugin.json)
await prepareJsonFiles({ type: type, pluginDetails, pluginPath: destPath });
// 6. Remove cloned repository .git dir
await removeGitFiles(destPath);
// 7. Promote Grafana Tutorials :)
printGrafanaTutorialsDetails(type);
};
export const pluginCreateTask = new Task<PluginCreateOptions>('plugin:create task', pluginCreateRunner);
| packages/grafana-toolkit/src/cli/tasks/plugin.create.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00019219928071834147,
0.00017460128583479673,
0.00016794665134511888,
0.00017144158482551575,
0.000008344291927642189
] |
{
"id": 3,
"code_window": [
"\t\treturn ErrResp(http.StatusBadRequest, err, \"invalid queries or expressions\")\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg}\n",
"\tevalResults, err := evaluator.QueriesAndExpressionsEval(c.SignedInUser.OrgId, cmd.Data, now, srv.DataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate queries and expressions\")\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg, Log: srv.log}\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 92
} | package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/util"
"github.com/pkg/errors"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3"
)
var searchRegex = regexp.MustCompile(`\{(\w+)\}`)
var NotImplementedResp = ErrResp(http.StatusNotImplemented, errors.New("endpoint not implemented"), "")
func toMacaronPath(path string) string {
return string(searchRegex.ReplaceAllFunc([]byte(path), func(s []byte) []byte {
m := string(s[1 : len(s)-1])
return []byte(fmt.Sprintf(":%s", m))
}))
}
func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) {
recipient := ctx.Params("Recipient")
if recipient == apimodels.GrafanaBackend.String() {
return apimodels.GrafanaBackend, nil
}
if datasourceID, err := strconv.ParseInt(recipient, 10, 64); err == nil {
if ds, err := cache.GetDatasource(datasourceID, ctx.SignedInUser, ctx.SkipCache); err == nil {
switch ds.Type {
case "loki", "prometheus":
return apimodels.LoTexRulerBackend, nil
case "alertmanager":
return apimodels.AlertmanagerBackend, nil
default:
return 0, fmt.Errorf("unexpected backend type (%v)", ds.Type)
}
}
}
return 0, fmt.Errorf("unexpected backend type (%v)", recipient)
}
// macaron unsafely asserts the http.ResponseWriter is an http.CloseNotifier, which will panic.
// Here we impl it, which will ensure this no longer happens, but neither will we take
// advantage cancelling upstream requests when the downstream has closed.
// NB: http.CloseNotifier is a deprecated ifc from before the context pkg.
type safeMacaronWrapper struct {
http.ResponseWriter
}
func (w *safeMacaronWrapper) CloseNotify() <-chan bool {
return make(chan bool)
}
// replacedResponseWriter overwrites the underlying responsewriter used by a *models.ReqContext.
// It's ugly because it needs to replace a value behind a few nested pointers.
func replacedResponseWriter(ctx *models.ReqContext) (*models.ReqContext, *response.NormalResponse) {
resp := response.CreateNormalResponse(make(http.Header), nil, 0)
cpy := *ctx
cpyMCtx := *cpy.Context
cpyMCtx.Resp = macaron.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{resp})
cpy.Context = &cpyMCtx
return &cpy, resp
}
type AlertingProxy struct {
DataProxy *datasourceproxy.DatasourceProxyService
}
// withReq proxies a different request
func (p *AlertingProxy) withReq(
ctx *models.ReqContext,
method string,
u *url.URL,
body io.Reader,
extractor func(*response.NormalResponse) (interface{}, error),
headers map[string]string,
) response.Response {
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
for h, v := range headers {
req.Header.Add(h, v)
}
newCtx, resp := replacedResponseWriter(ctx)
newCtx.Req.Request = req
p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64("Recipient"))
status := resp.Status()
if status >= 400 {
errMessage := string(resp.Body())
// if Content-Type is application/json
// and it is successfully decoded and contains a message
// return this as response error message
if strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json") {
var m map[string]interface{}
if err := json.Unmarshal(resp.Body(), &m); err == nil {
if message, ok := m["message"]; ok {
errMessage = message.(string)
}
}
} else if strings.HasPrefix(resp.Header().Get("Content-Type"), "text/html") {
// if Content-Type is text/html
// do not return the body
errMessage = "redacted html"
}
return ErrResp(status, errors.New(errMessage), "")
}
t, err := extractor(resp)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
b, err := json.Marshal(t)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(status, b)
}
func yamlExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "yaml") {
return nil, fmt.Errorf("unexpected content type from upstream. expected YAML, got %v", contentType)
}
decoder := yaml.NewDecoder(bytes.NewReader(resp.Body()))
decoder.KnownFields(true)
err := decoder.Decode(v)
return v, err
}
}
func jsonExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
if v == nil {
// json unmarshal expects a pointer
v = &map[string]interface{}{}
}
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "json") {
return nil, fmt.Errorf("unexpected content type from upstream. expected JSON, got %v", contentType)
}
return v, json.Unmarshal(resp.Body(), v)
}
}
func messageExtractor(resp *response.NormalResponse) (interface{}, error) {
return map[string]string{"message": string(resp.Body())}, nil
}
func validateCondition(c ngmodels.Condition, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) error {
if len(c.Data) == 0 {
return nil
}
refIDs, err := validateQueriesAndExpressions(c.Data, user, skipCache, datasourceCache)
if err != nil {
return err
}
t := make([]string, 0, len(refIDs))
for refID := range refIDs {
t = append(t, refID)
}
if _, ok := refIDs[c.Condition]; !ok {
return fmt.Errorf("condition %s not found in any query or expression: it should be one of: [%s]", c.Condition, strings.Join(t, ","))
}
return nil
}
func validateQueriesAndExpressions(data []ngmodels.AlertQuery, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) (map[string]struct{}, error) {
refIDs := make(map[string]struct{})
if len(data) == 0 {
return nil, nil
}
for _, query := range data {
datasourceUID, err := query.GetDatasource()
if err != nil {
return nil, err
}
isExpression, err := query.IsExpression()
if err != nil {
return nil, err
}
if isExpression {
refIDs[query.RefID] = struct{}{}
continue
}
_, err = datasourceCache.GetDatasourceByUID(datasourceUID, user, skipCache)
if err != nil {
return nil, fmt.Errorf("invalid query %s: %w: %s", query.RefID, err, datasourceUID)
}
refIDs[query.RefID] = struct{}{}
}
return refIDs, nil
}
func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {
evalCond := ngmodels.Condition{
Condition: cmd.Condition,
OrgID: c.SignedInUser.OrgId,
Data: cmd.Data,
}
if err := validateCondition(evalCond, c.SignedInUser, c.SkipCache, datasourceCache); err != nil {
return ErrResp(http.StatusBadRequest, err, "invalid condition")
}
now := cmd.Now
if now.IsZero() {
now = timeNow()
}
evaluator := eval.Evaluator{Cfg: cfg}
evalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "Failed to evaluate conditions")
}
frame := evalResults.AsDataFrame()
return response.JSONStreaming(http.StatusOK, util.DynMap{
"instances": []*data.Frame{&frame},
})
}
// ErrorResp creates a response with a visible error
func ErrResp(status int, err error, msg string, args ...interface{}) *response.NormalResponse {
if msg != "" {
err = errors.WithMessagef(err, msg, args...)
}
return response.Error(status, err.Error(), nil)
}
| pkg/services/ngalert/api/util.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9950180053710938,
0.055118028074502945,
0.00016119390784297138,
0.00017409806605428457,
0.2037172168493271
] |
{
"id": 3,
"code_window": [
"\t\treturn ErrResp(http.StatusBadRequest, err, \"invalid queries or expressions\")\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg}\n",
"\tevalResults, err := evaluator.QueriesAndExpressionsEval(c.SignedInUser.OrgId, cmd.Data, now, srv.DataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate queries and expressions\")\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg, Log: srv.log}\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 92
} | import { urlUtil, UrlQueryMap } from '@grafana/data';
import { RuleFilterState } from 'app/types/unified-alerting';
import { ALERTMANAGER_NAME_QUERY_KEY } from './constants';
export function createExploreLink(dataSourceName: string, query: string) {
return urlUtil.renderUrl('explore', {
left: JSON.stringify([
'now-1h',
'now',
dataSourceName,
{ datasource: dataSourceName, expr: query },
{ ui: [true, true, true, 'none'] },
]),
});
}
// used to hash rules
export function hash(value: string): number {
let hash = 0;
if (value.length === 0) {
return hash;
}
for (var i = 0; i < value.length; i++) {
var char = value.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
export function arrayToRecord(items: Array<{ key: string; value: string }>): Record<string, string> {
return items.reduce<Record<string, string>>((rec, { key, value }) => {
rec[key] = value;
return rec;
}, {});
}
export const getFiltersFromUrlParams = (queryParams: UrlQueryMap): RuleFilterState => {
const queryString = queryParams['queryString'] === undefined ? undefined : String(queryParams['queryString']);
const alertState = queryParams['alertState'] === undefined ? undefined : String(queryParams['alertState']);
const dataSource = queryParams['dataSource'] === undefined ? undefined : String(queryParams['dataSource']);
return { queryString, alertState, dataSource };
};
export function recordToArray(record: Record<string, string>): Array<{ key: string; value: string }> {
return Object.entries(record).map(([key, value]) => ({ key, value }));
}
export function makeAMLink(path: string, alertManagerName?: string): string {
return `${path}${alertManagerName ? `?${ALERTMANAGER_NAME_QUERY_KEY}=${encodeURIComponent(alertManagerName)}` : ''}`;
}
| public/app/features/alerting/unified/utils/misc.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017559717525728047,
0.00017325172666460276,
0.00017154209490399808,
0.00017325388034805655,
0.0000014367983567353804
] |
{
"id": 3,
"code_window": [
"\t\treturn ErrResp(http.StatusBadRequest, err, \"invalid queries or expressions\")\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg}\n",
"\tevalResults, err := evaluator.QueriesAndExpressionsEval(c.SignedInUser.OrgId, cmd.Data, now, srv.DataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate queries and expressions\")\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg, Log: srv.log}\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 92
} | import React, { useState } from 'react';
import { DashboardModel } from '../../state/DashboardModel';
import { AnnotationSettingsEdit, AnnotationSettingsList } from '../AnnotationSettings';
import { newAnnotation } from '../AnnotationSettings/AnnotationSettingsEdit';
import { DashboardSettingsHeader } from './DashboardSettingsHeader';
interface Props {
dashboard: DashboardModel;
}
export const AnnotationsSettings: React.FC<Props> = ({ dashboard }) => {
const [editIdx, setEditIdx] = useState<number | null>(null);
const onGoBack = () => {
setEditIdx(null);
};
const onNew = () => {
dashboard.annotations.list = [...dashboard.annotations.list, { ...newAnnotation }];
setEditIdx(dashboard.annotations.list.length - 1);
};
const onEdit = (idx: number) => {
setEditIdx(idx);
};
const isEditing = editIdx !== null;
return (
<>
<DashboardSettingsHeader title="Annotations" onGoBack={onGoBack} isEditing={isEditing} />
{!isEditing && <AnnotationSettingsList dashboard={dashboard} onNew={onNew} onEdit={onEdit} />}
{isEditing && <AnnotationSettingsEdit dashboard={dashboard} editIdx={editIdx!} />}
</>
);
};
| public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017829560965765268,
0.00017707327788230032,
0.00017504984862171113,
0.00017747381934896111,
0.0000012690400126302848
] |
{
"id": 3,
"code_window": [
"\t\treturn ErrResp(http.StatusBadRequest, err, \"invalid queries or expressions\")\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg}\n",
"\tevalResults, err := evaluator.QueriesAndExpressionsEval(c.SignedInUser.OrgId, cmd.Data, now, srv.DataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate queries and expressions\")\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: srv.Cfg, Log: srv.log}\n"
],
"file_path": "pkg/services/ngalert/api/api_testing.go",
"type": "replace",
"edit_start_line_idx": 92
} | package sqlstore
import (
"bytes"
"strings"
"github.com/grafana/grafana/pkg/models"
)
type SQLBuilder struct {
sql bytes.Buffer
params []interface{}
}
func (sb *SQLBuilder) Write(sql string, params ...interface{}) {
sb.sql.WriteString(sql)
if len(params) > 0 {
sb.params = append(sb.params, params...)
}
}
func (sb *SQLBuilder) GetSQLString() string {
return sb.sql.String()
}
func (sb *SQLBuilder) GetParams() []interface{} {
return sb.params
}
func (sb *SQLBuilder) AddParams(params ...interface{}) {
sb.params = append(sb.params, params...)
}
func (sb *SQLBuilder) WriteDashboardPermissionFilter(user *models.SignedInUser, permission models.PermissionType) {
if user.OrgRole == models.ROLE_ADMIN {
return
}
okRoles := []interface{}{user.OrgRole}
if user.OrgRole == models.ROLE_EDITOR {
okRoles = append(okRoles, models.ROLE_VIEWER)
}
falseStr := dialect.BooleanStr(false)
sb.sql.WriteString(` AND
(
dashboard.id IN (
SELECT distinct DashboardId from (
SELECT d.id AS DashboardId
FROM dashboard AS d
LEFT JOIN dashboard AS folder on folder.id = d.folder_id
LEFT JOIN dashboard_acl AS da ON
da.dashboard_id = d.id OR
da.dashboard_id = d.folder_id
LEFT JOIN team_member as ugm on ugm.team_id = da.team_id
WHERE
d.org_id = ? AND
da.permission >= ? AND
(
da.user_id = ? OR
ugm.user_id = ? OR
da.role IN (?` + strings.Repeat(",?", len(okRoles)-1) + `)
)
UNION
SELECT d.id AS DashboardId
FROM dashboard AS d
LEFT JOIN dashboard AS folder on folder.id = d.folder_id
LEFT JOIN dashboard_acl AS da ON
(
-- include default permissions -->
da.org_id = -1 AND (
(folder.id IS NOT NULL AND folder.has_acl = ` + falseStr + `) OR
(folder.id IS NULL AND d.has_acl = ` + falseStr + `)
)
)
WHERE
d.org_id = ? AND
da.permission >= ? AND
(
da.user_id = ? OR
da.role IN (?` + strings.Repeat(",?", len(okRoles)-1) + `)
)
) AS a
)
)`)
sb.params = append(sb.params, user.OrgId, permission, user.UserId, user.UserId)
sb.params = append(sb.params, okRoles...)
sb.params = append(sb.params, user.OrgId, permission, user.UserId)
sb.params = append(sb.params, okRoles...)
}
| pkg/services/sqlstore/sqlbuilder.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0003865209873765707,
0.00019266492745373398,
0.00016420471365563571,
0.0001705391623545438,
0.00006490229861810803
] |
{
"id": 4,
"code_window": [
"\t\"strings\"\n",
"\n",
"\t\"github.com/grafana/grafana-plugin-sdk-go/data\"\n",
"\t\"github.com/grafana/grafana/pkg/api/response\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasourceproxy\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasources\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "add",
"edit_start_line_idx": 15
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.013102327473461628,
0.0005171717493794858,
0.00016123201930895448,
0.00016971764853224158,
0.0019470278639346361
] |
{
"id": 4,
"code_window": [
"\t\"strings\"\n",
"\n",
"\t\"github.com/grafana/grafana-plugin-sdk-go/data\"\n",
"\t\"github.com/grafana/grafana/pkg/api/response\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasourceproxy\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasources\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "add",
"edit_start_line_idx": 15
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E3E3E3;}
</style>
<g>
<path class="st0" d="M54.1,40.6c0,0-0.1-0.1-0.2-0.1c-0.9-0.5-0.7-1.9-0.5-2.6c0.6-0.7,1.3-1.8,1.5-3.6c0.1-0.5,0.3-1,0.6-1.3
c0.6-0.8,0.9-1.8,0.9-2.8c0-0.8-0.2-1.5-0.5-2.1c-0.1-0.1-0.2-0.2-0.3-0.4c0.4-1.1,0.9-2.8,0.5-4.7c-0.8-3.2-5-4.6-8.6-4.6
c-7.6,0-8.3,3.8-8.5,4.5c-0.4,1.7-0.1,3.4,0.4,4.7c-0.1,0.1-0.2,0.3-0.3,0.4c-0.4,0.6-0.6,1.3-0.6,2.1c0,1,0.3,2,0.9,2.8
c0.3,0.4,0.5,0.9,0.6,1.3c0.3,1.8,0.9,3,1.6,3.7c0.1,0.2,0.1,0.5,0.1,0.7c3.5,2.4,3.9,4,3.9,5.4V51c0,2.7-1.3,5.2-3.2,6.8h4.9h8.1
h3.5c2.9,0,5.2-2.3,5.2-5.2v-5.4C64,46.6,64,44.8,54.1,40.6z"/>
<path class="st0" d="M43.5,44c0-0.9,0-3.3-13-8.7c-0.1,0-0.1-0.1-0.3-0.2c-1.2-0.6-0.9-2.5-0.7-3.5c0.8-0.9,1.7-2.4,2-4.7
c0.1-0.6,0.3-1.2,0.7-1.8c0.7-1,1.1-2.4,1.1-3.7c0-1-0.2-2-0.7-2.7c-0.1-0.2-0.2-0.3-0.3-0.5c0.6-1.5,1.2-3.7,0.6-6.1
c-1-4.2-6.5-6.1-11.2-6.1c-4.3,0-7.5,1.5-8.8,3.9c-1.1,0.6-1.8,1.4-2.1,2c-1,2-0.3,4.4,0.3,6.1c-0.2,0.2-0.3,0.3-0.4,0.5
c-0.5,0.7-0.7,1.7-0.7,2.8c0,1.3,0.4,2.7,1.1,3.6c0.4,0.5,0.6,1.1,0.7,1.8c0.4,2.4,1.2,3.9,2.1,4.8c0.2,1,0.5,2.8-0.7,3.4
c-0.1,0.1-0.2,0.1-0.3,0.2C0,40.7,0,43.1,0,44V51c0,3.8,3.1,6.8,6.8,6.8h14.7h10.6H36h0.6c3.8,0,6.8-3.1,6.8-6.8V44z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_team.svg | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017186069453600794,
0.00016904396761674434,
0.0001666684984229505,
0.00016860273899510503,
0.0000021425441900646547
] |
{
"id": 4,
"code_window": [
"\t\"strings\"\n",
"\n",
"\t\"github.com/grafana/grafana-plugin-sdk-go/data\"\n",
"\t\"github.com/grafana/grafana/pkg/api/response\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasourceproxy\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasources\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "add",
"edit_start_line_idx": 15
} | declare var global: NodeJS.Global;
(global as any).requestAnimationFrame = (callback: any) => {
setTimeout(callback, 0);
};
(Promise.prototype as any).finally = function (onFinally: any) {
return this.then(
/* onFulfilled */
(res: any) => Promise.resolve(onFinally()).then(() => res),
/* onRejected */
(err: any) =>
Promise.resolve(onFinally()).then(() => {
throw err;
})
);
};
| public/test/jest-shim.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017102387209888548,
0.00017080985708162189,
0.00017059585661627352,
0.00017080985708162189,
2.140077413059771e-7
] |
{
"id": 4,
"code_window": [
"\t\"strings\"\n",
"\n",
"\t\"github.com/grafana/grafana-plugin-sdk-go/data\"\n",
"\t\"github.com/grafana/grafana/pkg/api/response\"\n",
"\t\"github.com/grafana/grafana/pkg/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasourceproxy\"\n",
"\t\"github.com/grafana/grafana/pkg/services/datasources\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "add",
"edit_start_line_idx": 15
} | import { ComponentType } from 'react';
import { MatcherConfig, FieldConfig, Field, DataFrame, TimeZone } from '../types';
import { InterpolateFunction } from './panel';
import { StandardEditorProps, FieldConfigOptionsRegistry, StandardEditorContext } from '../field';
import { OptionsEditorItem } from './OptionsUIRegistryBuilder';
import { OptionEditorConfig } from './options';
import { GrafanaTheme2 } from '../themes';
export interface DynamicConfigValue {
id: string;
value?: any;
}
export interface ConfigOverrideRule {
matcher: MatcherConfig;
properties: DynamicConfigValue[];
}
/**
* Describes config override rules created when interacting with Grafana.
*
* @internal
*/
export interface SystemConfigOverrideRule extends ConfigOverrideRule {
__systemRef: string;
}
/**
* Guard functionality to check if an override rule is of type {@link SystemConfigOverrideRule}.
* It will only return true if the {@link SystemConfigOverrideRule} has the passed systemRef.
*
* @param ref system override reference
* @internal
*/
export function isSystemOverrideWithRef<T extends SystemConfigOverrideRule>(ref: string) {
return (override: ConfigOverrideRule): override is T => {
return (override as T)?.__systemRef === ref;
};
}
/**
* Guard functionality to check if an override rule is of type {@link SystemConfigOverrideRule}.
* It will return true if the {@link SystemConfigOverrideRule} has any systemRef set.
*
* @internal
*/
export const isSystemOverride = (override: ConfigOverrideRule): override is SystemConfigOverrideRule => {
return typeof (override as SystemConfigOverrideRule)?.__systemRef === 'string';
};
export interface FieldConfigSource<TOptions extends object = any> {
// Defaults applied to all numeric fields
defaults: FieldConfig<TOptions>;
// Rules to override individual values
overrides: ConfigOverrideRule[];
}
export interface FieldOverrideContext extends StandardEditorContext<any> {
field?: Field;
dataFrameIndex?: number; // The index for the selected field frame
}
export interface FieldConfigEditorProps<TValue, TSettings>
extends Omit<StandardEditorProps<TValue, TSettings>, 'item'> {
item: FieldConfigPropertyItem<any, TValue, TSettings>; // The property info
value: TValue;
context: FieldOverrideContext;
onChange: (value?: TValue) => void;
}
export interface FieldOverrideEditorProps<TValue, TSettings> extends Omit<StandardEditorProps<TValue>, 'item'> {
item: FieldConfigPropertyItem<TValue, TSettings>;
context: FieldOverrideContext;
}
export interface FieldConfigEditorConfig<TOptions, TSettings = any, TValue = any>
extends OptionEditorConfig<TOptions, TSettings, TValue> {
/**
* Function that allows specifying whether or not this field config should apply to a given field.
* @param field
*/
shouldApply?: (field: Field) => boolean;
/** Indicates that option shoukd not be available in the Field config tab */
hideFromDefaults?: boolean;
/** Indicates that option should not be available for the overrides */
hideFromOverrides?: boolean;
}
export interface FieldConfigPropertyItem<TOptions = any, TValue = any, TSettings extends {} = any>
extends OptionsEditorItem<TOptions, TSettings, FieldConfigEditorProps<TValue, TSettings>, TValue> {
// An editor that can be filled in with context info (template variables etc)
override: ComponentType<FieldOverrideEditorProps<TValue, TSettings>>;
/** true for plugin field config properties */
isCustom?: boolean;
/** Hides option from the Field config tab */
hideFromDefaults?: boolean;
/** Indicates that option should not be available for the overrides */
hideFromOverrides?: boolean;
/** Convert the override value to a well typed value */
process: (value: any, context: FieldOverrideContext, settings?: TSettings) => TValue | undefined | null;
/** Checks if field should be processed */
shouldApply: (field: Field) => boolean;
}
export interface ApplyFieldOverrideOptions {
data?: DataFrame[];
fieldConfig: FieldConfigSource;
fieldConfigRegistry?: FieldConfigOptionsRegistry;
replaceVariables: InterpolateFunction;
theme: GrafanaTheme2;
timeZone?: TimeZone;
}
export enum FieldConfigProperty {
Unit = 'unit',
Min = 'min',
Max = 'max',
Decimals = 'decimals',
DisplayName = 'displayName',
NoValue = 'noValue',
Thresholds = 'thresholds',
Mappings = 'mappings',
Links = 'links',
Color = 'color',
}
| packages/grafana-data/src/types/fieldOverrides.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001738414284773171,
0.00016963225789368153,
0.00016353859973605722,
0.00016997032798826694,
0.0000031241834221873432
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\treturn refIDs, nil\n",
"}\n",
"\n",
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {\n",
"\tevalCond := ngmodels.Condition{\n",
"\t\tCondition: cmd.Condition,\n",
"\t\tOrgID: c.SignedInUser.OrgId,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg, log log.Logger) response.Response {\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 224
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9272026419639587,
0.06034205108880997,
0.00016518021584488451,
0.0003295876085758209,
0.21698489785194397
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\treturn refIDs, nil\n",
"}\n",
"\n",
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {\n",
"\tevalCond := ngmodels.Condition{\n",
"\t\tCondition: cmd.Condition,\n",
"\t\tOrgID: c.SignedInUser.OrgId,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg, log log.Logger) response.Response {\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 224
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export { default } from './DraggableManagerDemo';
| packages/jaeger-ui-components/src/utils/DraggableManager/demo/index.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001769488153513521,
0.00017509941244497895,
0.00017324999498669058,
0.00017509941244497895,
0.0000018494101823307574
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\treturn refIDs, nil\n",
"}\n",
"\n",
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {\n",
"\tevalCond := ngmodels.Condition{\n",
"\t\tCondition: cmd.Condition,\n",
"\t\tOrgID: c.SignedInUser.OrgId,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg, log log.Logger) response.Response {\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 224
} | package api
import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
func GetOrgQuotas(c *models.ReqContext) response.Response {
if !setting.Quota.Enabled {
return response.Error(404, "Quotas not enabled", nil)
}
query := models.GetOrgQuotasQuery{OrgId: c.ParamsInt64(":orgId")}
if err := bus.Dispatch(&query); err != nil {
return response.Error(500, "Failed to get org quotas", err)
}
return response.JSON(200, query.Result)
}
func UpdateOrgQuota(c *models.ReqContext, cmd models.UpdateOrgQuotaCmd) response.Response {
if !setting.Quota.Enabled {
return response.Error(404, "Quotas not enabled", nil)
}
cmd.OrgId = c.ParamsInt64(":orgId")
cmd.Target = c.Params(":target")
if _, ok := setting.Quota.Org.ToMap()[cmd.Target]; !ok {
return response.Error(404, "Invalid quota target", nil)
}
if err := bus.Dispatch(&cmd); err != nil {
return response.Error(500, "Failed to update org quotas", err)
}
return response.Success("Organization quota updated")
}
func GetUserQuotas(c *models.ReqContext) response.Response {
if !setting.Quota.Enabled {
return response.Error(404, "Quotas not enabled", nil)
}
query := models.GetUserQuotasQuery{UserId: c.ParamsInt64(":id")}
if err := bus.Dispatch(&query); err != nil {
return response.Error(500, "Failed to get org quotas", err)
}
return response.JSON(200, query.Result)
}
func UpdateUserQuota(c *models.ReqContext, cmd models.UpdateUserQuotaCmd) response.Response {
if !setting.Quota.Enabled {
return response.Error(404, "Quotas not enabled", nil)
}
cmd.UserId = c.ParamsInt64(":id")
cmd.Target = c.Params(":target")
if _, ok := setting.Quota.User.ToMap()[cmd.Target]; !ok {
return response.Error(404, "Invalid quota target", nil)
}
if err := bus.Dispatch(&cmd); err != nil {
return response.Error(500, "Failed to update org quotas", err)
}
return response.Success("Organization quota updated")
}
| pkg/api/quota.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.002464618533849716,
0.001053558778949082,
0.00018038849520962685,
0.0006185345118865371,
0.0008945536683313549
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\treturn refIDs, nil\n",
"}\n",
"\n",
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {\n",
"\tevalCond := ngmodels.Condition{\n",
"\t\tCondition: cmd.Condition,\n",
"\t\tOrgID: c.SignedInUser.OrgId,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg, log log.Logger) response.Response {\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 224
} | /* WRONG CONFIG ON PURPOSE - DO NOT COPY THIS */
module.exports.config = {
name: 'test',
};
| packages/grafana-toolkit/src/config/mocks/webpack/unsupportedOverride/webpack.config.js | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017185397155117244,
0.00017185397155117244,
0.00017185397155117244,
0.00017185397155117244,
0
] |
{
"id": 6,
"code_window": [
"\tnow := cmd.Now\n",
"\tif now.IsZero() {\n",
"\t\tnow = timeNow()\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: cfg}\n",
"\tevalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate conditions\")\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: cfg, Log: log}\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 239
} | package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/util"
"github.com/pkg/errors"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3"
)
var searchRegex = regexp.MustCompile(`\{(\w+)\}`)
var NotImplementedResp = ErrResp(http.StatusNotImplemented, errors.New("endpoint not implemented"), "")
func toMacaronPath(path string) string {
return string(searchRegex.ReplaceAllFunc([]byte(path), func(s []byte) []byte {
m := string(s[1 : len(s)-1])
return []byte(fmt.Sprintf(":%s", m))
}))
}
func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) {
recipient := ctx.Params("Recipient")
if recipient == apimodels.GrafanaBackend.String() {
return apimodels.GrafanaBackend, nil
}
if datasourceID, err := strconv.ParseInt(recipient, 10, 64); err == nil {
if ds, err := cache.GetDatasource(datasourceID, ctx.SignedInUser, ctx.SkipCache); err == nil {
switch ds.Type {
case "loki", "prometheus":
return apimodels.LoTexRulerBackend, nil
case "alertmanager":
return apimodels.AlertmanagerBackend, nil
default:
return 0, fmt.Errorf("unexpected backend type (%v)", ds.Type)
}
}
}
return 0, fmt.Errorf("unexpected backend type (%v)", recipient)
}
// macaron unsafely asserts the http.ResponseWriter is an http.CloseNotifier, which will panic.
// Here we impl it, which will ensure this no longer happens, but neither will we take
// advantage cancelling upstream requests when the downstream has closed.
// NB: http.CloseNotifier is a deprecated ifc from before the context pkg.
type safeMacaronWrapper struct {
http.ResponseWriter
}
func (w *safeMacaronWrapper) CloseNotify() <-chan bool {
return make(chan bool)
}
// replacedResponseWriter overwrites the underlying responsewriter used by a *models.ReqContext.
// It's ugly because it needs to replace a value behind a few nested pointers.
func replacedResponseWriter(ctx *models.ReqContext) (*models.ReqContext, *response.NormalResponse) {
resp := response.CreateNormalResponse(make(http.Header), nil, 0)
cpy := *ctx
cpyMCtx := *cpy.Context
cpyMCtx.Resp = macaron.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{resp})
cpy.Context = &cpyMCtx
return &cpy, resp
}
type AlertingProxy struct {
DataProxy *datasourceproxy.DatasourceProxyService
}
// withReq proxies a different request
func (p *AlertingProxy) withReq(
ctx *models.ReqContext,
method string,
u *url.URL,
body io.Reader,
extractor func(*response.NormalResponse) (interface{}, error),
headers map[string]string,
) response.Response {
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
for h, v := range headers {
req.Header.Add(h, v)
}
newCtx, resp := replacedResponseWriter(ctx)
newCtx.Req.Request = req
p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64("Recipient"))
status := resp.Status()
if status >= 400 {
errMessage := string(resp.Body())
// if Content-Type is application/json
// and it is successfully decoded and contains a message
// return this as response error message
if strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json") {
var m map[string]interface{}
if err := json.Unmarshal(resp.Body(), &m); err == nil {
if message, ok := m["message"]; ok {
errMessage = message.(string)
}
}
} else if strings.HasPrefix(resp.Header().Get("Content-Type"), "text/html") {
// if Content-Type is text/html
// do not return the body
errMessage = "redacted html"
}
return ErrResp(status, errors.New(errMessage), "")
}
t, err := extractor(resp)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
b, err := json.Marshal(t)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(status, b)
}
func yamlExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "yaml") {
return nil, fmt.Errorf("unexpected content type from upstream. expected YAML, got %v", contentType)
}
decoder := yaml.NewDecoder(bytes.NewReader(resp.Body()))
decoder.KnownFields(true)
err := decoder.Decode(v)
return v, err
}
}
func jsonExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
if v == nil {
// json unmarshal expects a pointer
v = &map[string]interface{}{}
}
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "json") {
return nil, fmt.Errorf("unexpected content type from upstream. expected JSON, got %v", contentType)
}
return v, json.Unmarshal(resp.Body(), v)
}
}
func messageExtractor(resp *response.NormalResponse) (interface{}, error) {
return map[string]string{"message": string(resp.Body())}, nil
}
func validateCondition(c ngmodels.Condition, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) error {
if len(c.Data) == 0 {
return nil
}
refIDs, err := validateQueriesAndExpressions(c.Data, user, skipCache, datasourceCache)
if err != nil {
return err
}
t := make([]string, 0, len(refIDs))
for refID := range refIDs {
t = append(t, refID)
}
if _, ok := refIDs[c.Condition]; !ok {
return fmt.Errorf("condition %s not found in any query or expression: it should be one of: [%s]", c.Condition, strings.Join(t, ","))
}
return nil
}
func validateQueriesAndExpressions(data []ngmodels.AlertQuery, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) (map[string]struct{}, error) {
refIDs := make(map[string]struct{})
if len(data) == 0 {
return nil, nil
}
for _, query := range data {
datasourceUID, err := query.GetDatasource()
if err != nil {
return nil, err
}
isExpression, err := query.IsExpression()
if err != nil {
return nil, err
}
if isExpression {
refIDs[query.RefID] = struct{}{}
continue
}
_, err = datasourceCache.GetDatasourceByUID(datasourceUID, user, skipCache)
if err != nil {
return nil, fmt.Errorf("invalid query %s: %w: %s", query.RefID, err, datasourceUID)
}
refIDs[query.RefID] = struct{}{}
}
return refIDs, nil
}
func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {
evalCond := ngmodels.Condition{
Condition: cmd.Condition,
OrgID: c.SignedInUser.OrgId,
Data: cmd.Data,
}
if err := validateCondition(evalCond, c.SignedInUser, c.SkipCache, datasourceCache); err != nil {
return ErrResp(http.StatusBadRequest, err, "invalid condition")
}
now := cmd.Now
if now.IsZero() {
now = timeNow()
}
evaluator := eval.Evaluator{Cfg: cfg}
evalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "Failed to evaluate conditions")
}
frame := evalResults.AsDataFrame()
return response.JSONStreaming(http.StatusOK, util.DynMap{
"instances": []*data.Frame{&frame},
})
}
// ErrorResp creates a response with a visible error
func ErrResp(status int, err error, msg string, args ...interface{}) *response.NormalResponse {
if msg != "" {
err = errors.WithMessagef(err, msg, args...)
}
return response.Error(status, err.Error(), nil)
}
| pkg/services/ngalert/api/util.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9973094463348389,
0.07717496901750565,
0.00016049791884142905,
0.0001718616986181587,
0.26561641693115234
] |
{
"id": 6,
"code_window": [
"\tnow := cmd.Now\n",
"\tif now.IsZero() {\n",
"\t\tnow = timeNow()\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: cfg}\n",
"\tevalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate conditions\")\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: cfg, Log: log}\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 239
} | export enum TimeOptions {
seconds = 's',
minutes = 'm',
hours = 'h',
days = 'd',
weeks = 'w',
}
| public/app/features/alerting/unified/types/time.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001716347032925114,
0.0001716347032925114,
0.0001716347032925114,
0.0001716347032925114,
0
] |
{
"id": 6,
"code_window": [
"\tnow := cmd.Now\n",
"\tif now.IsZero() {\n",
"\t\tnow = timeNow()\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: cfg}\n",
"\tevalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate conditions\")\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: cfg, Log: log}\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 239
} | .grafana-info-box {
position: relative;
padding: $space-lg;
background-color: $empty-list-cta-bg;
border-left: 3px solid $info-box-border-color;
margin-bottom: $space-md;
margin-right: $space-xs;
box-shadow: $card-shadow;
flex-grow: 1;
h5 {
margin-bottom: $spacer;
}
ul {
padding-left: $spacer * 1.5;
}
code {
@include font-family-monospace();
font-size: $font-size-base - 2;
background-color: $code-tag-bg;
color: $text-color;
border: 1px solid $code-tag-border;
border-radius: 4px;
}
p:last-child {
margin-bottom: 0;
}
a {
@extend .external-link;
}
&--max-lg {
max-width: map-get($grid-breakpoints, 'lg');
}
}
.grafana-info-box__close {
text-align: center;
display: block;
color: $link-color !important;
height: 0;
position: relative;
top: -9px;
}
| public/sass/components/_infobox.scss | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017993550864048302,
0.00017819477943703532,
0.00017583642329555005,
0.00017856476188171655,
0.0000013706751360587077
] |
{
"id": 6,
"code_window": [
"\tnow := cmd.Now\n",
"\tif now.IsZero() {\n",
"\t\tnow = timeNow()\n",
"\t}\n",
"\n",
"\tevaluator := eval.Evaluator{Cfg: cfg}\n",
"\tevalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn ErrResp(http.StatusBadRequest, err, \"Failed to evaluate conditions\")\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tevaluator := eval.Evaluator{Cfg: cfg, Log: log}\n"
],
"file_path": "pkg/services/ngalert/api/util.go",
"type": "replace",
"edit_start_line_idx": 239
} | import React, { HTMLAttributes, SFC } from 'react';
import { css, cx } from '@emotion/css';
import { GrafanaTheme } from '@grafana/data';
import { Spinner } from '../Spinner/Spinner';
import { useStyles } from '../../themes';
/**
* @public
*/
export interface LoadingPlaceholderProps extends HTMLAttributes<HTMLDivElement> {
text: string;
}
/**
* @public
*/
export const LoadingPlaceholder: SFC<LoadingPlaceholderProps> = ({ text, className, ...rest }) => {
const styles = useStyles(getStyles);
return (
<div className={cx(styles.container, className)} {...rest}>
{text} <Spinner inline={true} />
</div>
);
};
const getStyles = (theme: GrafanaTheme) => {
return {
container: css`
margin-bottom: ${theme.spacing.xl};
`,
};
};
| packages/grafana-ui/src/components/LoadingPlaceholder/LoadingPlaceholder.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017818190099205822,
0.0001774225092958659,
0.00017618417041376233,
0.0001776619756128639,
7.888547770562582e-7
] |
{
"id": 7,
"code_window": [
"\n",
"import (\n",
"\t\"context\"\n",
"\t\"fmt\"\n",
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"runtime/debug\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 7
} | package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/util"
"github.com/pkg/errors"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3"
)
var searchRegex = regexp.MustCompile(`\{(\w+)\}`)
var NotImplementedResp = ErrResp(http.StatusNotImplemented, errors.New("endpoint not implemented"), "")
func toMacaronPath(path string) string {
return string(searchRegex.ReplaceAllFunc([]byte(path), func(s []byte) []byte {
m := string(s[1 : len(s)-1])
return []byte(fmt.Sprintf(":%s", m))
}))
}
func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) {
recipient := ctx.Params("Recipient")
if recipient == apimodels.GrafanaBackend.String() {
return apimodels.GrafanaBackend, nil
}
if datasourceID, err := strconv.ParseInt(recipient, 10, 64); err == nil {
if ds, err := cache.GetDatasource(datasourceID, ctx.SignedInUser, ctx.SkipCache); err == nil {
switch ds.Type {
case "loki", "prometheus":
return apimodels.LoTexRulerBackend, nil
case "alertmanager":
return apimodels.AlertmanagerBackend, nil
default:
return 0, fmt.Errorf("unexpected backend type (%v)", ds.Type)
}
}
}
return 0, fmt.Errorf("unexpected backend type (%v)", recipient)
}
// macaron unsafely asserts the http.ResponseWriter is an http.CloseNotifier, which will panic.
// Here we impl it, which will ensure this no longer happens, but neither will we take
// advantage cancelling upstream requests when the downstream has closed.
// NB: http.CloseNotifier is a deprecated ifc from before the context pkg.
type safeMacaronWrapper struct {
http.ResponseWriter
}
func (w *safeMacaronWrapper) CloseNotify() <-chan bool {
return make(chan bool)
}
// replacedResponseWriter overwrites the underlying responsewriter used by a *models.ReqContext.
// It's ugly because it needs to replace a value behind a few nested pointers.
func replacedResponseWriter(ctx *models.ReqContext) (*models.ReqContext, *response.NormalResponse) {
resp := response.CreateNormalResponse(make(http.Header), nil, 0)
cpy := *ctx
cpyMCtx := *cpy.Context
cpyMCtx.Resp = macaron.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{resp})
cpy.Context = &cpyMCtx
return &cpy, resp
}
type AlertingProxy struct {
DataProxy *datasourceproxy.DatasourceProxyService
}
// withReq proxies a different request
func (p *AlertingProxy) withReq(
ctx *models.ReqContext,
method string,
u *url.URL,
body io.Reader,
extractor func(*response.NormalResponse) (interface{}, error),
headers map[string]string,
) response.Response {
req, err := http.NewRequest(method, u.String(), body)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
for h, v := range headers {
req.Header.Add(h, v)
}
newCtx, resp := replacedResponseWriter(ctx)
newCtx.Req.Request = req
p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64("Recipient"))
status := resp.Status()
if status >= 400 {
errMessage := string(resp.Body())
// if Content-Type is application/json
// and it is successfully decoded and contains a message
// return this as response error message
if strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json") {
var m map[string]interface{}
if err := json.Unmarshal(resp.Body(), &m); err == nil {
if message, ok := m["message"]; ok {
errMessage = message.(string)
}
}
} else if strings.HasPrefix(resp.Header().Get("Content-Type"), "text/html") {
// if Content-Type is text/html
// do not return the body
errMessage = "redacted html"
}
return ErrResp(status, errors.New(errMessage), "")
}
t, err := extractor(resp)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
b, err := json.Marshal(t)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(status, b)
}
func yamlExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "yaml") {
return nil, fmt.Errorf("unexpected content type from upstream. expected YAML, got %v", contentType)
}
decoder := yaml.NewDecoder(bytes.NewReader(resp.Body()))
decoder.KnownFields(true)
err := decoder.Decode(v)
return v, err
}
}
func jsonExtractor(v interface{}) func(*response.NormalResponse) (interface{}, error) {
if v == nil {
// json unmarshal expects a pointer
v = &map[string]interface{}{}
}
return func(resp *response.NormalResponse) (interface{}, error) {
contentType := resp.Header().Get("Content-Type")
if !strings.Contains(contentType, "json") {
return nil, fmt.Errorf("unexpected content type from upstream. expected JSON, got %v", contentType)
}
return v, json.Unmarshal(resp.Body(), v)
}
}
func messageExtractor(resp *response.NormalResponse) (interface{}, error) {
return map[string]string{"message": string(resp.Body())}, nil
}
func validateCondition(c ngmodels.Condition, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) error {
if len(c.Data) == 0 {
return nil
}
refIDs, err := validateQueriesAndExpressions(c.Data, user, skipCache, datasourceCache)
if err != nil {
return err
}
t := make([]string, 0, len(refIDs))
for refID := range refIDs {
t = append(t, refID)
}
if _, ok := refIDs[c.Condition]; !ok {
return fmt.Errorf("condition %s not found in any query or expression: it should be one of: [%s]", c.Condition, strings.Join(t, ","))
}
return nil
}
func validateQueriesAndExpressions(data []ngmodels.AlertQuery, user *models.SignedInUser, skipCache bool, datasourceCache datasources.CacheService) (map[string]struct{}, error) {
refIDs := make(map[string]struct{})
if len(data) == 0 {
return nil, nil
}
for _, query := range data {
datasourceUID, err := query.GetDatasource()
if err != nil {
return nil, err
}
isExpression, err := query.IsExpression()
if err != nil {
return nil, err
}
if isExpression {
refIDs[query.RefID] = struct{}{}
continue
}
_, err = datasourceCache.GetDatasourceByUID(datasourceUID, user, skipCache)
if err != nil {
return nil, fmt.Errorf("invalid query %s: %w: %s", query.RefID, err, datasourceUID)
}
refIDs[query.RefID] = struct{}{}
}
return refIDs, nil
}
func conditionEval(c *models.ReqContext, cmd ngmodels.EvalAlertConditionCommand, datasourceCache datasources.CacheService, dataService *tsdb.Service, cfg *setting.Cfg) response.Response {
evalCond := ngmodels.Condition{
Condition: cmd.Condition,
OrgID: c.SignedInUser.OrgId,
Data: cmd.Data,
}
if err := validateCondition(evalCond, c.SignedInUser, c.SkipCache, datasourceCache); err != nil {
return ErrResp(http.StatusBadRequest, err, "invalid condition")
}
now := cmd.Now
if now.IsZero() {
now = timeNow()
}
evaluator := eval.Evaluator{Cfg: cfg}
evalResults, err := evaluator.ConditionEval(&evalCond, now, dataService)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "Failed to evaluate conditions")
}
frame := evalResults.AsDataFrame()
return response.JSONStreaming(http.StatusOK, util.DynMap{
"instances": []*data.Frame{&frame},
})
}
// ErrorResp creates a response with a visible error
func ErrResp(status int, err error, msg string, args ...interface{}) *response.NormalResponse {
if msg != "" {
err = errors.WithMessagef(err, msg, args...)
}
return response.Error(status, err.Error(), nil)
}
| pkg/services/ngalert/api/util.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.004875114653259516,
0.0004665169690269977,
0.00016115454491227865,
0.00016929832054302096,
0.0009870316134765744
] |
{
"id": 7,
"code_window": [
"\n",
"import (\n",
"\t\"context\"\n",
"\t\"fmt\"\n",
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"runtime/debug\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 7
} | @grafanaRecipient = grafana
@lokiDatasourceID = 32
@prometheusDatasourceID = 35
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{grafanaRecipient}}
content-type: application/json
{
"grafana_condition": {
"condition": "A",
"data": [
{
"refId": "A",
"relativeTimeRange": {
"from": 18000,
"to": 10800
},
"datasourceUid": "-100",
"model": {
"type":"math",
"expression":"1 < 2"
}
}
]
}
}
###
POST http://admin:admin@localhost:3000/api/v1/eval
content-type: application/json
{
"data": [
{
"refId": "A",
"queryType": "",
"relativeTimeRange": {
"from": 18000,
"to": 10800
},
"datasourceUid": "000000004",
"model": {
"intervalMs": 1000,
"maxDataPoints": 100,
"orgId": 0,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0"
}
},
{
"refId": "B",
"queryType": "",
"relativeTimeRange": {
"from": 18000,
"to": 10800
},
"datasourceUid": "-100",
"model": {
"expression": "$A",
"intervalMs": 2000,
"maxDataPoints": 200,
"orgId": 0,
"reducer": "mean",
"refId": "B",
"type": "reduce"
}
}
],
"now": "2021-04-11T14:38:14Z"
}
###
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{lokiDatasourceID}}
content-type: application/json
{
"expr": "rate({cluster=\"us-central1\", job=\"loki-prod/loki-canary\"}[1m]) > 0"
}
###
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{prometheusDatasourceID}}
content-type: application/json
{
"expr": "http_request_duration_microseconds > 1"
}
### loki recipient - empty payload
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{lokiDatasourceID}}
content-type: application/json
{}
### grafana recipient - empty payload
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{grafanaRecipient}}
content-type: application/json
{}
### loki recipient - grafana payload
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{lokiDatasourceID}}
content-type: application/json
{
"grafana_condition": {
"condition": "A",
"data": [
{
"refId": "A",
"relativeTimeRange": {
"from": 18000,
"to": 10800
},
"datasourceUid": "-100",
"model": {
"type":"math",
"expression":"1 < 2"
}
}
]
}
}}
### grafana recipient - lotex payload
POST http://admin:admin@localhost:3000/api/v1/rule/test/{{grafanaRecipient}}
content-type: application/json
{
"expr": "rate({cluster=\"us-central1\", job=\"loki-prod/loki-canary\"}[1m]) > 0"
} | pkg/services/ngalert/api/test-data/test.http | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0003602921206038445,
0.00019366128253750503,
0.0001622132258489728,
0.0001723103050608188,
0.00005110605707159266
] |
{
"id": 7,
"code_window": [
"\n",
"import (\n",
"\t\"context\"\n",
"\t\"fmt\"\n",
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"runtime/debug\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 7
} | import { runCLI } from '@jest/core';
import { useSpinner } from '../../utils/useSpinner';
import { loadJestPluginConfig } from '../../../config/jest.plugin.config';
export interface PluginTestOptions {
updateSnapshot: boolean;
coverage: boolean;
watch: boolean;
testPathPattern?: string;
testNamePattern?: string;
maxWorkers?: string;
}
export const testPlugin = ({
updateSnapshot,
coverage,
watch,
testPathPattern,
testNamePattern,
maxWorkers,
}: PluginTestOptions) =>
useSpinner('Running tests', async () => {
const testConfig = loadJestPluginConfig();
const cliConfig = {
config: JSON.stringify(testConfig),
updateSnapshot,
coverage,
watch,
testPathPattern: testPathPattern ? [testPathPattern] : [],
testNamePattern: testNamePattern ? [testNamePattern] : [],
passWithNoTests: true,
maxWorkers,
};
// @ts-ignore
const runJest = () => runCLI(cliConfig, [process.cwd()]);
if (watch) {
runJest();
} else {
// @ts-ignore
const results = await runJest();
if (results.results.numFailedTests > 0 || results.results.numFailedTestSuites > 0) {
throw new Error('Tests failed');
}
}
});
| packages/grafana-toolkit/src/cli/tasks/plugin/tests.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017214918625541031,
0.00017037938232533634,
0.00016815209528431296,
0.00017027149442583323,
0.0000015310354228859069
] |
{
"id": 7,
"code_window": [
"\n",
"import (\n",
"\t\"context\"\n",
"\t\"fmt\"\n",
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"runtime/debug\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 7
} | import React, { FC, useState } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { GrafanaRouteComponentProps } from '../../core/navigation/types';
import { StoreState } from '../../types';
import { getNavModel } from '../../core/selectors/navModel';
import Page from '../../core/components/Page/Page';
import { LibraryPanelsSearch } from './components/LibraryPanelsSearch/LibraryPanelsSearch';
import { LibraryElementDTO } from './types';
import { OpenLibraryPanelModal } from './components/OpenLibraryPanelModal/OpenLibraryPanelModal';
const mapStateToProps = (state: StoreState) => ({
navModel: getNavModel(state.navIndex, 'library-panels'),
});
const connector = connect(mapStateToProps, undefined);
interface OwnProps extends GrafanaRouteComponentProps {}
type Props = OwnProps & ConnectedProps<typeof connector>;
export const LibraryPanelsPage: FC<Props> = ({ navModel }) => {
const [selected, setSelected] = useState<LibraryElementDTO | undefined>(undefined);
return (
<Page navModel={navModel}>
<Page.Contents>
<LibraryPanelsSearch onClick={setSelected} showSecondaryActions showSort showPanelFilter showFolderFilter />
{selected ? <OpenLibraryPanelModal onDismiss={() => setSelected(undefined)} libraryPanel={selected} /> : null}
</Page.Contents>
</Page>
);
};
export default connect(mapStateToProps)(LibraryPanelsPage);
| public/app/features/library-panels/LibraryPanelsPage.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00016983466048259288,
0.0001687104522716254,
0.00016695624799467623,
0.00016902544302865863,
0.000001174377530333004
] |
{
"id": 8,
"code_window": [
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/setting\"\n",
"\t\"github.com/grafana/grafana/pkg/tsdb\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 11
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.15635466575622559,
0.003880266798660159,
0.00016380906163249165,
0.00017150709754787385,
0.02325601875782013
] |
{
"id": 8,
"code_window": [
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/setting\"\n",
"\t\"github.com/grafana/grafana/pkg/tsdb\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 11
} | pkg/services/provisioning/notifiers/testdata/test-configs/empty/empty.yaml | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00016737273836042732,
0.00016737273836042732,
0.00016737273836042732,
0.00016737273836042732,
0
] |
|
{
"id": 8,
"code_window": [
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/setting\"\n",
"\t\"github.com/grafana/grafana/pkg/tsdb\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 11
} | import React, { useState } from 'react';
import mdx from './RadioButtonGroup.mdx';
import { RadioButtonGroup } from './RadioButtonGroup';
import { Story } from '@storybook/react';
export default {
title: 'Forms/RadioButtonGroup',
component: RadioButtonGroup,
parameters: {
docs: {
page: mdx,
},
controls: {
exclude: ['className', 'options', 'value'],
},
},
argTypes: {
disabledOptions: {
name: 'Disabled item',
control: { type: 'select' },
options: ['', 'graphite', 'prometheus', 'elastic'],
},
size: { control: { type: 'select' }, options: ['xs', 'sm', 'md', 'lg'] },
},
};
export const RadioButtons: Story = (args) => {
const [selected, setSelected] = useState('elastic');
const options = [
{ label: 'Prometheus', value: 'prometheus' },
{ label: 'Graphite', value: 'graphite', icon: 'cloud' },
{ label: 'Elastic', value: 'elastic' },
];
const optionsWithOnlyIcons = [
{ description: 'Prometheus', value: 'prometheus', icon: 'gf-interpolation-linear' },
{ description: 'Graphite', value: 'graphite', icon: 'gf-interpolation-smooth' },
{ description: 'Elastic', value: 'elastic', icon: 'gf-interpolation-step-after' },
];
return (
<div style={{ width: '100%' }}>
<div style={{ marginBottom: '32px' }}>
<h5>Full width</h5>
<RadioButtonGroup
options={options}
disabled={args.disabled}
disabledOptions={args.disabledOptions}
value={selected}
onChange={(v) => setSelected(v!)}
size={args.size}
fullWidth={args.fullWidth}
/>
</div>
<div style={{ marginBottom: '32px' }}>
<h5>Auto width</h5>
<RadioButtonGroup
options={options}
disabled={args.disabled}
disabledOptions={args.disabledOptions}
value={selected}
onChange={(v) => setSelected(v!)}
size={args.size}
/>
</div>
<div style={{ marginBottom: '32px' }}>
<h5>With only icons and descriptions</h5>
<RadioButtonGroup
options={optionsWithOnlyIcons}
value={selected}
onChange={(v) => setSelected(v!)}
size={args.size}
/>
</div>
</div>
);
};
RadioButtons.args = {
disabled: false,
disabledOptions: '',
size: 'md',
fullWidth: true,
};
| packages/grafana-ui/src/components/Forms/RadioButtonGroup/RadioButtonGroup.story.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001741888845572248,
0.00016973809397313744,
0.00016539882926736027,
0.0001702063891571015,
0.000002386909727647435
] |
{
"id": 8,
"code_window": [
"\t\"sort\"\n",
"\t\"time\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/expr/classic\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/setting\"\n",
"\t\"github.com/grafana/grafana/pkg/tsdb\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 11
} | +++
title = "What's new in Grafana v4.5"
description = "Feature and improvement highlights for Grafana v4.5"
keywords = ["grafana", "new", "documentation", "4.5", "release notes"]
aliases = ["/docs/grafana/latest/guides/whats-new-in-v4-5/"]
weight = -12
[_build]
list = false
+++
# What's new in Grafana v4.5
## Highlights
### New prometheus query editor
The new query editor has full syntax highlighting. As well as auto complete for metrics, functions, and range vectors. There are also integrated function docs right from the query editor!
{{< figure src="/static/img/docs/v45/prometheus_query_editor_still.png" class="docs-image--block" animated-gif="/static/img/docs/v45/prometheus_query_editor.gif" >}}
### Elasticsearch: Add ad-hoc filters from the table panel
{{< figure src="/static/img/docs/v45/elastic_ad_hoc_filters.png" class="docs-image--block" >}}
### Table cell links!
Create column styles that turn cells into links that use the value in the cell (or other row values) to generate a URL to another dashboard or system:

### Query Inspector
Query Inspector is a new feature that shows query requests and responses. This can be helpful if a graph is not shown or shows something very different than what you expected.
For more information about query inspector, refer to [using grafanas query inspector to troubleshoot issues](https://community.grafana.com/t/using-grafanas-query-inspector-to-troubleshoot-issues/2630).

## Changelog
### New Features
- **Table panel**: Render cell values as links that can have an URL template that uses variables from current table row. [#3754](https://github.com/grafana/grafana/issues/3754)
- **Elasticsearch**: Add ad hoc filters directly by clicking values in table panel [#8052](https://github.com/grafana/grafana/issues/8052).
- **MySQL**: New rich query editor with syntax highlighting
- **Prometheus**: New rich query editor with syntax highlighting, metric and range auto complete and integrated function docs. [#5117](https://github.com/grafana/grafana/issues/5117)
### Enhancements
- **GitHub OAuth**: Support for GitHub organizations with 100+ teams. [#8846](https://github.com/grafana/grafana/issues/8846), thx [@skwashd](https://github.com/skwashd)
- **Graphite**: Calls to Graphite API /metrics/find now include panel or dashboard time range (from and until) in most cases, [#8055](https://github.com/grafana/grafana/issues/8055)
- **Graphite**: Added new graphite 1.0 functions, available if you set version to 1.0.x in data source settings. New Functions: mapSeries, reduceSeries, isNonNull, groupByNodes, offsetToZero, grep, weightedAverage, removeEmptySeries, aggregateLine, averageOutsidePercentile, delay, exponentialMovingAverage, fallbackSeries, integralByInterval, interpolate, invert, linearRegression, movingMin, movingMax, movingSum, multiplySeriesWithWildcards, pow, powSeries, removeBetweenPercentile, squareRoot, timeSlice, closes [#8261](https://github.com/grafana/grafana/issues/8261)
- **Elasticsearch**: Ad-hoc filters now use query phrase match filters instead of term filters, works on non keyword/raw fields [#9095](https://github.com/grafana/grafana/issues/9095).
### Breaking change
- **InfluxDB/Elasticsearch**: The panel and data source option named "Group by time interval" is now named "Min time interval" and does now always define a lower limit for the auto group by time. Without having to use `>` prefix (that prefix still works). This should in theory have close to zero actual impact on existing dashboards. It does mean that if you used this setting to define a hard group by time interval of, say "1d", if you zoomed to a time range wide enough the time range could increase above the "1d" range as the setting is now always considered a lower limit.
This option is now renamed (and moved to Options sub section above your queries):

Data source selection and options and help are now above your metric queries.

### Minor Changes
- **InfluxDB**: Change time range filter for absolute time ranges to be inclusive instead of exclusive [#8319](https://github.com/grafana/grafana/issues/8319), thx [@Oxydros](https://github.com/Oxydros)
- **InfluxDB**: Added parenthesis around tag filters in queries [#9131](https://github.com/grafana/grafana/pull/9131)
## Bug Fixes
- **Modals**: Maintain scroll position after opening/leaving modal [#8800](https://github.com/grafana/grafana/issues/8800)
- **Templating**: You cannot select data source variables as data source for other template variables [#7510](https://github.com/grafana/grafana/issues/7510)
| docs/sources/whatsnew/whats-new-in-v4-5.md | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0013680759584531188,
0.000458709429949522,
0.0001621929695829749,
0.00026898374198935926,
0.00040470389649271965
] |
{
"id": 9,
"code_window": [
"\n",
"const alertingEvaluationTimeout = 30 * time.Second\n",
"\n",
"type Evaluator struct {\n",
"\tCfg *setting.Cfg\n",
"}\n",
"\n",
"// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 25
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9989830851554871,
0.09134089946746826,
0.0001681315479800105,
0.0008101200219243765,
0.2729370892047882
] |
{
"id": 9,
"code_window": [
"\n",
"const alertingEvaluationTimeout = 30 * time.Second\n",
"\n",
"type Evaluator struct {\n",
"\tCfg *setting.Cfg\n",
"}\n",
"\n",
"// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 25
} | #!/bin/sh
##
# Script to deploy a docker image. Must return exit code 0
#
do_exit() {
message="$1"
exit_code="$2"
echo "$message"
exit $exit_code
}
##
# Get file, get's a file, validates the SHA
# @param filename
# @param expected sha value
# @returns 0 if successful, -1 of checksum validation failed.
#
get_file () {
[ -n "$1" ] && url=$1 || do_exit "url required" 1
[ -n "$2" ] && dest=$2 || do_exit "destination required" 2
sha=$3
file=$(basename $dest)
curl -fL "${url}" -o "$dest"
if [ -n "$sha" ]; then
echo "$sha $dest" | sha256sum || do_exit "Checksum validation failed for $file. Exiting" 1
fi
}
untar_file () {
[ -n "$1" ] && src=$1 || do_exit "src required" 1
[ -n "$2" ] && dest=$2 || dest="/usr/local"
tar -C "$dest" -xf "$src" && /bin/rm -rf "$src"
}
##
# WIP: Just started this and not finished.
# The intent it to download a release from a git repo,
# compile, and install
get_latest_release () {
tarsrc=$(curl -sL "https://api.github.com/repos/$1/$2/releases/latest" | jq ".tarball_url" | tr -d '"')
curl -fL -o /tmp/autoretrieved.tar.gz "$tarsrc"
origdir=$PWD
reponame=$(tar zxvf autoretrieved.tar.gz | tail -1 | awk -F / '{print $1}')
cd "/tmp/$reponame"
#perform compile
cd $origdir
}
| packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/scripts/deploy-common.sh | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001754527329467237,
0.00017173064406961203,
0.00016952288569882512,
0.00017083837883546948,
0.000002124302000083844
] |
{
"id": 9,
"code_window": [
"\n",
"const alertingEvaluationTimeout = 30 * time.Second\n",
"\n",
"type Evaluator struct {\n",
"\tCfg *setting.Cfg\n",
"}\n",
"\n",
"// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 25
} | //
// Code (inline and blocK)
// --------------------------------------------------
// Inline and block code styles
code,
pre {
@include font-family-monospace();
font-size: $font-size-base - 2;
background-color: $code-tag-bg;
color: $text-color;
border: 1px solid $code-tag-border;
border-radius: 4px;
}
// Inline code
code {
color: $text-color;
white-space: nowrap;
padding: 2px 5px;
margin: 0 2px;
}
code.code--small {
font-size: $font-size-xs;
padding: $space-xxs;
margin: 0 2px;
}
// Blocks of code
pre {
display: block;
margin: 0 0 $line-height-base;
line-height: $line-height-base;
word-break: break-all;
word-wrap: break-word;
white-space: pre;
white-space: pre-wrap;
background-color: $code-tag-bg;
padding: 10px;
&.pre--no-style {
background: transparent;
border: none;
padding: 0px;
}
// Make prettyprint styles more spaced out for readability
&.prettyprint {
margin-bottom: $line-height-base;
}
// Account for some code outputs that place code tags in pre tags
code {
padding: 0;
color: inherit;
white-space: pre;
white-space: pre-wrap;
background-color: transparent;
border: 0;
}
}
| public/sass/base/_code.scss | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017751901759766042,
0.0001735000842018053,
0.00016972862067632377,
0.00017353023577015847,
0.000002330287998120184
] |
{
"id": 9,
"code_window": [
"\n",
"const alertingEvaluationTimeout = 30 * time.Second\n",
"\n",
"type Evaluator struct {\n",
"\tCfg *setting.Cfg\n",
"}\n",
"\n",
"// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 25
} | import React, { FormEvent, memo, useCallback } from 'react';
import { css } from '@emotion/css';
import Calendar from 'react-calendar/dist/entry.nostyle';
import { dateTime, DateTime, dateTimeParse, GrafanaTheme2, TimeZone } from '@grafana/data';
import { stylesFactory, useTheme2 } from '../../../themes';
import { TimePickerTitle } from './TimePickerTitle';
import { Button } from '../../Button';
import { Icon } from '../../Icon/Icon';
import { Portal } from '../../Portal/Portal';
import { ClickOutsideWrapper } from '../../ClickOutsideWrapper/ClickOutsideWrapper';
const getStyles = stylesFactory((theme: GrafanaTheme2, isReversed = false) => {
return {
container: css`
top: -1px;
position: absolute;
${isReversed ? 'left' : 'right'}: 544px;
box-shadow: ${theme.shadows.z3};
background-color: ${theme.colors.background.primary};
z-index: -1;
border: 1px solid ${theme.colors.border.weak};
border-radius: 2px 0 0 2px;
&:after {
display: block;
background-color: ${theme.colors.background.primary};
width: 19px;
height: 100%;
content: ${!isReversed ? ' ' : ''};
position: absolute;
top: 0;
right: -19px;
border-left: 1px solid ${theme.colors.border.weak};
}
`,
modal: css`
position: fixed;
top: 20%;
width: 100%;
z-index: ${theme.zIndex.modal};
`,
content: css`
margin: 0 auto;
width: 268px;
`,
backdrop: css`
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #202226;
opacity: 0.7;
z-index: ${theme.zIndex.modalBackdrop};
text-align: center;
`,
};
});
const getFooterStyles = stylesFactory((theme: GrafanaTheme2) => {
return {
container: css`
background-color: ${theme.colors.background.primary};
display: flex;
justify-content: center;
padding: 10px;
align-items: stretch;
`,
apply: css`
margin-right: 4px;
width: 100%;
justify-content: center;
`,
};
});
const getBodyStyles = stylesFactory((theme: GrafanaTheme2) => {
return {
title: css`
color: ${theme.colors.text};
background-color: ${theme.colors.background.primary};
font-size: ${theme.typography.size.md};
border: 1px solid transparent;
&:hover {
position: relative;
}
`,
body: css`
z-index: ${theme.zIndex.modal};
background-color: ${theme.colors.background.primary};
width: 268px;
.react-calendar__navigation__label,
.react-calendar__navigation__arrow,
.react-calendar__navigation {
padding-top: 4px;
background-color: inherit;
color: ${theme.colors.text};
border: 0;
font-weight: ${theme.typography.fontWeightMedium};
}
.react-calendar__month-view__weekdays {
background-color: inherit;
text-align: center;
color: ${theme.colors.primary.text};
abbr {
border: 0;
text-decoration: none;
cursor: default;
display: block;
padding: 4px 0 4px 0;
}
}
.react-calendar__month-view__days {
background-color: inherit;
}
.react-calendar__tile,
.react-calendar__tile--now {
margin-bottom: 4px;
background-color: inherit;
height: 26px;
}
.react-calendar__navigation__label,
.react-calendar__navigation > button:focus,
.time-picker-calendar-tile:focus {
outline: 0;
}
.react-calendar__tile--active,
.react-calendar__tile--active:hover {
color: ${theme.colors.primary.contrastText};
font-weight: ${theme.typography.fontWeightMedium};
background: ${theme.colors.primary.main};
box-shadow: none;
border: 0px;
}
.react-calendar__tile--rangeEnd,
.react-calendar__tile--rangeStart {
padding: 0;
border: 0px;
color: ${theme.colors.primary.contrastText};
font-weight: ${theme.typography.fontWeightMedium};
background: ${theme.colors.primary.main};
abbr {
background-color: ${theme.colors.primary.main};
border-radius: 100px;
display: block;
padding-top: 2px;
height: 26px;
}
}
.react-calendar__tile--rangeStart {
border-top-left-radius: 20px;
border-bottom-left-radius: 20px;
}
.react-calendar__tile--rangeEnd {
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
}
`,
};
});
const getHeaderStyles = stylesFactory((theme: GrafanaTheme2) => {
return {
container: css`
background-color: ${theme.colors.background.primary};
display: flex;
justify-content: space-between;
padding: 7px;
`,
};
});
interface Props {
isOpen: boolean;
from: DateTime;
to: DateTime;
onClose: () => void;
onApply: (e: FormEvent<HTMLButtonElement>) => void;
onChange: (from: DateTime, to: DateTime) => void;
isFullscreen: boolean;
timeZone?: TimeZone;
isReversed?: boolean;
}
const stopPropagation = (event: React.MouseEvent<HTMLDivElement>) => event.stopPropagation();
export const TimePickerCalendar = memo<Props>((props) => {
const theme = useTheme2();
const styles = getStyles(theme, props.isReversed);
const { isOpen, isFullscreen } = props;
if (!isOpen) {
return null;
}
if (isFullscreen) {
return (
<ClickOutsideWrapper onClick={props.onClose}>
<div className={styles.container} onClick={stopPropagation}>
<Body {...props} />
</div>
</ClickOutsideWrapper>
);
}
return (
<Portal>
<div className={styles.modal} onClick={stopPropagation}>
<div className={styles.content}>
<Header {...props} />
<Body {...props} />
<Footer {...props} />
</div>
</div>
<div className={styles.backdrop} onClick={stopPropagation} />
</Portal>
);
});
TimePickerCalendar.displayName = 'TimePickerCalendar';
const Header = memo<Props>(({ onClose }) => {
const theme = useTheme2();
const styles = getHeaderStyles(theme);
return (
<div className={styles.container}>
<TimePickerTitle>Select a time range</TimePickerTitle>
<Icon name="times" onClick={onClose} />
</div>
);
});
Header.displayName = 'Header';
const Body = memo<Props>(({ onChange, from, to, timeZone }) => {
const value = inputToValue(from, to);
const theme = useTheme2();
const onCalendarChange = useOnCalendarChange(onChange, timeZone);
const styles = getBodyStyles(theme);
return (
<Calendar
selectRange={true}
next2Label={null}
prev2Label={null}
className={styles.body}
tileClassName={styles.title}
value={value}
nextLabel={<Icon name="angle-right" />}
prevLabel={<Icon name="angle-left" />}
onChange={onCalendarChange}
locale="en"
/>
);
});
Body.displayName = 'Body';
const Footer = memo<Props>(({ onClose, onApply }) => {
const theme = useTheme2();
const styles = getFooterStyles(theme);
return (
<div className={styles.container}>
<Button className={styles.apply} onClick={onApply}>
Apply time range
</Button>
<Button variant="secondary" onClick={onClose}>
Cancel
</Button>
</div>
);
});
Footer.displayName = 'Footer';
export function inputToValue(from: DateTime, to: DateTime, invalidDateDefault: Date = new Date()): Date[] {
const fromAsDate = from.toDate();
const toAsDate = to.toDate();
const fromAsValidDate = dateTime(fromAsDate).isValid() ? fromAsDate : invalidDateDefault;
const toAsValidDate = dateTime(toAsDate).isValid() ? toAsDate : invalidDateDefault;
if (fromAsValidDate > toAsValidDate) {
return [toAsValidDate, fromAsValidDate];
}
return [fromAsValidDate, toAsValidDate];
}
function useOnCalendarChange(onChange: (from: DateTime, to: DateTime) => void, timeZone?: TimeZone) {
return useCallback(
(value: Date | Date[]) => {
if (!Array.isArray(value)) {
return console.error('onCalendarChange: should be run in selectRange={true}');
}
const from = dateTimeParse(dateInfo(value[0]), { timeZone });
const to = dateTimeParse(dateInfo(value[1]), { timeZone });
onChange(from, to);
},
[onChange, timeZone]
);
}
function dateInfo(date: Date): number[] {
return [date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()];
}
| packages/grafana-ui/src/components/TimePicker/TimeRangePicker/TimePickerCalendar.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017638065037317574,
0.00017244710761588067,
0.00016758896526880562,
0.0001725273032207042,
0.0000023384668565995526
] |
{
"id": 10,
"code_window": [
"\n",
"// AlertExecCtx is the context provided for executing an alert condition.\n",
"type AlertExecCtx struct {\n",
"\tOrgID int64\n",
"\tExpressionsEnabled bool\n",
"\n",
"\tCtx context.Context\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 107
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9991194605827332,
0.16061297059059143,
0.0001681706780800596,
0.00017633223615121096,
0.3621043264865875
] |
{
"id": 10,
"code_window": [
"\n",
"// AlertExecCtx is the context provided for executing an alert condition.\n",
"type AlertExecCtx struct {\n",
"\tOrgID int64\n",
"\tExpressionsEnabled bool\n",
"\n",
"\tCtx context.Context\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 107
} | import React from 'react';
import { shallow } from 'enzyme';
import PluginListItem from './PluginListItem';
import { getMockPlugin } from './__mocks__/pluginMocks';
const setup = (propOverrides?: object) => {
const props = Object.assign(
{
plugin: getMockPlugin(),
},
propOverrides
);
return shallow(<PluginListItem {...props} />);
};
describe('Render', () => {
it('should render component', () => {
const wrapper = setup();
expect(wrapper).toMatchSnapshot();
});
it('should render has plugin section', () => {
const mockPlugin = getMockPlugin();
mockPlugin.hasUpdate = true;
const wrapper = setup({
plugin: mockPlugin,
});
expect(wrapper).toMatchSnapshot();
});
});
| public/app/features/plugins/PluginListItem.test.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001764124317560345,
0.0001759488950483501,
0.00017500596004538238,
0.0001761886232998222,
5.689084332516359e-7
] |
{
"id": 10,
"code_window": [
"\n",
"// AlertExecCtx is the context provided for executing an alert condition.\n",
"type AlertExecCtx struct {\n",
"\tOrgID int64\n",
"\tExpressionsEnabled bool\n",
"\n",
"\tCtx context.Context\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 107
} | package conditions
import (
"errors"
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/tsdb/prometheus"
gocontext "context"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/null"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/util/errutil"
)
func init() {
alerting.RegisterCondition("query", func(model *simplejson.Json, index int) (alerting.Condition, error) {
return newQueryCondition(model, index)
})
}
// QueryCondition is responsible for issue and query, reduce the
// timeseries into single values and evaluate if they are firing or not.
type QueryCondition struct {
Index int
Query AlertQuery
Reducer *queryReducer
Evaluator AlertEvaluator
Operator string
}
// AlertQuery contains information about what datasource a query
// should be sent to and the query object.
type AlertQuery struct {
Model *simplejson.Json
DatasourceID int64
From string
To string
}
// Eval evaluates the `QueryCondition`.
func (c *QueryCondition) Eval(context *alerting.EvalContext, requestHandler plugins.DataRequestHandler) (*alerting.ConditionResult, error) {
timeRange := plugins.NewDataTimeRange(c.Query.From, c.Query.To)
seriesList, err := c.executeQuery(context, timeRange, requestHandler)
if err != nil {
return nil, err
}
emptySeriesCount := 0
evalMatchCount := 0
var matches []*alerting.EvalMatch
for _, series := range seriesList {
reducedValue := c.Reducer.Reduce(series)
evalMatch := c.Evaluator.Eval(reducedValue)
if !reducedValue.Valid {
emptySeriesCount++
}
if context.IsTestRun {
context.Logs = append(context.Logs, &alerting.ResultLogEntry{
Message: fmt.Sprintf("Condition[%d]: Eval: %v, Metric: %s, Value: %s", c.Index, evalMatch, series.Name, reducedValue),
})
}
if evalMatch {
evalMatchCount++
matches = append(matches, &alerting.EvalMatch{
Metric: series.Name,
Value: reducedValue,
Tags: series.Tags,
})
}
}
// handle no series special case
if len(seriesList) == 0 {
// eval condition for null value
evalMatch := c.Evaluator.Eval(null.FloatFromPtr(nil))
if context.IsTestRun {
context.Logs = append(context.Logs, &alerting.ResultLogEntry{
Message: fmt.Sprintf("Condition: Eval: %v, Query Returned No Series (reduced to null/no value)", evalMatch),
})
}
if evalMatch {
evalMatchCount++
matches = append(matches, &alerting.EvalMatch{Metric: "NoData", Value: null.FloatFromPtr(nil)})
}
}
return &alerting.ConditionResult{
Firing: evalMatchCount > 0,
NoDataFound: emptySeriesCount == len(seriesList),
Operator: c.Operator,
EvalMatches: matches,
}, nil
}
func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange plugins.DataTimeRange,
requestHandler plugins.DataRequestHandler) (plugins.DataTimeSeriesSlice, error) {
getDsInfo := &models.GetDataSourceQuery{
Id: c.Query.DatasourceID,
OrgId: context.Rule.OrgID,
}
if err := bus.Dispatch(getDsInfo); err != nil {
return nil, fmt.Errorf("could not find datasource: %w", err)
}
err := context.RequestValidator.Validate(getDsInfo.Result.Url, nil)
if err != nil {
return nil, fmt.Errorf("access denied: %w", err)
}
req := c.getRequestForAlertRule(getDsInfo.Result, timeRange, context.IsDebug)
result := make(plugins.DataTimeSeriesSlice, 0)
if context.IsDebug {
data := simplejson.New()
if req.TimeRange != nil {
data.Set("from", req.TimeRange.GetFromAsMsEpoch())
data.Set("to", req.TimeRange.GetToAsMsEpoch())
}
type queryDto struct {
RefID string `json:"refId"`
Model *simplejson.Json `json:"model"`
Datasource *simplejson.Json `json:"datasource"`
MaxDataPoints int64 `json:"maxDataPoints"`
IntervalMS int64 `json:"intervalMs"`
}
queries := []*queryDto{}
for _, q := range req.Queries {
queries = append(queries, &queryDto{
RefID: q.RefID,
Model: q.Model,
Datasource: simplejson.NewFromAny(map[string]interface{}{
"id": q.DataSource.Id,
"name": q.DataSource.Name,
}),
MaxDataPoints: q.MaxDataPoints,
IntervalMS: q.IntervalMS,
})
}
data.Set("queries", queries)
context.Logs = append(context.Logs, &alerting.ResultLogEntry{
Message: fmt.Sprintf("Condition[%d]: Query", c.Index),
Data: data,
})
}
resp, err := requestHandler.HandleRequest(context.Ctx, getDsInfo.Result, req)
if err != nil {
return nil, toCustomError(err)
}
for _, v := range resp.Results {
if v.Error != nil {
return nil, fmt.Errorf("request handler response error %v", v)
}
// If there are dataframes but no series on the result
useDataframes := v.Dataframes != nil && (v.Series == nil || len(v.Series) == 0)
if useDataframes { // convert the dataframes to plugins.DataTimeSeries
frames, err := v.Dataframes.Decoded()
if err != nil {
return nil, errutil.Wrap("request handler failed to unmarshal arrow dataframes from bytes", err)
}
for _, frame := range frames {
ss, err := FrameToSeriesSlice(frame)
if err != nil {
return nil, errutil.Wrapf(err,
`request handler failed to convert dataframe "%v" to plugins.DataTimeSeriesSlice`, frame.Name)
}
result = append(result, ss...)
}
} else {
result = append(result, v.Series...)
}
queryResultData := map[string]interface{}{}
if context.IsTestRun {
queryResultData["series"] = result
}
if context.IsDebug && v.Meta != nil {
queryResultData["meta"] = v.Meta
}
if context.IsTestRun || context.IsDebug {
if useDataframes {
queryResultData["fromDataframe"] = true
}
context.Logs = append(context.Logs, &alerting.ResultLogEntry{
Message: fmt.Sprintf("Condition[%d]: Query Result", c.Index),
Data: simplejson.NewFromAny(queryResultData),
})
}
}
return result, nil
}
func (c *QueryCondition) getRequestForAlertRule(datasource *models.DataSource, timeRange plugins.DataTimeRange,
debug bool) plugins.DataQuery {
queryModel := c.Query.Model
req := plugins.DataQuery{
TimeRange: &timeRange,
Queries: []plugins.DataSubQuery{
{
RefID: "A",
Model: queryModel,
DataSource: datasource,
QueryType: queryModel.Get("queryType").MustString(""),
},
},
Headers: map[string]string{
"FromAlert": "true",
},
Debug: debug,
}
return req
}
func newQueryCondition(model *simplejson.Json, index int) (*QueryCondition, error) {
condition := QueryCondition{}
condition.Index = index
queryJSON := model.Get("query")
condition.Query.Model = queryJSON.Get("model")
condition.Query.From = queryJSON.Get("params").MustArray()[1].(string)
condition.Query.To = queryJSON.Get("params").MustArray()[2].(string)
if err := validateFromValue(condition.Query.From); err != nil {
return nil, err
}
if err := validateToValue(condition.Query.To); err != nil {
return nil, err
}
condition.Query.DatasourceID = queryJSON.Get("datasourceId").MustInt64()
reducerJSON := model.Get("reducer")
condition.Reducer = newSimpleReducer(reducerJSON.Get("type").MustString())
evaluatorJSON := model.Get("evaluator")
evaluator, err := NewAlertEvaluator(evaluatorJSON)
if err != nil {
return nil, fmt.Errorf("error in condition %v: %v", index, err)
}
condition.Evaluator = evaluator
operatorJSON := model.Get("operator")
operator := operatorJSON.Get("type").MustString("and")
condition.Operator = operator
return &condition, nil
}
func validateFromValue(from string) error {
fromRaw := strings.Replace(from, "now-", "", 1)
_, err := time.ParseDuration("-" + fromRaw)
return err
}
func validateToValue(to string) error {
if to == "now" {
return nil
} else if strings.HasPrefix(to, "now-") {
withoutNow := strings.Replace(to, "now-", "", 1)
_, err := time.ParseDuration("-" + withoutNow)
if err == nil {
return nil
}
}
_, err := time.ParseDuration(to)
return err
}
// FrameToSeriesSlice converts a frame that is a valid time series as per data.TimeSeriesSchema()
// to a DataTimeSeriesSlice.
func FrameToSeriesSlice(frame *data.Frame) (plugins.DataTimeSeriesSlice, error) {
tsSchema := frame.TimeSeriesSchema()
if tsSchema.Type == data.TimeSeriesTypeNot {
// If no fields, or only a time field, create an empty plugins.DataTimeSeriesSlice with a single
// time series in order to trigger "no data" in alerting.
if len(frame.Fields) == 0 || (len(frame.Fields) == 1 && frame.Fields[0].Type().Time()) {
return plugins.DataTimeSeriesSlice{{
Name: frame.Name,
Points: make(plugins.DataTimeSeriesPoints, 0),
}}, nil
}
return nil, fmt.Errorf("input frame is not recognized as a time series")
}
seriesCount := len(tsSchema.ValueIndices)
seriesSlice := make(plugins.DataTimeSeriesSlice, 0, seriesCount)
timeField := frame.Fields[tsSchema.TimeIndex]
timeNullFloatSlice := make([]null.Float, timeField.Len())
for i := 0; i < timeField.Len(); i++ { // built slice of time as epoch ms in null floats
tStamp, err := timeField.FloatAt(i)
if err != nil {
return nil, err
}
timeNullFloatSlice[i] = null.FloatFrom(tStamp)
}
for _, fieldIdx := range tsSchema.ValueIndices { // create a TimeSeries for each value Field
field := frame.Fields[fieldIdx]
ts := plugins.DataTimeSeries{
Points: make(plugins.DataTimeSeriesPoints, field.Len()),
}
if len(field.Labels) > 0 {
ts.Tags = field.Labels.Copy()
}
switch {
case field.Config != nil && field.Config.DisplayName != "":
ts.Name = field.Config.DisplayName
case field.Config != nil && field.Config.DisplayNameFromDS != "":
ts.Name = field.Config.DisplayNameFromDS
case len(field.Labels) > 0:
// Tags are appended to the name so they are eventually included in EvalMatch's Metric property
// for display in notifications.
ts.Name = fmt.Sprintf("%v {%v}", field.Name, field.Labels.String())
default:
ts.Name = field.Name
}
for rowIdx := 0; rowIdx < field.Len(); rowIdx++ { // for each value in the field, make a TimePoint
val, err := field.FloatAt(rowIdx)
if err != nil {
return nil, errutil.Wrapf(err,
"failed to convert frame to DataTimeSeriesSlice, can not convert value %v to float", field.At(rowIdx))
}
ts.Points[rowIdx] = plugins.DataTimePoint{
null.FloatFrom(val),
timeNullFloatSlice[rowIdx],
}
}
seriesSlice = append(seriesSlice, ts)
}
return seriesSlice, nil
}
func toCustomError(err error) error {
// is context timeout
if errors.Is(err, gocontext.DeadlineExceeded) {
return fmt.Errorf("alert execution exceeded the timeout")
}
// is Prometheus error
if prometheus.IsAPIError(err) {
return prometheus.ConvertAPIError(err)
}
// generic fallback
return fmt.Errorf("request handler error: %w", err)
}
| pkg/services/alerting/conditions/query.go | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.10128229111433029,
0.0052037909626960754,
0.00016801217861939222,
0.00017653543909545988,
0.01695871353149414
] |
{
"id": 10,
"code_window": [
"\n",
"// AlertExecCtx is the context provided for executing an alert condition.\n",
"type AlertExecCtx struct {\n",
"\tOrgID int64\n",
"\tExpressionsEnabled bool\n",
"\n",
"\tCtx context.Context\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tLog log.Logger\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "add",
"edit_start_line_idx": 107
} | import { cloneDeep } from 'lodash';
import { ConstantVariableModel } from '../types';
import { dispatch } from '../../../store/store';
import { setOptionAsCurrent, setOptionFromUrl } from '../state/actions';
import { VariableAdapter } from '../adapters';
import { constantVariableReducer, initialConstantVariableModelState } from './reducer';
import { ConstantVariableEditor } from './ConstantVariableEditor';
import { updateConstantVariableOptions } from './actions';
import { toVariableIdentifier } from '../state/types';
import { optionPickerFactory } from '../pickers';
export const createConstantVariableAdapter = (): VariableAdapter<ConstantVariableModel> => {
return {
id: 'constant',
description: 'Define a hidden constant variable, useful for metric prefixes in dashboards you want to share.',
name: 'Constant',
initialState: initialConstantVariableModelState,
reducer: constantVariableReducer,
picker: optionPickerFactory<ConstantVariableModel>(),
editor: ConstantVariableEditor,
dependsOn: () => {
return false;
},
setValue: async (variable, option, emitChanges = false) => {
await dispatch(setOptionAsCurrent(toVariableIdentifier(variable), option, emitChanges));
},
setValueFromUrl: async (variable, urlValue) => {
await dispatch(setOptionFromUrl(toVariableIdentifier(variable), urlValue));
},
updateOptions: async (variable) => {
await dispatch(updateConstantVariableOptions(toVariableIdentifier(variable)));
},
getSaveModel: (variable) => {
const { index, id, state, global, current, options, ...rest } = cloneDeep(variable);
return rest;
},
getValueForUrl: (variable) => {
return variable.current.value;
},
beforeAdding: (model) => {
const { current, options, query, ...rest } = cloneDeep(model);
const option = { selected: true, text: query, value: query };
return { ...rest, current: option, options: [option], query };
},
};
};
| public/app/features/variables/constant/adapter.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017824344104155898,
0.00017567934992257506,
0.00017254622071050107,
0.0001764514745445922,
0.0000019829826669592876
] |
{
"id": 11,
"code_window": [
"\n",
"\treturn result\n",
"}\n",
"\n",
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {\n",
"\tqueryDataReq, err := GetExprRequest(ctx, data, now)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (resp *backend.QueryDataResponse, err error) {\n",
"\tdefer func() {\n",
"\t\tif e := recover(); e != nil {\n",
"\t\t\tctx.Log.Error(\"alert rule panic\", \"error\", e, \"stack\", string(debug.Stack()))\n",
"\t\t\tpanicErr := fmt.Errorf(\"alert rule panic; please check the logs for the full stack\")\n",
"\t\t\tif err != nil {\n",
"\t\t\t\terr = fmt.Errorf(\"queries and expressions execution failed: %w; %v\", err, panicErr.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\terr = panicErr\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}()\n",
"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 222
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9992830157279968,
0.09345681220293045,
0.0001627885503694415,
0.00024507491616532207,
0.2726999819278717
] |
{
"id": 11,
"code_window": [
"\n",
"\treturn result\n",
"}\n",
"\n",
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {\n",
"\tqueryDataReq, err := GetExprRequest(ctx, data, now)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (resp *backend.QueryDataResponse, err error) {\n",
"\tdefer func() {\n",
"\t\tif e := recover(); e != nil {\n",
"\t\t\tctx.Log.Error(\"alert rule panic\", \"error\", e, \"stack\", string(debug.Stack()))\n",
"\t\t\tpanicErr := fmt.Errorf(\"alert rule panic; please check the logs for the full stack\")\n",
"\t\t\tif err != nil {\n",
"\t\t\t\terr = fmt.Errorf(\"queries and expressions execution failed: %w; %v\", err, panicErr.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\terr = panicErr\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}()\n",
"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 222
} | ---
title: View user list as server admin
---
1. Hover your cursor over the **Server Admin** (shield) icon until a menu appears.
1. Click **Users**. | docs/sources/shared/manage-users/view-server-user-list.md | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00016945712559390813,
0.00016945712559390813,
0.00016945712559390813,
0.00016945712559390813,
0
] |
{
"id": 11,
"code_window": [
"\n",
"\treturn result\n",
"}\n",
"\n",
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {\n",
"\tqueryDataReq, err := GetExprRequest(ctx, data, now)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (resp *backend.QueryDataResponse, err error) {\n",
"\tdefer func() {\n",
"\t\tif e := recover(); e != nil {\n",
"\t\t\tctx.Log.Error(\"alert rule panic\", \"error\", e, \"stack\", string(debug.Stack()))\n",
"\t\t\tpanicErr := fmt.Errorf(\"alert rule panic; please check the logs for the full stack\")\n",
"\t\t\tif err != nil {\n",
"\t\t\t\terr = fmt.Errorf(\"queries and expressions execution failed: %w; %v\", err, panicErr.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\terr = panicErr\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}()\n",
"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 222
} | // Libraries
import React, { PureComponent } from 'react';
// Utils & Services
import { CustomScrollbar, stylesFactory } from '@grafana/ui';
import config from 'app/core/config';
import { feedToDataFrame } from './utils';
import { loadRSSFeed } from './rss';
// Types
import { PanelProps, DataFrameView, dateTimeFormat, GrafanaTheme2, textUtil } from '@grafana/data';
import { NewsItem } from './types';
import { PanelOptions } from './models.gen';
import { DEFAULT_FEED_URL, PROXY_PREFIX } from './constants';
import { css, cx } from '@emotion/css';
interface Props extends PanelProps<PanelOptions> {}
interface State {
news?: DataFrameView<NewsItem>;
isError?: boolean;
}
export class NewsPanel extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {};
}
componentDidMount(): void {
this.loadChannel();
}
componentDidUpdate(prevProps: Props): void {
if (this.props.options.feedUrl !== prevProps.options.feedUrl) {
this.loadChannel();
}
}
async loadChannel() {
const { options } = this.props;
try {
const url = options.feedUrl
? options.useProxy
? `${PROXY_PREFIX}${options.feedUrl}`
: options.feedUrl
: DEFAULT_FEED_URL;
const res = await loadRSSFeed(url);
const frame = feedToDataFrame(res);
this.setState({
news: new DataFrameView<NewsItem>(frame),
isError: false,
});
} catch (err) {
console.error('Error Loading News', err);
this.setState({
news: undefined,
isError: true,
});
}
}
render() {
const { width } = this.props;
const { showImage } = this.props.options;
const { isError, news } = this.state;
const styles = getStyles(config.theme2);
const useWideLayout = width > 600;
if (isError) {
return <div>Error Loading News</div>;
}
if (!news) {
return <div>loading...</div>;
}
return (
<CustomScrollbar autoHeightMin="100%" autoHeightMax="100%">
{news.map((item, index) => {
return (
<div key={index} className={cx(styles.item, useWideLayout && styles.itemWide)}>
{showImage && item.ogImage && (
<a
href={textUtil.sanitizeUrl(item.link)}
target="_blank"
rel="noopener noreferrer"
className={cx(styles.socialImage, useWideLayout && styles.socialImageWide)}
>
<img src={item.ogImage} />
</a>
)}
<div className={styles.body}>
<div className={styles.date}>{dateTimeFormat(item.date, { format: 'MMM DD' })} </div>
<a
className={styles.link}
href={textUtil.sanitizeUrl(item.link)}
target="_blank"
rel="noopener noreferrer"
>
<div className={styles.title}>{item.title}</div>
</a>
<div className={styles.content} dangerouslySetInnerHTML={{ __html: textUtil.sanitize(item.content) }} />
</div>
</div>
);
})}
</CustomScrollbar>
);
}
}
const getStyles = stylesFactory((theme: GrafanaTheme2) => ({
container: css`
height: 100%;
`,
item: css`
display: flex;
padding: ${theme.spacing(1)};
position: relative;
margin-bottom: 4px;
margin-right: ${theme.spacing(1)};
border-bottom: 2px solid ${theme.colors.border.weak};
background: ${theme.colors.background.primary};
flex-direction: column;
flex-shrink: 0;
`,
itemWide: css`
flex-direction: row;
`,
body: css``,
socialImage: css`
display: flex;
align-items: center;
margin-bottom: ${theme.spacing(1)};
> img {
width: 100%;
border-radius: ${theme.shape.borderRadius(2)} ${theme.shape.borderRadius(2)} 0 0;
}
`,
socialImageWide: css`
margin-right: ${theme.spacing(2)};
margin-bottom: 0;
> img {
width: 250px;
border-radius: ${theme.shape.borderRadius()};
}
`,
link: css`
color: ${theme.colors.text.link};
&:hover {
color: ${theme.colors.text.link};
text-decoration: underline;
}
`,
title: css`
max-width: calc(100% - 70px);
font-size: 16px;
margin-bottom: ${theme.spacing(0.5)};
`,
content: css`
p {
margin-bottom: 4px;
color: ${theme.colors.text};
}
`,
date: css`
margin-bottom: ${theme.spacing(0.5)};
font-weight: 500;
border-radius: 0 0 0 3px;
color: ${theme.colors.text.secondary};
`,
}));
| public/app/plugins/panel/news/NewsPanel.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001770197122823447,
0.00017358263721689582,
0.00016899917682167143,
0.00017380961799062788,
0.0000020576053429977037
] |
{
"id": 11,
"code_window": [
"\n",
"\treturn result\n",
"}\n",
"\n",
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {\n",
"\tqueryDataReq, err := GetExprRequest(ctx, data, now)\n",
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (resp *backend.QueryDataResponse, err error) {\n",
"\tdefer func() {\n",
"\t\tif e := recover(); e != nil {\n",
"\t\t\tctx.Log.Error(\"alert rule panic\", \"error\", e, \"stack\", string(debug.Stack()))\n",
"\t\t\tpanicErr := fmt.Errorf(\"alert rule panic; please check the logs for the full stack\")\n",
"\t\t\tif err != nil {\n",
"\t\t\t\terr = fmt.Errorf(\"queries and expressions execution failed: %w; %v\", err, panicErr.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\terr = panicErr\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}()\n",
"\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 222
} | +++
title = "Release notes for Grafana 8.0.1"
[_build]
list = false
+++
<!-- Auto generated by update changelog github action -->
# Release notes for Grafana 8.0.1
### Bug fixes
* **Alerting/SSE:** Fix "count_non_null" reducer validation. [#35451](https://github.com/grafana/grafana/pull/35451), [@kylebrandt](https://github.com/kylebrandt)
* **Cloudwatch:** Fix duplicated time series. [#35433](https://github.com/grafana/grafana/pull/35433), [@sunker](https://github.com/sunker)
* **Cloudwatch:** Fix missing defaultRegion. [#35436](https://github.com/grafana/grafana/pull/35436), [@andresmgot](https://github.com/andresmgot)
* **Dashboard:** Fix Dashboard init failed error on dashboards with old singlestat panels in collapsed rows. [#35425](https://github.com/grafana/grafana/pull/35425), [@torkelo](https://github.com/torkelo)
* **Datasource:** Fix storing timeout option as numeric. [#35441](https://github.com/grafana/grafana/pull/35441), [@marefr](https://github.com/marefr)
* **Postgres/MySQL/MSSQL:** Fix annotation parsing for empty responses. [#35367](https://github.com/grafana/grafana/pull/35367), [@marcbachmann](https://github.com/marcbachmann)
* **Postgres/MySQL/MSSQL:** Numeric/non-string values are now returned from query variables. [#35411](https://github.com/grafana/grafana/pull/35411), [@marefr](https://github.com/marefr)
* **Postgres:** Fix an error that was thrown when the annotation query did not return any results. [#35382](https://github.com/grafana/grafana/pull/35382), [@dprokop](https://github.com/dprokop)
* **StatPanel:** Fix an issue with the appearance of the graph when switching color mode. [#35460](https://github.com/grafana/grafana/pull/35460), [@torkelo](https://github.com/torkelo)
* **Visualizations:** Fix an issue in the Stat/BarGauge/Gauge/PieChart panels where all values mode were showing the same name if they had the same value.. [#35368](https://github.com/grafana/grafana/pull/35368), [@torkelo](https://github.com/torkelo)
### Plugin development fixes & changes
* **Toolkit:** Resolve external fonts when Grafana is served from a sub path. [#35352](https://github.com/grafana/grafana/pull/35352), [@jackw](https://github.com/jackw)
| docs/sources/release-notes/release-notes-8-0-1.md | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017544788715895265,
0.00017036324425134808,
0.00016256191884167492,
0.00017307994130533189,
0.0000056004382713581435
] |
{
"id": 12,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult := executeCondition(alertExecCtx, condition, now, dataService)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 412
} | // Package eval executes the condition for an alert definition, evaluates the condition results, and
// returns the alert instance states.
package eval
import (
"context"
"fmt"
"sort"
"time"
"github.com/grafana/grafana/pkg/expr/classic"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
)
const alertingEvaluationTimeout = 30 * time.Second
type Evaluator struct {
Cfg *setting.Cfg
}
// invalidEvalResultFormatError is an error for invalid format of the alert definition evaluation results.
type invalidEvalResultFormatError struct {
refID string
reason string
err error
}
func (e *invalidEvalResultFormatError) Error() string {
s := fmt.Sprintf("invalid format of evaluation results for the alert definition %s: %s", e.refID, e.reason)
if e.err != nil {
s = fmt.Sprintf("%s: %s", s, e.err.Error())
}
return s
}
func (e *invalidEvalResultFormatError) Unwrap() error {
return e.err
}
// ExecutionResults contains the unevaluated results from executing
// a condition.
type ExecutionResults struct {
Error error
Results data.Frames
}
// Results is a slice of evaluated alert instances states.
type Results []Result
// Result contains the evaluated State of an alert instance
// identified by its labels.
type Result struct {
Instance data.Labels
State State // Enum
// Error message for Error state. should be nil if State != Error.
Error error
EvaluatedAt time.Time
EvaluationDuration time.Duration
// EvaluationSring is a string representation of evaluation data such
// as EvalMatches (from "classic condition"), and in the future from operations
// like SSE "math".
EvaluationString string
}
// State is an enum of the evaluation State for an alert instance.
type State int
const (
// Normal is the eval state for an alert instance condition
// that evaluated to false.
Normal State = iota
// Alerting is the eval state for an alert instance condition
// that evaluated to true (Alerting).
Alerting
// Pending is the eval state for an alert instance condition
// that evaluated to true (Alerting) but has not yet met
// the For duration defined in AlertRule.
Pending
// NoData is the eval state for an alert rule condition
// that evaluated to NoData.
NoData
// Error is the eval state for an alert rule condition
// that evaluated to Error.
Error
)
func (s State) String() string {
return [...]string{"Normal", "Alerting", "Pending", "NoData", "Error"}[s]
}
// AlertExecCtx is the context provided for executing an alert condition.
type AlertExecCtx struct {
OrgID int64
ExpressionsEnabled bool
Ctx context.Context
}
// GetExprRequest validates the condition and creates a expr.Request from it.
func GetExprRequest(ctx AlertExecCtx, data []models.AlertQuery, now time.Time) (*expr.Request, error) {
req := &expr.Request{
OrgId: ctx.OrgID,
}
for i := range data {
q := data[i]
model, err := q.GetModel()
if err != nil {
return nil, fmt.Errorf("failed to get query model: %w", err)
}
interval, err := q.GetIntervalDuration()
if err != nil {
return nil, fmt.Errorf("failed to retrieve intervalMs from the model: %w", err)
}
maxDatapoints, err := q.GetMaxDatapoints()
if err != nil {
return nil, fmt.Errorf("failed to retrieve maxDatapoints from the model: %w", err)
}
req.Queries = append(req.Queries, expr.Query{
TimeRange: expr.TimeRange{
From: q.RelativeTimeRange.ToTimeRange(now).From,
To: q.RelativeTimeRange.ToTimeRange(now).To,
},
DatasourceUID: q.DatasourceUID,
JSON: model,
Interval: interval,
RefID: q.RefID,
MaxDataPoints: maxDatapoints,
QueryType: q.QueryType,
})
}
return req, nil
}
type NumberValueCapture struct {
Var string // RefID
Labels data.Labels
Value *float64
}
func executeCondition(ctx AlertExecCtx, c *models.Condition, now time.Time, dataService *tsdb.Service) ExecutionResults {
result := ExecutionResults{}
execResp, err := executeQueriesAndExpressions(ctx, c.Data, now, dataService)
if err != nil {
return ExecutionResults{Error: err}
}
// eval captures for the '__value__' label.
captures := make([]NumberValueCapture, 0, len(execResp.Responses))
captureVal := func(refID string, labels data.Labels, value *float64) {
captures = append(captures, NumberValueCapture{
Var: refID,
Value: value,
Labels: labels.Copy(),
})
}
for refID, res := range execResp.Responses {
// for each frame within each response, the response can contain several data types including time-series data.
// For now, we favour simplicity and only care about single scalar values.
for _, frame := range res.Frames {
if len(frame.Fields) != 1 || frame.Fields[0].Type() != data.FieldTypeNullableFloat64 {
continue
}
var v *float64
if frame.Fields[0].Len() == 1 {
v = frame.At(0, 0).(*float64) // type checked above
}
captureVal(frame.RefID, frame.Fields[0].Labels, v)
}
if refID == c.Condition {
result.Results = res.Frames
}
}
// add capture values as data frame metadata to each result (frame) that has matching labels.
for _, frame := range result.Results {
// classic conditions already have metadata set and only have one value, there's no need to add anything in this case.
if frame.Meta != nil && frame.Meta.Custom != nil {
if _, ok := frame.Meta.Custom.([]classic.EvalMatch); ok {
continue // do not overwrite EvalMatch from classic condition.
}
}
frame.SetMeta(&data.FrameMeta{}) // overwrite metadata
if len(frame.Fields) == 1 {
theseLabels := frame.Fields[0].Labels
for _, cap := range captures {
// matching labels are equal labels, or when one set of labels includes the labels of the other.
if theseLabels.Equals(cap.Labels) || theseLabels.Contains(cap.Labels) || cap.Labels.Contains(theseLabels) {
if frame.Meta.Custom == nil {
frame.Meta.Custom = []NumberValueCapture{}
}
frame.Meta.Custom = append(frame.Meta.Custom.([]NumberValueCapture), cap)
}
}
}
}
return result
}
func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
queryDataReq, err := GetExprRequest(ctx, data, now)
if err != nil {
return nil, err
}
exprService := expr.Service{
Cfg: &setting.Cfg{ExpressionsEnabled: ctx.ExpressionsEnabled},
DataService: dataService,
}
return exprService.TransformData(ctx.Ctx, queryDataReq)
}
// evaluateExecutionResult takes the ExecutionResult which includes data.Frames returned
// from SSE (Server Side Expressions). It will create Results (slice of Result) with a State
// extracted from each Frame.
//
// If the ExecutionResults error property is not nil, a single Error result will be returned.
// If there is no error and no results then a single NoData state Result will be returned.
//
// Each non-empty Frame must be a single Field of type []*float64 and of length 1.
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
appendErrRes := func(e error) {
evalResults = append(evalResults, Result{
State: Error,
Error: e,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
appendNoData := func(l data.Labels) {
evalResults = append(evalResults, Result{
State: NoData,
Instance: l,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
})
}
if execResults.Error != nil {
appendErrRes(execResults.Error)
return evalResults
}
if len(execResults.Results) == 0 {
appendNoData(nil)
return evalResults
}
for _, f := range execResults.Results {
rowLen, err := f.RowLen()
if err != nil {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "unable to get frame row length", err: err})
continue
}
if len(f.TypeIndices(data.FieldTypeTime, data.FieldTypeNullableTime)) > 0 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: "looks like time series data, only reduced data can be alerted on."})
continue
}
if rowLen == 0 {
if len(f.Fields) == 0 {
appendNoData(nil)
continue
}
if len(f.Fields) == 1 {
appendNoData(f.Fields[0].Labels)
continue
}
}
if rowLen > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected row length: %d instead of 0 or 1", rowLen)})
continue
}
if len(f.Fields) > 1 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("unexpected field length: %d instead of 1", len(f.Fields))})
continue
}
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
appendErrRes(&invalidEvalResultFormatError{refID: f.RefID, reason: fmt.Sprintf("invalid field type: %s", f.Fields[0].Type())})
continue
}
val := f.Fields[0].At(0).(*float64) // type checked by data.FieldTypeNullableFloat64 above
r := Result{
Instance: f.Fields[0].Labels,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
EvaluationString: extractEvalString(f),
}
switch {
case val == nil:
r.State = NoData
case *val == 0:
r.State = Normal
default:
r.State = Alerting
}
evalResults = append(evalResults, r)
}
seenLabels := make(map[string]bool)
for _, res := range evalResults {
labelsStr := res.Instance.String()
_, ok := seenLabels[labelsStr]
if ok {
return Results{
Result{
State: Error,
Instance: res.Instance,
EvaluatedAt: ts,
EvaluationDuration: time.Since(ts),
Error: &invalidEvalResultFormatError{reason: fmt.Sprintf("frame cannot uniquely be identified by its labels: has duplicate results with labels {%s}", labelsStr)},
},
}
}
seenLabels[labelsStr] = true
}
return evalResults
}
// AsDataFrame forms the EvalResults in Frame suitable for displaying in the table panel of the front end.
// It displays one row per alert instance, with a column for each label and one for the alerting state.
func (evalResults Results) AsDataFrame() data.Frame {
fieldLen := len(evalResults)
uniqueLabelKeys := make(map[string]struct{})
for _, evalResult := range evalResults {
for k := range evalResult.Instance {
uniqueLabelKeys[k] = struct{}{}
}
}
labelColumns := make([]string, 0, len(uniqueLabelKeys))
for k := range uniqueLabelKeys {
labelColumns = append(labelColumns, k)
}
labelColumns = sort.StringSlice(labelColumns)
frame := data.NewFrame("evaluation results")
for _, lKey := range labelColumns {
frame.Fields = append(frame.Fields, data.NewField(lKey, nil, make([]string, fieldLen)))
}
frame.Fields = append(frame.Fields, data.NewField("State", nil, make([]string, fieldLen)))
frame.Fields = append(frame.Fields, data.NewField("Info", nil, make([]string, fieldLen)))
for evalIdx, evalResult := range evalResults {
for lIdx, v := range labelColumns {
frame.Set(lIdx, evalIdx, evalResult.Instance[v])
}
frame.Set(len(labelColumns), evalIdx, evalResult.State.String())
switch {
case evalResult.Error != nil:
frame.Set(len(labelColumns)+1, evalIdx, evalResult.Error.Error())
case evalResult.EvaluationString != "":
frame.Set(len(labelColumns)+1, evalIdx, evalResult.EvaluationString)
}
}
return *frame
}
// ConditionEval executes conditions and evaluates the result.
func (e *Evaluator) ConditionEval(condition *models.Condition, now time.Time, dataService *tsdb.Service) (Results, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult := executeCondition(alertExecCtx, condition, now, dataService)
evalResults := evaluateExecutionResult(execResult, now)
return evalResults, nil
}
// QueriesAndExpressionsEval executes queries and expressions and returns the result.
func (e *Evaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, dataService *tsdb.Service) (*backend.QueryDataResponse, error) {
alertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)
defer cancelFn()
alertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}
execResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)
if err != nil {
return nil, fmt.Errorf("failed to execute conditions: %w", err)
}
return execResult, nil
}
| pkg/services/ngalert/eval/eval.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.9979844093322754,
0.1268082708120346,
0.00016377828433178365,
0.0001764807675499469,
0.302673876285553
] |
{
"id": 12,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult := executeCondition(alertExecCtx, condition, now, dataService)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 412
} | import React, { createRef, FC } from 'react';
import { VirtualElement } from '@popperjs/core';
import { Popover } from './Popover';
import { PopoverController, UsingPopperProps } from './PopoverController';
export interface TooltipProps extends UsingPopperProps {
theme?: 'info' | 'error' | 'info-alt';
}
export interface PopoverContentProps {
updatePopperPosition?: () => void;
}
export type PopoverContent = string | React.ReactElement<any> | ((props: PopoverContentProps) => JSX.Element);
export const Tooltip: FC<TooltipProps> = React.memo(({ children, theme, ...controllerProps }: TooltipProps) => {
const tooltipTriggerRef = createRef<HTMLElement | VirtualElement>();
const popperBackgroundClassName = 'popper__background' + (theme ? ' popper__background--' + theme : '');
return (
<PopoverController {...controllerProps}>
{(showPopper, hidePopper, popperProps) => {
{
/* Override internal 'show' state if passed in as prop */
}
const payloadProps = {
...popperProps,
show: controllerProps.show !== undefined ? controllerProps.show : popperProps.show,
};
return (
<>
{tooltipTriggerRef.current && controllerProps.content && (
<Popover
{...payloadProps}
onMouseEnter={showPopper}
onMouseLeave={hidePopper}
referenceElement={tooltipTriggerRef.current}
wrapperClassName="popper"
className={popperBackgroundClassName}
renderArrow={({ arrowProps, placement }) => (
<div className="popper__arrow" data-placement={placement} {...arrowProps} />
)}
/>
)}
{React.cloneElement(children, {
ref: tooltipTriggerRef,
onMouseEnter: showPopper,
onMouseLeave: hidePopper,
})}
</>
);
}}
</PopoverController>
);
});
Tooltip.displayName = 'Tooltip';
| packages/grafana-ui/src/components/Tooltip/Tooltip.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017886620480567217,
0.00017478532390668988,
0.00017104622384067625,
0.00017472065519541502,
0.0000027804007913800888
] |
{
"id": 12,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult := executeCondition(alertExecCtx, condition, now, dataService)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 412
} | ---
title: Navigate to user preferences list
---
1. On the left menu, hover your cursor over your avatar and then click **Preferences**. | docs/sources/shared/preferences/navigate-user-preferences-list.md | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017195493273902684,
0.00017195493273902684,
0.00017195493273902684,
0.00017195493273902684,
0
] |
{
"id": 12,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult := executeCondition(alertExecCtx, condition, now, dataService)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: condition.OrgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 412
} | import React, { useEffect, useState } from 'react';
import { css } from '@emotion/css';
import { AppRootProps, GrafanaTheme2 } from '@grafana/data';
import { useStyles2, TabsBar, TabContent, Tab, Icon } from '@grafana/ui';
import { useParams } from 'react-router-dom';
import { VersionList } from '../components/VersionList';
import { InstallControls } from '../components/InstallControls';
import { PLUGIN_ROOT, GRAFANA_API_ROOT } from '../constants';
import { usePlugin } from '../hooks/usePlugins';
import { Page } from 'components/Page';
import { Loader } from 'components/Loader';
export const PluginDetails = ({ onNavChanged }: AppRootProps) => {
const { pluginId } = useParams<{ pluginId: string }>();
const [tabs, setTabs] = useState([
{ label: 'Overview', active: true },
{ label: 'Version history', active: false },
]);
const { isLoading, local, remote, remoteVersions } = usePlugin(pluginId);
const styles = useStyles2(getStyles);
const description = remote?.description;
const readme = remote?.readme;
const version = local?.info?.version || remote?.version;
const links = (local?.info?.links || remote?.json?.info?.links) ?? [];
const downloads = remote?.downloads;
useEffect(() => {
onNavChanged(undefined as any);
}, [onNavChanged]);
if (isLoading) {
return <Loader />;
}
return (
<Page>
<div className={styles.headerContainer}>
<img
src={`${GRAFANA_API_ROOT}/plugins/${pluginId}/versions/${remote?.version}/logos/small`}
className={css`
object-fit: cover;
width: 100%;
height: 68px;
max-width: 68px;
`}
/>
<div className={styles.headerWrapper}>
<h1>{remote?.name}</h1>
<div className={styles.headerLinks}>
<a className={styles.headerOrgName} href={`${PLUGIN_ROOT}`}>
{remote?.orgName}
</a>
{links.map((link: any) => (
<a key={link.name} href={link.url}>
{link.name}
</a>
))}
{downloads && (
<span>
<Icon name="cloud-download" />
{` ${new Intl.NumberFormat().format(downloads)}`}{' '}
</span>
)}
{version && <span>{version}</span>}
</div>
<p>{description}</p>
{remote && <InstallControls localPlugin={local} remotePlugin={remote} />}
</div>
</div>
<TabsBar>
{tabs.map((tab, key) => (
<Tab
key={key}
label={tab.label}
active={tab.active}
onChangeTab={() => {
setTabs(tabs.map((tab, index) => ({ ...tab, active: index === key })));
}}
/>
))}
</TabsBar>
<TabContent>
{tabs.find((_) => _.label === 'Overview')?.active && (
<div className={styles.readme} dangerouslySetInnerHTML={{ __html: readme ?? '' }} />
)}
{tabs.find((_) => _.label === 'Version history')?.active && <VersionList versions={remoteVersions ?? []} />}
</TabContent>
</Page>
);
};
export const getStyles = (theme: GrafanaTheme2) => {
return {
headerContainer: css`
display: flex;
margin-bottom: 24px;
margin-top: 24px;
min-height: 120px;
`,
headerWrapper: css`
margin-left: ${theme.spacing(3)};
`,
headerLinks: css`
display: flex;
align-items: center;
margin-top: ${theme.spacing()};
margin-bottom: ${theme.spacing(3)};
& > * {
&::after {
content: '|';
padding: 0 ${theme.spacing()};
}
}
& > *:last-child {
&::after {
content: '';
padding-right: 0;
}
}
font-size: ${theme.typography.h4.fontSize};
`,
headerOrgName: css`
font-size: ${theme.typography.h4.fontSize};
`,
message: css`
color: ${theme.colors.text.secondary};
`,
readme: css`
padding: ${theme.spacing(3, 4)};
& img {
max-width: 100%;
}
h1,
h2,
h3 {
margin-top: ${theme.spacing(3)};
margin-bottom: ${theme.spacing(2)};
}
*:first-child {
margin-top: 0;
}
li {
margin-left: ${theme.spacing(2)};
& > p {
margin: ${theme.spacing()} 0;
}
}
`,
};
};
| plugins-bundled/internal/plugin-admin-app/src/pages/PluginDetails.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017987545288633555,
0.0001755792909534648,
0.00016712093201931566,
0.0001761744060786441,
0.000003273914444434922
] |
{
"id": 13,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn nil, fmt.Errorf(\"failed to execute conditions: %w\", err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 425
} | package ngalert
import (
"context"
"time"
"github.com/grafana/grafana/pkg/services/quota"
"golang.org/x/sync/errgroup"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
"github.com/grafana/grafana/pkg/services/ngalert/state"
"github.com/benbjohnson/clock"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/ngalert/api"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/ngalert/schedule"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
)
const (
maxAttempts int64 = 3
// scheduler interval
// changing this value is discouraged
// because this could cause existing alert definition
// with intervals that are not exactly divided by this number
// not to be evaluated
baseIntervalSeconds = 10
// default alert definiiton interval
defaultIntervalSeconds int64 = 6 * baseIntervalSeconds
)
// AlertNG is the service for evaluating the condition of an alert definition.
type AlertNG struct {
Cfg *setting.Cfg `inject:""`
DatasourceCache datasources.CacheService `inject:""`
RouteRegister routing.RouteRegister `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
DataService *tsdb.Service `inject:""`
DataProxy *datasourceproxy.DatasourceProxyService `inject:""`
QuotaService *quota.QuotaService `inject:""`
Metrics *metrics.Metrics `inject:""`
Alertmanager *notifier.Alertmanager
Log log.Logger
schedule schedule.ScheduleService
stateManager *state.Manager
}
func init() {
registry.RegisterService(&AlertNG{})
}
// Init initializes the AlertingService.
func (ng *AlertNG) Init() error {
ng.Log = log.New("ngalert")
ng.stateManager = state.NewManager(ng.Log, ng.Metrics)
baseInterval := baseIntervalSeconds * time.Second
store := &store.DBstore{
BaseInterval: baseInterval,
DefaultIntervalSeconds: defaultIntervalSeconds,
SQLStore: ng.SQLStore,
Logger: ng.Log,
}
var err error
ng.Alertmanager, err = notifier.New(ng.Cfg, store, ng.Metrics)
if err != nil {
return err
}
schedCfg := schedule.SchedulerCfg{
C: clock.New(),
BaseInterval: baseInterval,
Logger: ng.Log,
MaxAttempts: maxAttempts,
Evaluator: eval.Evaluator{Cfg: ng.Cfg},
InstanceStore: store,
RuleStore: store,
Notifier: ng.Alertmanager,
Metrics: ng.Metrics,
}
ng.schedule = schedule.NewScheduler(schedCfg, ng.DataService)
api := api.API{
Cfg: ng.Cfg,
DatasourceCache: ng.DatasourceCache,
RouteRegister: ng.RouteRegister,
DataService: ng.DataService,
Schedule: ng.schedule,
DataProxy: ng.DataProxy,
QuotaService: ng.QuotaService,
InstanceStore: store,
RuleStore: store,
AlertingStore: store,
Alertmanager: ng.Alertmanager,
StateManager: ng.stateManager,
}
api.RegisterAPIEndpoints(ng.Metrics)
return nil
}
// Run starts the scheduler.
func (ng *AlertNG) Run(ctx context.Context) error {
ng.Log.Debug("ngalert starting")
ng.schedule.WarmStateCache(ng.stateManager)
children, subCtx := errgroup.WithContext(ctx)
children.Go(func() error {
return ng.schedule.Ticker(subCtx, ng.stateManager)
})
children.Go(func() error {
return ng.Alertmanager.Run(subCtx)
})
return children.Wait()
}
// IsDisabled returns true if the alerting service is disable for this instance.
func (ng *AlertNG) IsDisabled() bool {
if ng.Cfg == nil {
return true
}
return !ng.Cfg.IsNgAlertEnabled()
}
| pkg/services/ngalert/ngalert.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0006049529765732586,
0.00021976559946779162,
0.00016351054364349693,
0.0001697814732324332,
0.0001240931305801496
] |
{
"id": 13,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn nil, fmt.Errorf(\"failed to execute conditions: %w\", err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 425
} | import React from 'react';
import { ToolbarButton, VerticalGroup } from '@grafana/ui';
import { withCenteredStory } from '../../utils/storybook/withCenteredStory';
import { PageToolbar } from './PageToolbar';
import { StoryExample } from '../../utils/storybook/StoryExample';
import { action } from '@storybook/addon-actions';
import { IconButton } from '../IconButton/IconButton';
export default {
title: 'Layout/PageToolbar',
component: PageToolbar,
decorators: [withCenteredStory],
parameters: {},
};
export const Examples = () => {
return (
<VerticalGroup>
<StoryExample name="With non clickable title">
<PageToolbar pageIcon="bell" title="Dashboard">
<ToolbarButton icon="panel-add" />
<ToolbarButton icon="sync">Sync</ToolbarButton>
</PageToolbar>
</StoryExample>
<StoryExample name="With clickable title and parent">
<PageToolbar
pageIcon="apps"
title="A very long dashboard name"
parent="A long folder name"
onClickTitle={() => action('Title clicked')}
onClickParent={() => action('Parent clicked')}
leftItems={[
<IconButton name="share-alt" size="lg" key="share" />,
<IconButton name="favorite" iconType="mono" size="lg" key="favorite" />,
]}
>
<ToolbarButton icon="panel-add" />
<ToolbarButton icon="share-alt" />
<ToolbarButton icon="sync">Sync</ToolbarButton>
<ToolbarButton icon="cog">Settings </ToolbarButton>
</PageToolbar>
</StoryExample>
<StoryExample name="Go back version">
<PageToolbar title="Service overview / Edit panel" onGoBack={() => action('Go back')}>
<ToolbarButton icon="cog" />
<ToolbarButton icon="save" />
<ToolbarButton>Discard</ToolbarButton>
<ToolbarButton>Apply</ToolbarButton>
</PageToolbar>
</StoryExample>
</VerticalGroup>
);
};
| packages/grafana-ui/src/components/PageLayout/PageToolbar.story.tsx | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017706833023112267,
0.00017437666247133166,
0.00017164844030048698,
0.00017445249250158668,
0.000001641047219891334
] |
{
"id": 13,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn nil, fmt.Errorf(\"failed to execute conditions: %w\", err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 425
} | $font-size-heatmap-tick: 11px;
.heatmap-canvas-wrapper {
// position: relative;
cursor: crosshair;
}
.heatmap-panel {
position: relative;
.axis .tick {
text {
fill: $text-color;
color: $text-color;
font-size: $font-size-heatmap-tick;
}
line {
opacity: 0.4;
stroke: $text-color-weak;
}
}
// This hack prevents mouseenter/mouseleave events get fired too often
svg {
pointer-events: none;
rect {
pointer-events: visiblePainted;
}
}
}
.heatmap-tooltip {
white-space: nowrap;
font-size: $font-size-sm;
background-color: $graph-tooltip-bg;
color: $text-color;
}
.heatmap-histogram rect {
fill: $text-color-weak;
}
.heatmap-crosshair {
line {
stroke: darken($red, 15%);
stroke-width: 1;
}
}
.heatmap-selection {
stroke-width: 1;
fill: rgba(102, 102, 102, 0.4);
stroke: rgba(102, 102, 102, 0.8);
}
.heatmap-legend-wrapper {
@include clearfix();
margin: 0 $spacer;
padding-top: 4px;
svg {
width: 100%;
max-width: 300px;
height: 18px;
float: left;
white-space: nowrap;
}
.heatmap-legend-values {
display: inline-block;
}
.axis .tick {
text {
fill: $text-color;
color: $text-color;
font-size: $font-size-heatmap-tick;
}
line {
opacity: 0.4;
stroke: $text-color-weak;
}
.domain {
opacity: 0.4;
stroke: $text-color-weak;
}
}
}
| public/sass/components/_panel_heatmap.scss | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017910153837874532,
0.0001760490267770365,
0.0001732883247314021,
0.00017534723156131804,
0.0000019166734546161024
] |
{
"id": 13,
"code_window": [
"\talertCtx, cancelFn := context.WithTimeout(context.Background(), alertingEvaluationTimeout)\n",
"\tdefer cancelFn()\n",
"\n",
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled}\n",
"\n",
"\texecResult, err := executeQueriesAndExpressions(alertExecCtx, data, now, dataService)\n",
"\tif err != nil {\n",
"\t\treturn nil, fmt.Errorf(\"failed to execute conditions: %w\", err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\talertExecCtx := AlertExecCtx{OrgID: orgID, Ctx: alertCtx, ExpressionsEnabled: e.Cfg.ExpressionsEnabled, Log: e.Log}\n"
],
"file_path": "pkg/services/ngalert/eval/eval.go",
"type": "replace",
"edit_start_line_idx": 425
} | import React from 'react';
import ReactDOM from 'react-dom';
import coreModule from 'app/core/core_module';
import appEvents from 'app/core/app_events';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { AngularModalProxy } from '../components/modals/AngularModalProxy';
import { provideTheme } from '../utils/ConfigProvider';
import {
HideModalEvent,
ShowConfirmModalEvent,
ShowConfirmModalPayload,
ShowModalEvent,
ShowModalReactEvent,
} from '../../types/events';
import { ConfirmModal, ConfirmModalProps } from '@grafana/ui';
import { deprecationWarning, textUtil } from '@grafana/data';
export class UtilSrv {
modalScope: any;
reactModalRoot = document.body;
reactModalNode = document.createElement('div');
/** @ngInject */
constructor(private $rootScope: GrafanaRootScope, private $modal: any) {
this.reactModalNode.setAttribute('id', 'angular2ReactModalRoot');
}
init() {
appEvents.subscribe(ShowModalEvent, (e) => this.showModal(e.payload));
appEvents.subscribe(HideModalEvent, this.hideModal.bind(this));
appEvents.subscribe(ShowConfirmModalEvent, (e) => this.showConfirmModal(e.payload));
appEvents.subscribe(ShowModalReactEvent, (e) => this.showModalReact(e.payload));
}
showModalReact(options: any) {
const { component, props } = options;
const modalProps = {
component,
props: {
...props,
isOpen: true,
onDismiss: this.onReactModalDismiss,
},
};
const elem = React.createElement(provideTheme(AngularModalProxy), modalProps);
this.reactModalRoot.appendChild(this.reactModalNode);
ReactDOM.render(elem, this.reactModalNode);
}
onReactModalDismiss = () => {
ReactDOM.unmountComponentAtNode(this.reactModalNode);
this.reactModalRoot.removeChild(this.reactModalNode);
};
/**
* @deprecated use showModalReact instead that has this capability built in
*/
hideModal() {
deprecationWarning('UtilSrv', 'hideModal', 'showModalReact');
if (this.modalScope && this.modalScope.dismiss) {
this.modalScope.dismiss();
}
}
/**
* @deprecated use showModalReact instead
*/
showModal(options: any) {
deprecationWarning('UtilSrv', 'showModal', 'showModalReact');
if (this.modalScope && this.modalScope.dismiss) {
this.modalScope.dismiss();
}
this.modalScope = options.scope;
if (options.model) {
this.modalScope = this.$rootScope.$new();
this.modalScope.model = options.model;
} else if (!this.modalScope) {
this.modalScope = this.$rootScope.$new();
}
const modal = this.$modal({
modalClass: options.modalClass,
template: options.src,
templateHtml: options.templateHtml,
persist: false,
show: false,
scope: this.modalScope,
keyboard: false,
backdrop: options.backdrop,
});
Promise.resolve(modal).then((modalEl) => {
modalEl.modal('show');
});
}
showConfirmModal(payload: ShowConfirmModalPayload) {
const {
confirmText,
onConfirm = () => undefined,
text2,
altActionText,
onAltAction,
noText,
text,
text2htmlBind,
yesText = 'Yes',
icon,
title = 'Confirm',
} = payload;
const props: ConfirmModalProps = {
confirmText: yesText,
confirmationText: confirmText,
icon,
title,
body: text,
description: text2 && text2htmlBind ? textUtil.sanitize(text2) : text2,
isOpen: true,
dismissText: noText,
onConfirm: () => {
onConfirm();
this.onReactModalDismiss();
},
onDismiss: this.onReactModalDismiss,
onAlternative: onAltAction
? () => {
onAltAction();
this.onReactModalDismiss();
}
: undefined,
alternativeText: altActionText,
};
const modalProps = {
component: ConfirmModal,
props,
};
const elem = React.createElement(provideTheme(AngularModalProxy), modalProps);
this.reactModalRoot.appendChild(this.reactModalNode);
ReactDOM.render(elem, this.reactModalNode);
}
}
coreModule.service('utilSrv', UtilSrv);
| public/app/core/services/util_srv.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017779394693206996,
0.00017497992666903883,
0.00016800110461190343,
0.00017569246119819582,
0.000002585866241133772
] |
{
"id": 14,
"code_window": [
"\tschedCfg := schedule.SchedulerCfg{\n",
"\t\tC: clock.New(),\n",
"\t\tBaseInterval: baseInterval,\n",
"\t\tLogger: ng.Log,\n",
"\t\tMaxAttempts: maxAttempts,\n",
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg},\n",
"\t\tInstanceStore: store,\n",
"\t\tRuleStore: store,\n",
"\t\tNotifier: ng.Alertmanager,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg, Log: ng.Log},\n"
],
"file_path": "pkg/services/ngalert/ngalert.go",
"type": "replace",
"edit_start_line_idx": 85
} | package api
import (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb"
"github.com/grafana/grafana/pkg/util"
)
type TestingApiSrv struct {
*AlertingProxy
Cfg *setting.Cfg
DataService *tsdb.Service
DatasourceCache datasources.CacheService
log log.Logger
}
func (srv TestingApiSrv) RouteTestReceiverConfig(c *models.ReqContext, body apimodels.ExtendedReceiver) response.Response {
srv.log.Info("RouteTestReceiverConfig: ", "body", body)
return response.JSON(http.StatusOK, util.DynMap{"message": "success"})
}
func (srv TestingApiSrv) RouteTestRuleConfig(c *models.ReqContext, body apimodels.TestRulePayload) response.Response {
recipient := c.Params("Recipient")
if recipient == apimodels.GrafanaBackend.String() {
if body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {
return ErrResp(http.StatusBadRequest, errors.New("unexpected payload"), "")
}
return conditionEval(c, *body.GrafanaManagedCondition, srv.DatasourceCache, srv.DataService, srv.Cfg)
}
if body.Type() != apimodels.LoTexRulerBackend {
return ErrResp(http.StatusBadRequest, errors.New("unexpected payload"), "")
}
var path string
if datasourceID, err := strconv.ParseInt(recipient, 10, 64); err == nil {
ds, err := srv.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to get datasource")
}
switch ds.Type {
case "loki":
path = "loki/api/v1/query"
case "prometheus":
path = "api/v1/query"
default:
return ErrResp(http.StatusBadRequest, fmt.Errorf("unexpected recipient type %s", ds.Type), "")
}
}
t := timeNow()
queryURL, err := url.Parse(path)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to parse url")
}
params := queryURL.Query()
params.Set("query", body.Expr)
params.Set("time", strconv.FormatInt(t.Unix(), 10))
queryURL.RawQuery = params.Encode()
return srv.withReq(
c,
http.MethodGet,
queryURL,
nil,
instantQueryResultsExtractor,
nil,
)
}
func (srv TestingApiSrv) RouteEvalQueries(c *models.ReqContext, cmd apimodels.EvalQueriesPayload) response.Response {
now := cmd.Now
if now.IsZero() {
now = timeNow()
}
if _, err := validateQueriesAndExpressions(cmd.Data, c.SignedInUser, c.SkipCache, srv.DatasourceCache); err != nil {
return ErrResp(http.StatusBadRequest, err, "invalid queries or expressions")
}
evaluator := eval.Evaluator{Cfg: srv.Cfg}
evalResults, err := evaluator.QueriesAndExpressionsEval(c.SignedInUser.OrgId, cmd.Data, now, srv.DataService)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "Failed to evaluate queries and expressions")
}
return response.JSONStreaming(http.StatusOK, evalResults)
}
| pkg/services/ngalert/api/api_testing.go | 1 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0013934166636317968,
0.0002904547145590186,
0.00016855822468642145,
0.0001723140594549477,
0.00034966779639944434
] |
{
"id": 14,
"code_window": [
"\tschedCfg := schedule.SchedulerCfg{\n",
"\t\tC: clock.New(),\n",
"\t\tBaseInterval: baseInterval,\n",
"\t\tLogger: ng.Log,\n",
"\t\tMaxAttempts: maxAttempts,\n",
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg},\n",
"\t\tInstanceStore: store,\n",
"\t\tRuleStore: store,\n",
"\t\tNotifier: ng.Alertmanager,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg, Log: ng.Log},\n"
],
"file_path": "pkg/services/ngalert/ngalert.go",
"type": "replace",
"edit_start_line_idx": 85
} | //
// Modals
// --------------------------------------------------
// Background
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: $zindex-modal-backdrop;
background-color: $modal-backdrop-bg;
}
.modal-backdrop,
.modal-backdrop.fade.in {
@include opacity(70);
}
// Base modal
.modal {
position: fixed;
z-index: $zindex-modal;
width: 100%;
background: $page-bg;
@include box-shadow(0 3px 7px rgba(0, 0, 0, 0.3));
@include background-clip(padding-box);
outline: none;
max-width: 750px;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
top: 10%;
}
.modal-header {
background: $page-header-bg;
box-shadow: $page-header-shadow;
border-bottom: 1px solid $page-header-border-color;
display: flex;
align-items: center;
justify-content: space-between;
}
.modal-header-title {
font-size: $font-size-lg;
float: left;
padding-top: $space-sm;
margin: 0 $space-md;
}
.modal-header-close {
float: right;
padding: 9px $spacer;
}
// Body (where all modal content resides)
.modal-body {
position: relative;
}
.modal-content {
padding: $spacer * 2;
&--has-scroll {
max-height: calc(100vh - 400px);
position: relative;
}
}
// Remove bottom margin if need be
.modal-form {
margin-bottom: 0;
}
// Footer (for actions)
.modal-footer {
padding: 14px 15px 15px;
border-top: 1px solid $panel-bg;
background-color: $panel-bg;
text-align: right; // right align buttons
@include clearfix(); // clear it in case folks use .pull-* classes on buttons
}
.modal--narrow {
max-width: 500px;
}
.confirm-modal {
max-width: 500px;
.confirm-modal-icon {
padding-top: 41px;
font-size: 280%;
color: $green-base;
padding-bottom: 20px;
}
.confirm-modal-text {
font-size: $font-size-h4;
color: $link-color;
margin-bottom: $spacer * 2;
padding-top: $spacer;
}
.confirm-modal-text2 {
font-size: $font-size-base;
padding-top: $spacer;
}
.confirm-modal-buttons {
margin-bottom: $spacer;
button {
margin-right: $spacer/2;
}
}
.modal-content-confirm-text {
margin-bottom: $space-xl;
span {
text-align: center;
}
}
}
.share-modal-body {
.share-modal-options {
margin: 11px 0px 33px 0px;
display: inline-block;
}
.share-modal-big-icon {
margin-right: 8px;
margin-top: -7px;
}
.share-modal-info-text {
margin-top: 5px;
strong {
color: $text-color-emphasis;
font-weight: $font-weight-semi-bold;
}
}
.share-modal-header {
display: flex;
margin: 0px 0 22px 0;
}
.share-modal-content {
flex-grow: 1;
}
.share-modal-link {
max-width: 716px;
white-space: nowrap;
overflow: hidden;
display: block;
text-overflow: ellipsis;
}
}
| public/sass/components/_modals.scss | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.0001775408600224182,
0.00017481099348515272,
0.000170808270922862,
0.0001751022646203637,
0.0000018650001720743603
] |
{
"id": 14,
"code_window": [
"\tschedCfg := schedule.SchedulerCfg{\n",
"\t\tC: clock.New(),\n",
"\t\tBaseInterval: baseInterval,\n",
"\t\tLogger: ng.Log,\n",
"\t\tMaxAttempts: maxAttempts,\n",
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg},\n",
"\t\tInstanceStore: store,\n",
"\t\tRuleStore: store,\n",
"\t\tNotifier: ng.Alertmanager,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg, Log: ng.Log},\n"
],
"file_path": "pkg/services/ngalert/ngalert.go",
"type": "replace",
"edit_start_line_idx": 85
} | import { Observable } from 'rxjs';
type ObservableType<T> = T extends Observable<infer V> ? V : never;
declare global {
namespace jest {
interface Matchers<R, T = {}> {
toEmitValues<E = ObservableType<T>>(expected: E[]): Promise<CustomMatcherResult>;
/**
* Collect all the values emitted by the observables (also errors) and pass them to the expectations functions after
* the observable ended (or emitted error). If Observable does not complete within OBSERVABLE_TEST_TIMEOUT_IN_MS the
* test fails.
*/
toEmitValuesWith<E = ObservableType<T>>(expectations: (received: E[]) => void): Promise<CustomMatcherResult>;
}
}
}
| packages/grafana-data/typings/jest/index.d.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.000172468411619775,
0.00017031648894771934,
0.0001681645808275789,
0.00017031648894771934,
0.0000021519153960980475
] |
{
"id": 14,
"code_window": [
"\tschedCfg := schedule.SchedulerCfg{\n",
"\t\tC: clock.New(),\n",
"\t\tBaseInterval: baseInterval,\n",
"\t\tLogger: ng.Log,\n",
"\t\tMaxAttempts: maxAttempts,\n",
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg},\n",
"\t\tInstanceStore: store,\n",
"\t\tRuleStore: store,\n",
"\t\tNotifier: ng.Alertmanager,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tEvaluator: eval.Evaluator{Cfg: ng.Cfg, Log: ng.Log},\n"
],
"file_path": "pkg/services/ngalert/ngalert.go",
"type": "replace",
"edit_start_line_idx": 85
} | import {
DataQuery,
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
} from '@grafana/data';
import { DataSourceWithBackend } from '@grafana/runtime';
import { TraceToLogsData, TraceToLogsOptions } from 'app/core/components/TraceToLogsSettings';
import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
import { from, merge, Observable, throwError } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { LokiOptions } from '../loki/types';
import { transformTrace, transformTraceList } from './resultTransformer';
export type TempoQueryType = 'search' | 'traceId';
export type TempoQuery = {
query: string;
// Query to find list of traces, e.g., via Loki
linkedQuery?: DataQuery;
queryType: TempoQueryType;
} & DataQuery;
export class TempoDatasource extends DataSourceWithBackend<TempoQuery, TraceToLogsData> {
tracesToLogs?: TraceToLogsOptions;
constructor(instanceSettings: DataSourceInstanceSettings<TraceToLogsData>) {
super(instanceSettings);
this.tracesToLogs = instanceSettings.jsonData.tracesToLogs;
}
query(options: DataQueryRequest<TempoQuery>): Observable<DataQueryResponse> {
const subQueries: Array<Observable<DataQueryResponse>> = [];
const filteredTargets = options.targets.filter((target) => !target.hide);
const searchTargets = filteredTargets.filter((target) => target.queryType === 'search');
const traceTargets = filteredTargets.filter(
(target) => target.queryType === 'traceId' || target.queryType === undefined
);
// Run search queries on linked datasource
if (this.tracesToLogs?.datasourceUid && searchTargets.length > 0) {
const dsSrv = getDatasourceSrv();
subQueries.push(
from(dsSrv.get(this.tracesToLogs.datasourceUid)).pipe(
mergeMap((linkedDatasource: DataSourceApi) => {
// Wrap linked query into a data request based on original request
const linkedRequest: DataQueryRequest = { ...options, targets: searchTargets.map((t) => t.linkedQuery!) };
// Find trace matchers in derived fields of the linked datasource that's identical to this datasource
const settings: DataSourceInstanceSettings<LokiOptions> = (linkedDatasource as any).instanceSettings;
const traceLinkMatcher: string[] =
settings.jsonData.derivedFields
?.filter((field) => field.datasourceUid === this.uid && field.matcherRegex)
.map((field) => field.matcherRegex) || [];
if (!traceLinkMatcher || traceLinkMatcher.length === 0) {
return throwError(
'No Loki datasource configured for search. Set up Derived Fields for traces in a Loki datasource settings and link it to this Tempo datasource.'
);
} else {
return (linkedDatasource.query(linkedRequest) as Observable<DataQueryResponse>).pipe(
map((response) =>
response.error ? response : transformTraceList(response, this.uid, this.name, traceLinkMatcher)
)
);
}
})
)
);
}
if (traceTargets.length > 0) {
const traceRequest: DataQueryRequest<TempoQuery> = { ...options, targets: traceTargets };
subQueries.push(
super.query(traceRequest).pipe(
map((response) => {
if (response.error) {
return response;
}
return transformTrace(response);
})
)
);
}
return merge(...subQueries);
}
async testDatasource(): Promise<any> {
// to test Tempo we send a dummy traceID and verify Tempo answers with 'trace not found'
const response = await super.query({ targets: [{ query: '0' }] } as any).toPromise();
const errorMessage = response.error?.message;
if (
errorMessage &&
errorMessage.startsWith('failed to get trace') &&
errorMessage.endsWith('trace not found in Tempo')
) {
return { status: 'success', message: 'Data source is working' };
}
return { status: 'error', message: 'Data source is not working' + (errorMessage ? `: ${errorMessage}` : '') };
}
getQueryDisplayText(query: TempoQuery) {
return query.query;
}
}
| public/app/plugins/datasource/tempo/datasource.ts | 0 | https://github.com/grafana/grafana/commit/abe35c8c01ecd69c4fb18eaa43b2cb9e98bb03c2 | [
0.00017567069153301418,
0.000171763458638452,
0.00016683450667187572,
0.00017154209490399808,
0.0000025482033834123285
] |
{
"id": 0,
"code_window": [
"if (SUPER_NAME !== null) {\n",
" SUPER_NAME.apply(this, arguments);\n",
"}"
],
"labels": [
"replace",
"replace",
"keep"
],
"after_edit": [
"if (Object.getPrototypeOf(CLASS_NAME) !== null) {\n",
" Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);\n"
],
"file_path": "lib/6to5/transformation/templates/class-super-constructor-call.js",
"type": "replace",
"edit_start_line_idx": 0
} | "use strict";
var _inherits = function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) child.__proto__ = parent;
};
var BaseController = (function () {
var _Chaplin$Controller = Chaplin.Controller;
var BaseController = function BaseController() {
if (_Chaplin$Controller !== null) {
_Chaplin$Controller.apply(this, arguments);
}
};
_inherits(BaseController, _Chaplin$Controller);
return BaseController;
})();
var BaseController2 = (function () {
var _Chaplin$Controller$Another = Chaplin.Controller.Another;
var BaseController2 = function BaseController2() {
if (_Chaplin$Controller$Another !== null) {
_Chaplin$Controller$Another.apply(this, arguments);
}
};
_inherits(BaseController2, _Chaplin$Controller$Another);
return BaseController2;
})();
| test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0004449788830243051,
0.00024329726875294,
0.00016685899754520506,
0.00016851516556926072,
0.00010800226300489157
] |
{
"id": 0,
"code_window": [
"if (SUPER_NAME !== null) {\n",
" SUPER_NAME.apply(this, arguments);\n",
"}"
],
"labels": [
"replace",
"replace",
"keep"
],
"after_edit": [
"if (Object.getPrototypeOf(CLASS_NAME) !== null) {\n",
" Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);\n"
],
"file_path": "lib/6to5/transformation/templates/class-super-constructor-call.js",
"type": "replace",
"edit_start_line_idx": 0
} | define(["exports", "./evens"], function (exports, _evens) {
"use strict";
exports.nextOdd = nextOdd;
var isEven = _evens.isEven;
function nextOdd(n) {
return isEven(n) ? n + 1 : n + 2;
}
var isOdd = exports.isOdd = (function (isEven) {
return function (n) {
return !isEven(n);
};
})(isEven);
}); | test/fixtures/transformation/es6-modules-amd/hoist-function-exports/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017156351532321423,
0.00017148764163721353,
0.00017141176795121282,
0.00017148764163721353,
7.587368600070477e-8
] |
{
"id": 0,
"code_window": [
"if (SUPER_NAME !== null) {\n",
" SUPER_NAME.apply(this, arguments);\n",
"}"
],
"labels": [
"replace",
"replace",
"keep"
],
"after_edit": [
"if (Object.getPrototypeOf(CLASS_NAME) !== null) {\n",
" Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);\n"
],
"file_path": "lib/6to5/transformation/templates/class-super-constructor-call.js",
"type": "replace",
"edit_start_line_idx": 0
} | <p align="center">
<img alt="6to5" src="https://raw.githubusercontent.com/6to5/logo/master/logo.png" width="546">
</p>
<p align="center">
<a href="https://gratipay.com/sebmck">
<img alt="Gratipay" src="https://img.shields.io/gratipay/sebmck.svg?style=flat">
</a>
<a href="https://travis-ci.org/6to5/6to5">
<img alt="Travis Status" src="http://img.shields.io/travis/6to5/6to5/master.svg?style=flat&label=travis">
</a>
<a href="https://codeclimate.com/github/6to5/6to5">
<img alt="Code Climate Score" src="http://img.shields.io/codeclimate/github/6to5/6to5.svg?style=flat">
</a>
<a href="https://codeclimate.com/github/6to5/6to5">
<img alt="Coverage" src="http://img.shields.io/codeclimate/coverage/github/6to5/6to5.svg?style=flat">
</a>
<a href="https://david-dm.org/6to5/6to5">
<img alt="Dependency Status" src="http://img.shields.io/david/6to5/6to5.svg?style=flat">
</a>
</p>
<p align="center">
<strong>6to5</strong> turns ES6+ code into vanilla ES5, so you can use next generation features <strong>today.</strong>
</p>
<p align="center">
For more information view the <a href="https://6to5.github.io">documentation</a>. For
support visit the <a href="https://gitter.im/6to5/6to5">gitter room</a>.
</p>
| README.md | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00016989103460218757,
0.00016808207146823406,
0.00016587103891652077,
0.00016828312072902918,
0.0000014580859897250775
] |
{
"id": 0,
"code_window": [
"if (SUPER_NAME !== null) {\n",
" SUPER_NAME.apply(this, arguments);\n",
"}"
],
"labels": [
"replace",
"replace",
"keep"
],
"after_edit": [
"if (Object.getPrototypeOf(CLASS_NAME) !== null) {\n",
" Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);\n"
],
"file_path": "lib/6to5/transformation/templates/class-super-constructor-call.js",
"type": "replace",
"edit_start_line_idx": 0
} | foobar();
| test/fixtures/transformation/es6-modules-umd/module-name/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017594560631550848,
0.00017594560631550848,
0.00017594560631550848,
0.00017594560631550848,
0
] |
{
"id": 1,
"code_window": [
"\n",
" if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {\n",
" constructor.body.body.push(util.template(\"class-super-constructor-call\", {\n",
" SUPER_NAME: superName\n",
" }, true));\n",
" }\n",
"\n",
" var instanceProps;\n",
" var staticProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" CLASS_NAME: className\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-classes.js",
"type": "replace",
"edit_start_line_idx": 151
} | "use strict";
var _inherits = function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) child.__proto__ = parent;
};
var BaseController = (function () {
var _Chaplin$Controller = Chaplin.Controller;
var BaseController = function BaseController() {
if (_Chaplin$Controller !== null) {
_Chaplin$Controller.apply(this, arguments);
}
};
_inherits(BaseController, _Chaplin$Controller);
return BaseController;
})();
var BaseController2 = (function () {
var _Chaplin$Controller$Another = Chaplin.Controller.Another;
var BaseController2 = function BaseController2() {
if (_Chaplin$Controller$Another !== null) {
_Chaplin$Controller$Another.apply(this, arguments);
}
};
_inherits(BaseController2, _Chaplin$Controller$Another);
return BaseController2;
})();
| test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0009439132991246879,
0.0003262484970036894,
0.00016975095786619931,
0.00017378144548274577,
0.00030883762519806623
] |
{
"id": 1,
"code_window": [
"\n",
" if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {\n",
" constructor.body.body.push(util.template(\"class-super-constructor-call\", {\n",
" SUPER_NAME: superName\n",
" }, true));\n",
" }\n",
"\n",
" var instanceProps;\n",
" var staticProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" CLASS_NAME: className\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-classes.js",
"type": "replace",
"edit_start_line_idx": 151
} | "use strict";
var _obj2, _obj4, _x2, _obj$y2, _x4;
var _hasOwn = Object.prototype.hasOwnProperty;
var obj = {};
var _obj = obj;
if (!_hasOwn.call(_obj, "x")) _obj.x = 2;
console.log((_obj2 = obj, !_hasOwn.call(_obj2, "x") && (_obj2.x = 2), _obj2.x));
var _obj3 = obj;
var _x = x();
if (!_hasOwn.call(_obj3, _x)) _obj3[_x] = 2;
console.log((_obj4 = obj, _x2 = x(), !_hasOwn.call(_obj4, _x2) && (_obj4[_x2] = 2), _obj4[_x2]));
var _obj$y = obj[y()];
var _x3 = x();
if (!_hasOwn.call(_obj$y, _x3)) _obj$y[_x3] = 2;
console.log((_obj$y2 = obj[y()], _x4 = x(), !_hasOwn.call(_obj$y2, _x4) && (_obj$y2[_x4] = 2), _obj$y2[_x4]));
| test/fixtures/transformation/playground/memoization-assignment-operator/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0001766620553098619,
0.00017418306379113346,
0.0001720694126561284,
0.00017381772340741009,
0.0000018926518805528758
] |
{
"id": 1,
"code_window": [
"\n",
" if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {\n",
" constructor.body.body.push(util.template(\"class-super-constructor-call\", {\n",
" SUPER_NAME: superName\n",
" }, true));\n",
" }\n",
"\n",
" var instanceProps;\n",
" var staticProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" CLASS_NAME: className\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-classes.js",
"type": "replace",
"edit_start_line_idx": 151
} | environment:
matrix:
- nodejs_version: "0.10"
- nodejs_version: "0.11"
install:
- "npm install"
- "cinst make"
test_script:
- "node --version"
- "npm --version"
- "make test-spec"
build: "off"
version: "{build}"
| appveyor.yml | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017730028775986284,
0.00017645108164288104,
0.000175601860973984,
0.00017645108164288104,
8.492133929394186e-7
] |
{
"id": 1,
"code_window": [
"\n",
" if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {\n",
" constructor.body.body.push(util.template(\"class-super-constructor-call\", {\n",
" SUPER_NAME: superName\n",
" }, true));\n",
" }\n",
"\n",
" var instanceProps;\n",
" var staticProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" CLASS_NAME: className\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-classes.js",
"type": "replace",
"edit_start_line_idx": 151
} | import { isEven } from "./evens";
export function nextOdd(n) {
return isEven(n) ? n + 1 : n + 2;
}
export var isOdd = (function (isEven) {
return function (n) {
return !isEven(n);
};
})(isEven);
| test/fixtures/transformation/es6-modules-amd/hoist-function-exports/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017851401935331523,
0.00017828794079832733,
0.0001780618476914242,
0.00017828794079832733,
2.260858309455216e-7
] |
{
"id": 2,
"code_window": [
"\n",
"var BaseController = (function () {\n",
" var _Chaplin$Controller = Chaplin.Controller;\n",
" var BaseController = function BaseController() {\n",
" if (_Chaplin$Controller !== null) {\n",
" _Chaplin$Controller.apply(this, arguments);\n",
" }\n",
" };\n",
"\n",
" _inherits(BaseController, _Chaplin$Controller);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController) !== null) {\n",
" Object.getPrototypeOf(BaseController).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | "use strict";
var _defaults = function (obj, defaults) {
for (var key in defaults) {
if (obj[key] === undefined) {
obj[key] = defaults[key];
}
}
return obj;
};
var _inherits = function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) _defaults(child, parent);
};
var Foo = (function () {
var _Bar = Bar;
var Foo = function Foo() {
if (_Bar !== null) {
_Bar.apply(this, arguments);
}
};
_inherits(Foo, _Bar);
return Foo;
})();
| test/fixtures/transformation/optional-proto-to-assign/class/expected.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.001428436953574419,
0.00048331194557249546,
0.00016461136692669243,
0.00017009969451464713,
0.000545680639334023
] |
{
"id": 2,
"code_window": [
"\n",
"var BaseController = (function () {\n",
" var _Chaplin$Controller = Chaplin.Controller;\n",
" var BaseController = function BaseController() {\n",
" if (_Chaplin$Controller !== null) {\n",
" _Chaplin$Controller.apply(this, arguments);\n",
" }\n",
" };\n",
"\n",
" _inherits(BaseController, _Chaplin$Controller);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController) !== null) {\n",
" Object.getPrototypeOf(BaseController).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | function test() {
var
/*
* Leading to VariableDeclarator
* Leading to VariableDeclarator
*/
i = 20,
/*
* Leading to VariableDeclarator
* Leading to VariableDeclarator
*/
j = 20;
}
| test/fixtures/generation/comments/variable-declarator-multi-comment/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017767820099834353,
0.00017316482262685895,
0.0001686514588072896,
0.00017316482262685895,
0.0000045133710955269635
] |
{
"id": 2,
"code_window": [
"\n",
"var BaseController = (function () {\n",
" var _Chaplin$Controller = Chaplin.Controller;\n",
" var BaseController = function BaseController() {\n",
" if (_Chaplin$Controller !== null) {\n",
" _Chaplin$Controller.apply(this, arguments);\n",
" }\n",
" };\n",
"\n",
" _inherits(BaseController, _Chaplin$Controller);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController) !== null) {\n",
" Object.getPrototypeOf(BaseController).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | foob.add(...numbers);
foob.test.add(...numbers);
| test/fixtures/transformation/es6-spread/contexted-method-call-single-arg/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017771073908079416,
0.00017771073908079416,
0.00017771073908079416,
0.00017771073908079416,
0
] |
{
"id": 2,
"code_window": [
"\n",
"var BaseController = (function () {\n",
" var _Chaplin$Controller = Chaplin.Controller;\n",
" var BaseController = function BaseController() {\n",
" if (_Chaplin$Controller !== null) {\n",
" _Chaplin$Controller.apply(this, arguments);\n",
" }\n",
" };\n",
"\n",
" _inherits(BaseController, _Chaplin$Controller);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController) !== null) {\n",
" Object.getPrototypeOf(BaseController).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | environment:
matrix:
- nodejs_version: "0.10"
- nodejs_version: "0.11"
install:
- "npm install"
- "cinst make"
test_script:
- "node --version"
- "npm --version"
- "make test-spec"
build: "off"
version: "{build}"
| appveyor.yml | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0001770389499142766,
0.00017626775661483407,
0.00017549657786730677,
0.00017626775661483407,
7.711860234849155e-7
] |
{
"id": 3,
"code_window": [
"})();\n",
"\n",
"var BaseController2 = (function () {\n",
" var _Chaplin$Controller$Another = Chaplin.Controller.Another;\n",
" var BaseController2 = function BaseController2() {\n",
" if (_Chaplin$Controller$Another !== null) {\n",
" _Chaplin$Controller$Another.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController2) !== null) {\n",
" Object.getPrototypeOf(BaseController2).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 33
} | var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports.ClassDeclaration = function (node, parent, file, scope) {
var closure = true;
if (t.isProgram(parent) || t.isBlockStatement(parent)) {
closure = false;
}
var factory = new Class(node, file, scope, closure);
var newNode = factory.run();
if (factory.closure) {
if (closure) {
// declaration in an expression context...
// export default class Foo {}
scope.push({
kind: "var",
key: node.id.key,
id: node.id
});
return t.assignmentExpression("=", node.id, newNode);
} else {
// has a super class or PrivateDeclaration etc
return t.variableDeclaration("let", [
t.variableDeclarator(node.id, newNode)
]);
}
} else {
return newNode;
}
};
exports.ClassExpression = function (node, parent, file, scope) {
return new Class(node, file, scope, true).run();
};
/**
* Description
*
* @param {Node} node
* @param {File} file
* @param {Scope} scope
* @param {Boolean} closure
*/
function Class(node, file, scope, closure) {
this.closure = closure;
this.scope = scope;
this.node = node;
this.file = file;
this.hasInstanceMutators = false;
this.hasStaticMutators = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || file.generateUidIdentifier("class", scope);
this.superName = node.superClass;
}
/**
* Description
*
* @returns {Array}
*/
Class.prototype.run = function () {
var superName = this.superName;
var className = this.className;
var file = this.file;
//
var body = this.body = [];
var constructor = t.functionExpression(null, [], t.blockStatement([]));
if (this.node.id) constructor.id = className;
this.constructor = constructor;
body.push(t.variableDeclaration("let", [
t.variableDeclarator(className, constructor)
]));
//
if (superName) {
this.closure = true;
// so we're only evaluating it once
var superRef = this.scope.generateUidBasedOnNode(superName, this.file);
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(superRef, superName)
]));
superName = superRef;
this.superName = superName;
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName])));
}
this.buildBody();
t.inheritsComments(body[0], this.node);
if (this.closure) {
if (body.length === 1) {
// only a constructor so no need for a closure container
return constructor;
} else {
body.push(t.returnStatement(className));
return t.callExpression(
t.functionExpression(null, [], t.blockStatement(body)),
[]
);
}
} else {
return body;
}
};
/**
* Description
*/
Class.prototype.buildBody = function () {
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
var self = this;
for (var i in classBody) {
var node = classBody[i];
if (t.isMethodDefinition(node)) {
self.replaceInstanceSuperReferences(node);
if (node.key.name === "constructor") {
self.pushConstructor(node);
} else {
self.pushMethod(node);
}
} else if (t.isPrivateDeclaration(node)) {
self.closure = true;
body.unshift(node);
}
}
if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {
constructor.body.body.push(util.template("class-super-constructor-call", {
SUPER_NAME: superName
}, true));
}
var instanceProps;
var staticProps;
if (this.hasInstanceMutators) {
var protoId = util.template("prototype-identifier", {
CLASS_NAME: className
});
instanceProps = util.buildDefineProperties(this.instanceMutatorMap, protoId);
}
if (this.hasStaticMutators) {
staticProps = util.buildDefineProperties(this.staticMutatorMap, className);
}
if (instanceProps || staticProps) {
staticProps = staticProps || t.literal(null);
var args = [className, staticProps];
if (instanceProps) args.push(instanceProps);
body.push(t.expressionStatement(
t.callExpression(this.file.addHelper("prototype-properties"), args)
));
}
};
/**
* Push a method to it's respective mutatorMap.
*
* @param {Node} node MethodDefinition
*/
Class.prototype.pushMethod = function (node) {
var methodName = node.key;
var kind = node.kind;
if (kind === "") {
// method
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
} else {
// mutator
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
}
util.pushMutatorMap(mutatorMap, methodName, kind, node);
}
};
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {boolean} isStatic
* @param {boolean} isComputed
*
* @returns {Node}
*/
Class.prototype.superProperty = function (property, isStatic, isComputed) {
return t.callExpression(
this.file.addHelper("get"),
[
t.callExpression(
t.memberExpression(
t.identifier("Object"),
t.identifier("getPrototypeOf"),
false
),
[
isStatic ?
this.className :
t.memberExpression(
this.className,
t.identifier("prototype"),
false
)
]
),
isComputed ?
property :
t.literal(property.name),
t.thisExpression()
]
);
};
/**
* Replace all `super` references with a reference to our `superClass`.
*
* @param {Node} methodNode MethodDefinition
*/
Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
var method = methodNode.value;
var self = this;
traverse(method, {
enter: function (node, parent) {
var property;
var computed;
var args;
if (t.isIdentifier(node, { name: "super" })) {
if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
throw self.file.errorWithNode(node, "illegal use of bare super");
}
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (t.isIdentifier(callee) && callee.name === "super") {
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
property = methodNode.key;
computed = methodNode.computed;
args = node.arguments;
} else {
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node)) {
if (!t.isIdentifier(node.object, { name: "super" })) return;
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
}
if (property) {
var superProperty = self.superProperty(property, methodNode.static, computed);
if (args) {
return t.callExpression(
t.memberExpression(superProperty, t.identifier("call"), false),
[t.thisExpression()].concat(args)
);
} else {
return superProperty;
}
}
}
});
};
/**
* Replace the constructor body of our class.
*
* @param {Node} method MethodDefinition
*/
Class.prototype.pushConstructor = function (method) {
if (method.kind !== "") {
throw this.file.errorWithNode(method, "illegal kind for constructor method");
}
var construct = this.constructor;
var fn = method.value;
this.hasConstructor = true;
t.inherits(construct, fn);
t.inheritsComments(construct, method);
construct.defaults = fn.defaults;
construct.params = fn.params;
construct.body = fn.body;
construct.rest = fn.rest;
};
| lib/6to5/transformation/transformers/es6-classes.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017947766173165292,
0.00017283734632655978,
0.00016142877575475723,
0.000174851666088216,
0.000005183459052204853
] |
{
"id": 3,
"code_window": [
"})();\n",
"\n",
"var BaseController2 = (function () {\n",
" var _Chaplin$Controller$Another = Chaplin.Controller.Another;\n",
" var BaseController2 = function BaseController2() {\n",
" if (_Chaplin$Controller$Another !== null) {\n",
" _Chaplin$Controller$Another.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController2) !== null) {\n",
" Object.getPrototypeOf(BaseController2).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 33
} | delete delete i;
+ +i;
!!i;
+ ++i;
- --i;
| test/fixtures/generation/types/UnaryExpression/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017820655193645507,
0.00017820655193645507,
0.00017820655193645507,
0.00017820655193645507,
0
] |
{
"id": 3,
"code_window": [
"})();\n",
"\n",
"var BaseController2 = (function () {\n",
" var _Chaplin$Controller$Another = Chaplin.Controller.Another;\n",
" var BaseController2 = function BaseController2() {\n",
" if (_Chaplin$Controller$Another !== null) {\n",
" _Chaplin$Controller$Another.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController2) !== null) {\n",
" Object.getPrototypeOf(BaseController2).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 33
} | "use strict";
var test = exports.test = 2;
test = exports.test = 5;
test = exports.test += 1;
(function () {
var test = 2;
test = 3;
test++;
})();
| test/fixtures/transformation/es6-modules-common/remap/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017192625091411173,
0.00016704227891750634,
0.00016215832147281617,
0.00016704227891750634,
0.000004883964720647782
] |
{
"id": 3,
"code_window": [
"})();\n",
"\n",
"var BaseController2 = (function () {\n",
" var _Chaplin$Controller$Another = Chaplin.Controller.Another;\n",
" var BaseController2 = function BaseController2() {\n",
" if (_Chaplin$Controller$Another !== null) {\n",
" _Chaplin$Controller$Another.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(BaseController2) !== null) {\n",
" Object.getPrototypeOf(BaseController2).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js",
"type": "replace",
"edit_start_line_idx": 33
} | var square = x => x * x;
assert.equal(square(4), 16);
| test/fixtures/esnext/es6-arrow-functions/no-parens-for-low-precedence-expression-body.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017750936967786402,
0.00017750936967786402,
0.00017750936967786402,
0.00017750936967786402,
0
] |
{
"id": 4,
"code_window": [
"\n",
"var Test = (function () {\n",
" var _Foo = Foo;\n",
" var Test = function Test() {\n",
" if (_Foo !== null) {\n",
" _Foo.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Test) !== null) {\n",
" Object.getPrototypeOf(Test).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | "use strict";
var _inherits = function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) child.__proto__ = parent;
};
var Test = (function () {
var _Foo = Foo;
var Test = function Test() {
if (_Foo !== null) {
_Foo.apply(this, arguments);
}
};
_inherits(Test, _Foo);
return Test;
})();
| test/fixtures/transformation/es6-classes/super-class/expected.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.9988607168197632,
0.665597140789032,
0.0001665544550633058,
0.9977642297744751,
0.47053074836730957
] |
{
"id": 4,
"code_window": [
"\n",
"var Test = (function () {\n",
" var _Foo = Foo;\n",
" var Test = function Test() {\n",
" if (_Foo !== null) {\n",
" _Foo.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Test) !== null) {\n",
" Object.getPrototypeOf(Test).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | foo::bar;
foo::bar = baz;
delete foo::bar;
| test/fixtures/generation/types/VirualPropertyExpression/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00016388717631343752,
0.00016388717631343752,
0.00016388717631343752,
0.00016388717631343752,
0
] |
{
"id": 4,
"code_window": [
"\n",
"var Test = (function () {\n",
" var _Foo = Foo;\n",
" var Test = function Test() {\n",
" if (_Foo !== null) {\n",
" _Foo.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Test) !== null) {\n",
" Object.getPrototypeOf(Test).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | import * as foo from "foo";
foo = 1;
| test/fixtures/transformation/es6-modules-common/.disallow-import-remapping-4/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0016163053223863244,
0.0016163053223863244,
0.0016163053223863244,
0.0016163053223863244,
0
] |
{
"id": 4,
"code_window": [
"\n",
"var Test = (function () {\n",
" var _Foo = Foo;\n",
" var Test = function Test() {\n",
" if (_Foo !== null) {\n",
" _Foo.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Test) !== null) {\n",
" Object.getPrototypeOf(Test).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/es6-classes/super-class/expected.js",
"type": "replace",
"edit_start_line_idx": 20
} | "use strict";
bar[Symbol.referenceDelete](foo);
if ((bar[Symbol.referenceDelete](foo), true)) {}
| test/fixtures/transformation/es7-abstract-references/delete/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017687410581856966,
0.00017687410581856966,
0.00017687410581856966,
0.00017687410581856966,
0
] |
{
"id": 5,
"code_window": [
"};\n",
"\n",
"var Foo = (function () {\n",
" var _Bar = Bar;\n",
" var Foo = function Foo() {\n",
" if (_Bar !== null) {\n",
" _Bar.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Foo) !== null) {\n",
" Object.getPrototypeOf(Foo).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/optional-proto-to-assign/class/expected.js",
"type": "replace",
"edit_start_line_idx": 30
} | "use strict";
var _inherits = function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) child.__proto__ = parent;
};
var BaseController = (function () {
var _Chaplin$Controller = Chaplin.Controller;
var BaseController = function BaseController() {
if (_Chaplin$Controller !== null) {
_Chaplin$Controller.apply(this, arguments);
}
};
_inherits(BaseController, _Chaplin$Controller);
return BaseController;
})();
var BaseController2 = (function () {
var _Chaplin$Controller$Another = Chaplin.Controller.Another;
var BaseController2 = function BaseController2() {
if (_Chaplin$Controller$Another !== null) {
_Chaplin$Controller$Another.apply(this, arguments);
}
};
_inherits(BaseController2, _Chaplin$Controller$Another);
return BaseController2;
})();
| test/fixtures/transformation/es6-classes/super-class-id-member-expression/expected.js | 1 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017064694839064032,
0.0001686025643721223,
0.00016602168034296483,
0.0001695193350315094,
0.0000017392870859112008
] |
{
"id": 5,
"code_window": [
"};\n",
"\n",
"var Foo = (function () {\n",
" var _Bar = Bar;\n",
" var Foo = function Foo() {\n",
" if (_Bar !== null) {\n",
" _Bar.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Foo) !== null) {\n",
" Object.getPrototypeOf(Foo).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/optional-proto-to-assign/class/expected.js",
"type": "replace",
"edit_start_line_idx": 30
} | {
"args": ["foo", "--extensions", ".bar"],
"stdout": "[ 1, 4, 9 ]"
}
| test/fixtures/bin/6to5-node/--extensions/options.json | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00016923235671129078,
0.00016923235671129078,
0.00016923235671129078,
0.00016923235671129078,
0
] |
{
"id": 5,
"code_window": [
"};\n",
"\n",
"var Foo = (function () {\n",
" var _Bar = Bar;\n",
" var Foo = function Foo() {\n",
" if (_Bar !== null) {\n",
" _Bar.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Foo) !== null) {\n",
" Object.getPrototypeOf(Foo).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/optional-proto-to-assign/class/expected.js",
"type": "replace",
"edit_start_line_idx": 30
} | "use strict";
var obj = Object.defineProperties({}, {
foo: {
set: function (value) {
this._foo = value;
},
enumerable: true
}
});
| test/fixtures/transformation/es6-property-method-assignment/setter/expected.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.0001789941597962752,
0.00017787766410037875,
0.00017676115385256708,
0.00017787766410037875,
0.0000011165029718540609
] |
{
"id": 5,
"code_window": [
"};\n",
"\n",
"var Foo = (function () {\n",
" var _Bar = Bar;\n",
" var Foo = function Foo() {\n",
" if (_Bar !== null) {\n",
" _Bar.apply(this, arguments);\n",
" }\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (Object.getPrototypeOf(Foo) !== null) {\n",
" Object.getPrototypeOf(Foo).apply(this, arguments);\n"
],
"file_path": "test/fixtures/transformation/optional-proto-to-assign/class/expected.js",
"type": "replace",
"edit_start_line_idx": 30
} | do {
} // LINE
while (true);
| test/fixtures/generation/comments/do-while-line-comment/actual.js | 0 | https://github.com/babel/babel/commit/af1912ab7af99a4cfed061e49d7e1ad454410c7f | [
0.00017013320757541806,
0.00017013320757541806,
0.00017013320757541806,
0.00017013320757541806,
0
] |
{
"id": 0,
"code_window": [
"\tmax-width: var(--vscode-editor-dictation-widget-width);\n",
"}\n",
"\n",
".monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled {\n",
"\tdisplay: flex;\n",
"\talign-items: center;\n",
"\twidth: 16px;\n",
"\theight: 16px;\n",
"}\n",
"\n",
".monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled {\n",
"\tcolor: var(--vscode-activityBarBadge-background);\n",
"\tanimation: editor-dictation-animation 1s infinite;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css",
"type": "replace",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./editorDictation';
import { localize2 } from 'vs/nls';
import { IDimension, h, reset } from 'vs/base/browser/dom';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';
import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { Codicon } from 'vs/base/common/codicons';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { KeyCode } from 'vs/base/common/keyCodes';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Selection } from 'vs/editor/common/core/selection';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { registerAction2 } from 'vs/platform/actions/common/actions';
import { assertIsDefined } from 'vs/base/common/types';
const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false);
const VOICE_CATEGORY = localize2('voiceCategory', "Voice");
export class EditorDictationStartAction extends EditorAction2 {
constructor() {
super({
id: 'workbench.action.editorDictation.start',
title: localize2('startDictation', "Start Dictation in Editor"),
category: VOICE_CATEGORY,
precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()),
f1: true
});
}
override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void {
const keybindingService = accessor.get(IKeybindingService);
const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id);
if (holdMode) {
let shouldCallStop = false;
const handle = setTimeout(() => {
shouldCallStop = true;
}, 500);
holdMode.finally(() => {
clearTimeout(handle);
if (shouldCallStop) {
EditorDictation.get(editor)?.stop();
}
});
}
EditorDictation.get(editor)?.start();
}
}
export class EditorDictationStopAction extends EditorAction2 {
constructor() {
super({
id: 'workbench.action.editorDictation.stop',
title: localize2('stopDictation', "Stop Dictation in Editor"),
category: VOICE_CATEGORY,
precondition: EDITOR_DICTATION_IN_PROGRESS,
f1: true,
keybinding: {
primary: KeyCode.Escape,
weight: KeybindingWeight.WorkbenchContrib + 100
}
});
}
override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void {
EditorDictation.get(editor)?.stop();
}
}
export class DictationWidget extends Disposable implements IContentWidget {
readonly suppressMouseDown = true;
readonly allowEditorOverflow = true;
private readonly domNode = document.createElement('div');
private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]);
constructor(private readonly editor: ICodeEditor) {
super();
this.domNode.appendChild(this.elements.root);
this.domNode.style.zIndex = '1000';
reset(this.elements.mic, renderIcon(Codicon.micFilled));
}
getId(): string {
return 'editorDictation';
}
getDomNode(): HTMLElement {
return this.domNode;
}
getPosition(): IContentWidgetPosition | null {
if (!this.editor.hasModel()) {
return null;
}
const selection = this.editor.getSelection();
return {
position: selection.getPosition(),
preference: [
selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW,
ContentWidgetPositionPreference.EXACT
]
};
}
beforeRender(): IDimension | null {
const lineHeight = this.editor.getOption(EditorOption.lineHeight);
const width = this.editor.getLayoutInfo().contentWidth * 0.7;
this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);
this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);
return null;
}
show() {
this.editor.addContentWidget(this);
}
layout(): void {
this.editor.layoutContentWidget(this);
}
active(): void {
this.elements.main.classList.add('recording');
}
hide() {
this.elements.main.classList.remove('recording');
this.editor.removeContentWidget(this);
}
}
export class EditorDictation extends Disposable implements IEditorContribution {
static readonly ID = 'editorDictation';
static get(editor: ICodeEditor): EditorDictation | null {
return editor.getContribution<EditorDictation>(EditorDictation.ID);
}
private readonly widget = this._register(new DictationWidget(this.editor));
private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService);
private sessionDisposables = this._register(new MutableDisposable());
constructor(
private readonly editor: ICodeEditor,
@ISpeechService private readonly speechService: ISpeechService,
@IContextKeyService private readonly contextKeyService: IContextKeyService
) {
super();
}
start() {
const disposables = new DisposableStore();
this.sessionDisposables.value = disposables;
this.widget.show();
disposables.add(toDisposable(() => this.widget.hide()));
this.editorDictationInProgress.set(true);
disposables.add(toDisposable(() => this.editorDictationInProgress.reset()));
const collection = this.editor.createDecorationsCollection();
disposables.add(toDisposable(() => collection.clear()));
let previewStart: Position | undefined = undefined;
let lastReplaceTextLength = 0;
const replaceText = (text: string, isPreview: boolean) => {
if (!previewStart) {
previewStart = assertIsDefined(this.editor.getPosition());
}
const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length);
this.editor.executeEdits(EditorDictation.ID, [
EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text)
], [
Selection.fromPositions(endPosition)
]);
if (isPreview) {
collection.set([
{
range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)),
options: {
description: 'editor-dictation-preview',
inlineClassName: 'ghost-text-decoration-preview'
}
}
]);
} else {
collection.clear();
}
lastReplaceTextLength = text.length;
if (!isPreview) {
previewStart = undefined;
lastReplaceTextLength = 0;
}
this.editor.revealPositionInCenterIfOutsideViewport(endPosition);
this.widget.layout();
};
const cts = new CancellationTokenSource();
disposables.add(toDisposable(() => cts.dispose(true)));
const session = this.speechService.createSpeechToTextSession(cts.token);
disposables.add(session.onDidChange(e => {
if (cts.token.isCancellationRequested) {
return;
}
switch (e.status) {
case SpeechToTextStatus.Started:
this.widget.active();
break;
case SpeechToTextStatus.Stopped:
disposables.dispose();
break;
case SpeechToTextStatus.Recognizing: {
if (!e.text) {
return;
}
replaceText(e.text, true);
break;
}
case SpeechToTextStatus.Recognized: {
if (!e.text) {
return;
}
replaceText(`${e.text} `, false);
break;
}
}
}));
}
stop(): void {
this.sessionDisposables.clear();
}
}
registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy);
registerAction2(EditorDictationStartAction);
registerAction2(EditorDictationStopAction);
| src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts | 1 | https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7 | [
0.0019492462743073702,
0.0002652702678460628,
0.0001625879667699337,
0.0001676195824984461,
0.00035729576484300196
] |
{
"id": 0,
"code_window": [
"\tmax-width: var(--vscode-editor-dictation-widget-width);\n",
"}\n",
"\n",
".monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled {\n",
"\tdisplay: flex;\n",
"\talign-items: center;\n",
"\twidth: 16px;\n",
"\theight: 16px;\n",
"}\n",
"\n",
".monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled {\n",
"\tcolor: var(--vscode-activityBarBadge-background);\n",
"\tanimation: editor-dictation-animation 1s infinite;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css",
"type": "replace",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as words from '../utils/strings';
import * as fs from 'fs';
import * as path from 'path';
suite('HTML Language Configuration', () => {
const config = JSON.parse((fs.readFileSync(path.join(__dirname, '../../../../html/language-configuration.json')).toString()));
function createRegex(str: string | { pattern: string; flags: string }): RegExp {
if (typeof str === 'string') {
return new RegExp(str, 'g');
}
return new RegExp(str.pattern, str.flags);
}
const wordRegex = createRegex(config.wordPattern);
function assertWord(value: string, expected: string): void {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substring(offset + 1);
const actualRange = words.getWordAtText(value, offset, wordRegex);
assert(actualRange.start <= offset);
assert(actualRange.start + actualRange.length >= offset);
assert.strictEqual(value.substr(actualRange.start, actualRange.length), expected);
}
test('Words Basic', function (): any {
assertWord('|var x1 = new F<A>(a, b);', 'var');
assertWord('v|ar x1 = new F<A>(a, b);', 'var');
assertWord('var| x1 = new F<A>(a, b);', 'var');
assertWord('var |x1 = new F<A>(a, b);', 'x1');
assertWord('var x1| = new F<A>(a, b);', 'x1');
assertWord('var x1 = new |F<A>(a, b);', 'F');
assertWord('var x1 = new F<|A>(a, b);', 'A');
assertWord('var x1 = new F<A>(|a, b);', 'a');
assertWord('var x1 = new F<A>(a, b|);', 'b');
assertWord('var x1 = new F<A>(a, b)|;', '');
assertWord('var x1 = new F<A>(a, b)|;|', '');
assertWord('var x1 = | new F<A>(a, b)|;|', '');
});
test('Words Multiline', function (): any {
assertWord('console.log("hello");\n|var x1 = new F<A>(a, b);', 'var');
assertWord('console.log("hello");\n|\nvar x1 = new F<A>(a, b);', '');
assertWord('console.log("hello");\n\r |var x1 = new F<A>(a, b);', 'var');
});
const onEnterBeforeRules: RegExp[] = config.onEnterRules.map((r: any) => createRegex(r.beforeText));
function assertBeforeRule(text: string, expectedMatch: boolean): void {
for (const reg of onEnterBeforeRules) {
const start = new Date().getTime();
assert.strictEqual(reg.test(text), expectedMatch);
const totalTime = new Date().getTime() - start;
assert.ok(totalTime < 200, `Evaluation of ${reg.source} on ${text} took ${totalTime}ms]`);
}
}
test('OnEnter Before', function (): any {
assertBeforeRule('<button attr1=val1 attr2=val2', false);
assertBeforeRule('<button attr1=val1 attr2=val2>', true);
assertBeforeRule('<button attr1=\'val1\' attr2="val2">', true);
assertBeforeRule('<button attr1=val1 attr2=val2></button>', false);
});
});
| extensions/html-language-features/server/src/test/words.test.ts | 0 | https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7 | [
0.00017252829275093973,
0.0001696710824035108,
0.0001658488909015432,
0.0001693655940471217,
0.0000019666522348416038
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.