Compare commits

..
Author SHA1 Message Date
Christian Simon c36d03a1ba Implement exemplars 2026-01-13 20:12:03 +00:00
Christian Simon 7099cae39f WIP: Add heatmap to Pyroscope 2026-01-13 20:10:19 +00:00
107 changed files with 1919 additions and 8904 deletions
-1
View File
@@ -658,7 +658,6 @@ i18next.config.ts @grafana/grafana-frontend-platform
/packages/grafana-runtime/src/services/LocationService.tsx @grafana/grafana-search-navigate-organise
/packages/grafana-runtime/src/services/LocationSrv.ts @grafana/grafana-search-navigate-organise
/packages/grafana-runtime/src/services/live.ts @grafana/dashboards-squad
/packages/grafana-runtime/src/services/pluginMeta @grafana/plugins-platform-frontend
/packages/grafana-runtime/src/utils/chromeHeaderHeight.ts @grafana/grafana-search-navigate-organise
/packages/grafana-runtime/src/utils/DataSourceWithBackend* @grafana/grafana-datasources-core-services
/packages/grafana-runtime/src/utils/licensing.ts @grafana/grafana-operator-experience-squad
+3 -10
View File
@@ -1,16 +1,9 @@
include ../sdk.mk
.PHONY: internal-generate # Run Grafana App SDK code generation
internal-generate: install-app-sdk update-app-sdk
.PHONY: generate # Run Grafana App SDK code generation
generate: install-app-sdk update-app-sdk
@$(APP_SDK_BIN) generate \
--source=./kinds/ \
--gogenpath=./pkg/apis \
--grouping=group \
--defencoding=none
.PHONY: generate
generate: internal-generate # copy files to packages/grafana-runtime/src/services/pluginMeta/types
rm -f ./packages/grafana-runtime/src/services/pluginMeta/types/*.ts
cp plugin/src/generated/meta/v0alpha1/meta_object_gen.ts ../../packages/grafana-runtime/src/services/pluginMeta/types/meta_object_gen.ts
cp plugin/src/generated/meta/v0alpha1/types.spec.gen.ts ../../packages/grafana-runtime/src/services/pluginMeta/types/types.spec.gen.ts
cp plugin/src/generated/meta/v0alpha1/types.status.gen.ts ../../packages/grafana-runtime/src/services/pluginMeta/types/types.status.gen.ts
--defencoding=none
+2 -1
View File
@@ -4,7 +4,8 @@ API documentation is available at http://localhost:3000/swagger?api=plugins.graf
## Codegen
- Go and TypeScript: `make generate`
- Go: `make generate`
- Frontend: Follow instructions in this [README](../..//packages/grafana-api-clients/README.md)
## Plugin sync
+1 -1
View File
@@ -11,7 +11,7 @@ manifest: {
v0alpha1Version: {
served: true
codegen: {
ts: {enabled: true}
ts: {enabled: false}
go: {enabled: true}
}
kinds: [
@@ -1,49 +0,0 @@
/*
* This file was generated by grafana-app-sdk. DO NOT EDIT.
*/
import { Spec } from './types.spec.gen';
import { Status } from './types.status.gen';
export interface Metadata {
name: string;
namespace: string;
generateName?: string;
selfLink?: string;
uid?: string;
resourceVersion?: string;
generation?: number;
creationTimestamp?: string;
deletionTimestamp?: string;
deletionGracePeriodSeconds?: number;
labels?: Record<string, string>;
annotations?: Record<string, string>;
ownerReferences?: OwnerReference[];
finalizers?: string[];
managedFields?: ManagedFieldsEntry[];
}
export interface OwnerReference {
apiVersion: string;
kind: string;
name: string;
uid: string;
controller?: boolean;
blockOwnerDeletion?: boolean;
}
export interface ManagedFieldsEntry {
manager?: string;
operation?: string;
apiVersion?: string;
time?: string;
fieldsType?: string;
subresource?: string;
}
export interface Meta {
kind: string;
apiVersion: string;
metadata: Metadata;
spec: Spec;
status: Status;
}
@@ -1,30 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
// metadata contains embedded CommonMetadata and can be extended with custom string fields
// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here
// without external reference as using the CommonMetadata reference breaks thema codegen.
export interface Metadata {
updateTimestamp: string;
createdBy: string;
uid: string;
creationTimestamp: string;
deletionTimestamp?: string;
finalizers: string[];
resourceVersion: string;
generation: number;
updatedBy: string;
labels: Record<string, string>;
}
export const defaultMetadata = (): Metadata => ({
updateTimestamp: "",
createdBy: "",
uid: "",
creationTimestamp: "",
finalizers: [],
resourceVersion: "",
generation: 0,
updatedBy: "",
labels: {},
});
@@ -1,278 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
// JSON configuration schema for Grafana plugins
// Converted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json
export interface JSONData {
// Unique name of the plugin
id: string;
// Plugin type
type: "app" | "datasource" | "panel" | "renderer";
// Human-readable name of the plugin
name: string;
// Metadata for the plugin
info: Info;
// Dependency information
dependencies: Dependencies;
// Optional fields
alerting?: boolean;
annotations?: boolean;
autoEnabled?: boolean;
backend?: boolean;
buildMode?: string;
builtIn?: boolean;
category?: "tsdb" | "logging" | "cloud" | "tracing" | "profiling" | "sql" | "enterprise" | "iot" | "other";
enterpriseFeatures?: EnterpriseFeatures;
executable?: string;
hideFromList?: boolean;
// +listType=atomic
includes?: Include[];
logs?: boolean;
metrics?: boolean;
multiValueFilterOperators?: boolean;
pascalName?: string;
preload?: boolean;
queryOptions?: QueryOptions;
// +listType=atomic
routes?: Route[];
skipDataQuery?: boolean;
state?: "alpha" | "beta";
streaming?: boolean;
suggestions?: boolean;
tracing?: boolean;
iam?: IAM;
// +listType=atomic
roles?: Role[];
extensions?: Extensions;
}
export const defaultJSONData = (): JSONData => ({
id: "",
type: "app",
name: "",
info: defaultInfo(),
dependencies: defaultDependencies(),
});
export interface Info {
// Required fields
// +listType=set
keywords: string[];
logos: {
small: string;
large: string;
};
updated: string;
version: string;
// Optional fields
author?: {
name?: string;
email?: string;
url?: string;
};
description?: string;
// +listType=atomic
links?: {
name?: string;
url?: string;
}[];
// +listType=atomic
screenshots?: {
name?: string;
path?: string;
}[];
}
export const defaultInfo = (): Info => ({
keywords: [],
logos: {
small: "",
large: "",
},
updated: "",
version: "",
});
export interface Dependencies {
// Required field
grafanaDependency: string;
// Optional fields
grafanaVersion?: string;
// +listType=set
// +listMapKey=id
plugins?: {
id: string;
type: "app" | "datasource" | "panel";
name: string;
}[];
extensions?: {
// +listType=set
exposedComponents?: string[];
};
}
export const defaultDependencies = (): Dependencies => ({
grafanaDependency: "",
});
export interface EnterpriseFeatures {
// Allow additional properties
healthDiagnosticsErrors?: boolean;
}
export const defaultEnterpriseFeatures = (): EnterpriseFeatures => ({
healthDiagnosticsErrors: false,
});
export interface Include {
uid?: string;
type?: "dashboard" | "page" | "panel" | "datasource";
name?: string;
component?: string;
role?: "Admin" | "Editor" | "Viewer" | "None";
action?: string;
path?: string;
addToNav?: boolean;
defaultNav?: boolean;
icon?: string;
}
export const defaultInclude = (): Include => ({
});
export interface QueryOptions {
maxDataPoints?: boolean;
minInterval?: boolean;
cacheTimeout?: boolean;
}
export const defaultQueryOptions = (): QueryOptions => ({
});
export interface Route {
path?: string;
method?: string;
url?: string;
reqSignedIn?: boolean;
reqRole?: string;
reqAction?: string;
// +listType=atomic
headers?: string[];
body?: Record<string, any>;
tokenAuth?: {
url?: string;
// +listType=set
scopes?: string[];
params?: Record<string, any>;
};
jwtTokenAuth?: {
url?: string;
// +listType=set
scopes?: string[];
params?: Record<string, any>;
};
// +listType=atomic
urlParams?: {
name?: string;
content?: string;
}[];
}
export const defaultRoute = (): Route => ({
});
export interface IAM {
// +listType=atomic
permissions?: {
action?: string;
scope?: string;
}[];
}
export const defaultIAM = (): IAM => ({
});
export interface Role {
role?: {
name?: string;
description?: string;
// +listType=atomic
permissions?: {
action?: string;
scope?: string;
}[];
};
// +listType=set
grants?: string[];
}
export const defaultRole = (): Role => ({
});
export interface Extensions {
// +listType=atomic
addedComponents?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=atomic
addedLinks?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=atomic
addedFunctions?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=set
// +listMapKey=id
exposedComponents?: {
id: string;
title?: string;
description?: string;
}[];
// +listType=set
// +listMapKey=id
extensionPoints?: {
id: string;
title?: string;
description?: string;
}[];
}
export const defaultExtensions = (): Extensions => ({
});
export interface Spec {
pluginJson: JSONData;
class: "core" | "external";
module?: {
path: string;
hash?: string;
loadingStrategy?: "fetch" | "script";
};
baseURL?: string;
signature?: {
status: "internal" | "valid" | "invalid" | "modified" | "unsigned";
type?: "grafana" | "commercial" | "community" | "private" | "private-glob";
org?: string;
};
angular?: {
detected: boolean;
};
translations?: Record<string, string>;
// +listType=atomic
children?: string[];
}
export const defaultSpec = (): Spec => ({
pluginJson: defaultJSONData(),
class: "core",
});
@@ -1,30 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
export interface OperatorState {
// lastEvaluation is the ResourceVersion last evaluated
lastEvaluation: string;
// state describes the state of the lastEvaluation.
// It is limited to three possible states for machine evaluation.
state: "success" | "in_progress" | "failed";
// descriptiveState is an optional more descriptive state field which has no requirements on format
descriptiveState?: string;
// details contains any extra information that is operator-specific
details?: Record<string, any>;
}
export const defaultOperatorState = (): OperatorState => ({
lastEvaluation: "",
state: "success",
});
export interface Status {
// operatorStates is a map of operator ID to operator state evaluations.
// Any operator which consumes this kind SHOULD add its state evaluation information to this field.
operatorStates?: Record<string, OperatorState>;
// additionalFields is reserved for future use
additionalFields?: Record<string, any>;
}
export const defaultStatus = (): Status => ({
});
@@ -1,49 +0,0 @@
/*
* This file was generated by grafana-app-sdk. DO NOT EDIT.
*/
import { Spec } from './types.spec.gen';
import { Status } from './types.status.gen';
export interface Metadata {
name: string;
namespace: string;
generateName?: string;
selfLink?: string;
uid?: string;
resourceVersion?: string;
generation?: number;
creationTimestamp?: string;
deletionTimestamp?: string;
deletionGracePeriodSeconds?: number;
labels?: Record<string, string>;
annotations?: Record<string, string>;
ownerReferences?: OwnerReference[];
finalizers?: string[];
managedFields?: ManagedFieldsEntry[];
}
export interface OwnerReference {
apiVersion: string;
kind: string;
name: string;
uid: string;
controller?: boolean;
blockOwnerDeletion?: boolean;
}
export interface ManagedFieldsEntry {
manager?: string;
operation?: string;
apiVersion?: string;
time?: string;
fieldsType?: string;
subresource?: string;
}
export interface Plugin {
kind: string;
apiVersion: string;
metadata: Metadata;
spec: Spec;
status: Status;
}
@@ -1,30 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
// metadata contains embedded CommonMetadata and can be extended with custom string fields
// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here
// without external reference as using the CommonMetadata reference breaks thema codegen.
export interface Metadata {
updateTimestamp: string;
createdBy: string;
uid: string;
creationTimestamp: string;
deletionTimestamp?: string;
finalizers: string[];
resourceVersion: string;
generation: number;
updatedBy: string;
labels: Record<string, string>;
}
export const defaultMetadata = (): Metadata => ({
updateTimestamp: "",
createdBy: "",
uid: "",
creationTimestamp: "",
finalizers: [],
resourceVersion: "",
generation: 0,
updatedBy: "",
labels: {},
});
@@ -1,13 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
export interface Spec {
id: string;
version: string;
url?: string;
}
export const defaultSpec = (): Spec => ({
id: "",
version: "",
});
@@ -1,30 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
export interface OperatorState {
// lastEvaluation is the ResourceVersion last evaluated
lastEvaluation: string;
// state describes the state of the lastEvaluation.
// It is limited to three possible states for machine evaluation.
state: "success" | "in_progress" | "failed";
// descriptiveState is an optional more descriptive state field which has no requirements on format
descriptiveState?: string;
// details contains any extra information that is operator-specific
details?: Record<string, any>;
}
export const defaultOperatorState = (): OperatorState => ({
lastEvaluation: "",
state: "success",
});
export interface Status {
// operatorStates is a map of operator ID to operator state evaluations.
// Any operator which consumes this kind SHOULD add its state evaluation information to this field.
operatorStates?: Record<string, OperatorState>;
// additionalFields is reserved for future use
additionalFields?: Record<string, any>;
}
export const defaultStatus = (): Status => ({
});
@@ -2030,44 +2030,6 @@ For example: `disabled_labels=grafana_folder`
<hr>
### `[unified_alerting.state_history]`
This section configures where Grafana Alerting writes alert state history. Refer to [Configure alert state history](/docs/grafana/<GRAFANA_VERSION>/alerting/set-up/configure-alert-state-history/) for end-to-end setup and examples.
#### `enabled `
Enables recording alert state history. Default is `false`.
#### `backend `
Select the backend used to store alert state history. Supported values: `loki`, `prometheus`, `multiple`.
#### `loki_remote_url `
The URL of the Loki server used when `backend = loki` (or when `backend = multiple` and Loki is a primary/secondary).
#### `prometheus_target_datasource_uid `
Target Prometheus data source UID used for writing alert state changes when `backend = prometheus` (or when `backend = multiple` and Prometheus is a secondary).
#### `prometheus_metric_name `
Optional. Metric name for the alert state metric. Default is `GRAFANA_ALERTS`.
#### `prometheus_write_timeout `
Optional. Timeout for writing alert state data to the target data source. Default is `10s`.
#### `primary `
Used only when `backend = multiple`. Selects the primary backend (for example `loki`).
#### `secondaries `
Used only when `backend = multiple`. Comma-separated list of secondary backends (for example `prometheus`).
<hr>
### `[unified_alerting.state_history.annotations]`
This section controls retention of annotations automatically created while evaluating alert rules when alerting state history backend is configured to be annotations (see setting [unified_alerting.state_history].backend)
-128
View File
@@ -1337,11 +1337,6 @@
"count": 2
}
},
"public/app/features/alerting/unified/api/onCallApi.test.ts": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/alerting/unified/components/AnnotationDetailsField.tsx": {
"@typescript-eslint/consistent-type-assertions": {
"count": 1
@@ -1382,11 +1377,6 @@
"count": 1
}
},
"public/app/features/alerting/unified/components/import-to-gma/ConfirmConvertModal.test.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/import-to-gma/NamespaceAndGroupFilter.tsx": {
"no-restricted-syntax": {
"count": 2
@@ -1627,31 +1617,11 @@
"count": 1
}
},
"public/app/features/alerting/unified/mocks/server/configure.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/mocks/server/handlers/plugins.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/rule-editor/clone.utils.test.tsx": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/alerting/unified/rule-editor/formDefaults.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.test.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/types/alerting.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 5
@@ -1662,16 +1632,6 @@
"count": 1
}
},
"public/app/features/alerting/unified/utils/config.test.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/alerting/unified/utils/config.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/utils/datasource.ts": {
"no-restricted-syntax": {
"count": 2
@@ -1703,20 +1663,12 @@
"count": 1
}
},
"public/app/features/alerting/unified/utils/rules.test.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/utils/rules.ts": {
"@typescript-eslint/consistent-type-assertions": {
"count": 3
},
"@typescript-eslint/no-explicit-any": {
"count": 1
},
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/annotations/components/StandardAnnotationQueryEditor.tsx": {
@@ -1772,16 +1724,6 @@
"count": 1
}
},
"public/app/features/connections/components/AdvisorRedirectNotice/AdvisorRedirectNotice.test.tsx": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/connections/components/AdvisorRedirectNotice/AdvisorRedirectNotice.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/connections/tabs/ConnectData/ConnectData.tsx": {
"@typescript-eslint/consistent-type-assertions": {
"count": 1
@@ -2121,11 +2063,6 @@
"count": 1
}
},
"public/app/features/dashboard/components/GenAI/utils.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/dashboard/components/HelpWizard/HelpWizard.tsx": {
"no-restricted-syntax": {
"count": 3
@@ -2952,71 +2889,6 @@
"count": 1
}
},
"public/app/features/plugins/extensions/registry/AddedComponentsRegistry.test.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/plugins/extensions/registry/AddedFunctionsRegistry.test.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/plugins/extensions/registry/AddedLinksRegistry.test.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/plugins/extensions/registry/ExposedComponentsRegistry.test.ts": {
"no-restricted-syntax": {
"count": 6
}
},
"public/app/features/plugins/extensions/usePluginComponent.test.tsx": {
"no-restricted-syntax": {
"count": 3
}
},
"public/app/features/plugins/extensions/usePluginComponents.test.tsx": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/plugins/extensions/usePluginFunctions.test.tsx": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/plugins/extensions/usePluginLinks.test.tsx": {
"no-restricted-syntax": {
"count": 2
}
},
"public/app/features/plugins/extensions/utils.test.tsx": {
"no-restricted-syntax": {
"count": 27
}
},
"public/app/features/plugins/extensions/utils.tsx": {
"no-restricted-syntax": {
"count": 7
}
},
"public/app/features/plugins/extensions/validators.test.tsx": {
"no-restricted-syntax": {
"count": 30
}
},
"public/app/features/plugins/extensions/validators.ts": {
"no-restricted-syntax": {
"count": 4
}
},
"public/app/features/plugins/sandbox/codeLoader.ts": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/plugins/sandbox/distortions.ts": {
"@typescript-eslint/consistent-type-assertions": {
"count": 1
-38
View File
@@ -117,8 +117,6 @@ module.exports = [
'scripts/grafana-server/tmp',
'packages/grafana-ui/src/graveyard', // deprecated UI components slated for removal
'public/build-swagger', // swagger build output
'apps/plugins/plugin/src/generated/meta/v0alpha1',
'apps/plugins/plugin/src/generated/plugin/v0alpha1',
],
},
...grafanaConfig,
@@ -577,42 +575,6 @@ module.exports = [
"Property[key.name='a11y'][value.type='ObjectExpression'] Property[key.name='test'][value.value='off']",
message: 'Skipping a11y tests is not allowed. Please fix the component or story instead.',
},
{
selector: 'MemberExpression[object.name="config"][property.name="apps"]',
message:
'Usage of config.apps is not allowed. Use the function getAppPluginMetas or useAppPluginMetas from @grafana/runtime instead',
},
],
},
},
{
files: [...commonTestIgnores],
ignores: [
// FIXME: Remove once all enterprise issues are fixed -
// we don't have a suppressions file/approach for enterprise code yet
...enterpriseIgnores,
],
rules: {
'no-restricted-syntax': [
'error',
{
selector: 'MemberExpression[object.name="config"][property.name="apps"]',
message:
'Usage of config.apps is not allowed. Use the function getAppPluginMetas or useAppPluginMetas from @grafana/runtime instead',
},
],
},
},
{
files: [...enterpriseIgnores],
rules: {
'no-restricted-syntax': [
'error',
{
selector: 'MemberExpression[object.name="config"][property.name="apps"]',
message:
'Usage of config.apps is not allowed. Use the function getAppPluginMetas or useAppPluginMetas from @grafana/runtime instead',
},
],
},
},
+1 -1
View File
@@ -112,7 +112,7 @@ require (
github.com/grafana/nanogit v0.3.0 // indirect; @grafana/grafana-git-ui-sync-team
github.com/grafana/otel-profiling-go v0.5.1 // @grafana/grafana-backend-group
github.com/grafana/pyroscope-go/godeltaprof v0.1.9 // @grafana/observability-traces-and-profiling
github.com/grafana/pyroscope/api v1.2.1-0.20251118081820-ace37f973a0f // @grafana/observability-traces-and-profiling
github.com/grafana/pyroscope/api v1.2.1-0.20260109143659-5ff77ad3011a // @grafana/observability-traces-and-profiling
github.com/grafana/tempo v1.5.1-0.20250529124718-87c2dc380cec // @grafana/observability-traces-and-profiling
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // @grafana/grafana-search-and-storage
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // @grafana/plugins-platform-backend
+2 -2
View File
@@ -1685,8 +1685,8 @@ github.com/grafana/prometheus-alertmanager v0.25.1-0.20260112162805-d29cc9cf7f0f
github.com/grafana/prometheus-alertmanager v0.25.1-0.20260112162805-d29cc9cf7f0f/go.mod h1:AsVdCBeDFN9QbgpJg+8voDAcgsW0RmNvBd70ecMMdC0=
github.com/grafana/pyroscope-go/godeltaprof v0.1.9 h1:c1Us8i6eSmkW+Ez05d3co8kasnuOY813tbMN8i/a3Og=
github.com/grafana/pyroscope-go/godeltaprof v0.1.9/go.mod h1:2+l7K7twW49Ct4wFluZD3tZ6e0SjanjcUUBPVD/UuGU=
github.com/grafana/pyroscope/api v1.2.1-0.20251118081820-ace37f973a0f h1:fTlIj5n4x5dU63XHItug7GLjtnaeJdPqBlqg4zlABq0=
github.com/grafana/pyroscope/api v1.2.1-0.20251118081820-ace37f973a0f/go.mod h1:VBNcIhunCZsJ3/mcYx+j7uFf0P/108eiWa+8+Z9ll3o=
github.com/grafana/pyroscope/api v1.2.1-0.20260109143659-5ff77ad3011a h1:8ol+RVtrjm6rFu275xR7ChDzm4nYFNj9gWRO19p9sQI=
github.com/grafana/pyroscope/api v1.2.1-0.20260109143659-5ff77ad3011a/go.mod h1:ga4rxVfVsvUKEbmwx4/dryIRwHBYpuwP0mDB81aMR2Y=
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc h1:GN2Lv3MGO7AS6PrRoT6yV5+wkrOpcszoIsO4+4ds248=
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=
github.com/grafana/saml v0.4.15-0.20240917091248-ae3bbdad8a56 h1:SDGrP81Vcd102L3UJEryRd1eestRw73wt+b8vnVEFe0=
+1
View File
@@ -1488,6 +1488,7 @@ github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFR
github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636 h1:aSISeOcal5irEhJd1M+IrApc0PdcN7e7Aj4yuEnOrfQ=
github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/simonswine/pyroscope/api v0.0.0-20260105145211-3182b395db2f/go.mod h1:ga4rxVfVsvUKEbmwx4/dryIRwHBYpuwP0mDB81aMR2Y=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
@@ -32,7 +32,6 @@ export type AppPluginConfig = {
path: string;
version: string;
preload: boolean;
/** @deprecated it will be removed in a future release */
angular: AngularMeta;
loadingStrategy: PluginLoadingStrategy;
dependencies: PluginDependencies;
@@ -220,7 +219,6 @@ export interface GrafanaConfig {
snapshotEnabled: boolean;
datasources: { [str: string]: DataSourceInstanceSettings };
panels: { [key: string]: PanelPluginMeta };
/** @deprecated it will be removed in a future release */
apps: Record<string, AppPluginConfig>;
auth: AuthSettings;
minRefreshInterval: string;
+4
View File
@@ -1251,4 +1251,8 @@ export interface FeatureToggles {
* Enables profiles exemplars support in profiles drilldown
*/
profilesExemplars?: boolean;
/**
* Enables heatmap visualization support for Pyroscope profiles
*/
profilesHeatmap?: boolean;
}
@@ -53,7 +53,6 @@ export interface PluginError {
pluginType?: PluginType;
}
/** @deprecated it will be removed in a future release */
export interface AngularMeta {
detected: boolean;
hideDeprecation: boolean;
-1
View File
@@ -86,7 +86,6 @@ export class GrafanaBootConfig {
snapshotEnabled = true;
datasources: { [str: string]: DataSourceInstanceSettings } = {};
panels: { [key: string]: PanelPluginMeta } = {};
/** @deprecated it will be removed in a future release, use isAppPluginInstalled or getAppPluginVersion instead */
apps: Record<string, AppPluginConfigGrafanaData> = {};
auth: AuthSettings = {};
minRefreshInterval = '';
-2
View File
@@ -77,5 +77,3 @@ export {
getCorrelationsService,
setCorrelationsService,
} from './services/CorrelationsService';
export { getAppPluginVersion, isAppPluginInstalled } from './services/pluginMeta/apps';
export { useAppPluginInstalled, useAppPluginVersion } from './services/pluginMeta/hooks';
@@ -29,5 +29,3 @@ export {
export { UserStorage } from '../utils/userStorage';
export { initOpenFeature, evaluateBooleanFlag } from './openFeature';
export { getAppPluginMeta, getAppPluginMetas, setAppPluginMetas } from '../services/pluginMeta/apps';
export { useAppPluginMeta, useAppPluginMetas } from '../services/pluginMeta/hooks';
@@ -1,258 +0,0 @@
import { evaluateBooleanFlag } from '../../internal/openFeature';
import {
getAppPluginMeta,
getAppPluginMetas,
getAppPluginVersion,
isAppPluginInstalled,
setAppPluginMetas,
} from './apps';
import { initPluginMetas } from './plugins';
import { app } from './test-fixtures/config.apps';
jest.mock('./plugins', () => ({ ...jest.requireActual('./plugins'), initPluginMetas: jest.fn() }));
jest.mock('../../internal/openFeature', () => ({
...jest.requireActual('../../internal/openFeature'),
evaluateBooleanFlag: jest.fn(),
}));
const initPluginMetasMock = jest.mocked(initPluginMetas);
const evaluateBooleanFlagMock = jest.mocked(evaluateBooleanFlag);
describe('when useMTPlugins flag is enabled and apps is not initialized', () => {
beforeEach(() => {
setAppPluginMetas({});
jest.resetAllMocks();
initPluginMetasMock.mockResolvedValue({ items: [] });
evaluateBooleanFlagMock.mockReturnValue(true);
});
it('getAppPluginMetas should call initPluginMetas and return correct result', async () => {
const apps = await getAppPluginMetas();
expect(apps).toEqual([]);
expect(initPluginMetasMock).toHaveBeenCalledTimes(1);
});
it('getAppPluginMeta should call initPluginMetas and return correct result', async () => {
const result = await getAppPluginMeta('myorg-someplugin-app');
expect(result).toEqual(null);
expect(initPluginMetasMock).toHaveBeenCalledTimes(1);
});
it('isAppPluginInstalled should call initPluginMetas and return false', async () => {
const installed = await isAppPluginInstalled('myorg-someplugin-app');
expect(installed).toEqual(false);
expect(initPluginMetasMock).toHaveBeenCalledTimes(1);
});
it('getAppPluginVersion should call initPluginMetas and return null', async () => {
const result = await getAppPluginVersion('myorg-someplugin-app');
expect(result).toEqual(null);
expect(initPluginMetasMock).toHaveBeenCalledTimes(1);
});
});
describe('when useMTPlugins flag is enabled and apps is initialized', () => {
beforeEach(() => {
setAppPluginMetas({ 'myorg-someplugin-app': app });
jest.resetAllMocks();
evaluateBooleanFlagMock.mockReturnValue(true);
});
it('getAppPluginMetas should not call initPluginMetas and return correct result', async () => {
const apps = await getAppPluginMetas();
expect(apps).toEqual([app]);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginMeta should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginMeta('myorg-someplugin-app');
expect(result).toEqual(app);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginMeta should return null if the pluginId is not found', async () => {
const result = await getAppPluginMeta('otherorg-otherplugin-app');
expect(result).toEqual(null);
});
it('isAppPluginInstalled should not call initPluginMetas and return true', async () => {
const installed = await isAppPluginInstalled('myorg-someplugin-app');
expect(installed).toEqual(true);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('isAppPluginInstalled should return false if the pluginId is not found', async () => {
const result = await isAppPluginInstalled('otherorg-otherplugin-app');
expect(result).toEqual(false);
});
it('getAppPluginVersion should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginVersion('myorg-someplugin-app');
expect(result).toEqual('1.0.0');
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginVersion should return null if the pluginId is not found', async () => {
const result = await getAppPluginVersion('otherorg-otherplugin-app');
expect(result).toEqual(null);
});
});
describe('when useMTPlugins flag is disabled and apps is not initialized', () => {
beforeEach(() => {
setAppPluginMetas({});
jest.resetAllMocks();
evaluateBooleanFlagMock.mockReturnValue(false);
});
it('getAppPluginMetas should not call initPluginMetas and return correct result', async () => {
const apps = await getAppPluginMetas();
expect(apps).toEqual([]);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginMeta should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginMeta('myorg-someplugin-app');
expect(result).toEqual(null);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('isAppPluginInstalled should not call initPluginMetas and return false', async () => {
const result = await isAppPluginInstalled('myorg-someplugin-app');
expect(result).toEqual(false);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginVersion should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginVersion('myorg-someplugin-app');
expect(result).toEqual(null);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
});
describe('when useMTPlugins flag is disabled and apps is initialized', () => {
beforeEach(() => {
setAppPluginMetas({ 'myorg-someplugin-app': app });
jest.resetAllMocks();
evaluateBooleanFlagMock.mockReturnValue(false);
});
it('getAppPluginMetas should not call initPluginMetas and return correct result', async () => {
const apps = await getAppPluginMetas();
expect(apps).toEqual([app]);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginMeta should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginMeta('myorg-someplugin-app');
expect(result).toEqual(app);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginMeta should return null if the pluginId is not found', async () => {
const result = await getAppPluginMeta('otherorg-otherplugin-app');
expect(result).toEqual(null);
});
it('isAppPluginInstalled should not call initPluginMetas and return true', async () => {
const result = await isAppPluginInstalled('myorg-someplugin-app');
expect(result).toEqual(true);
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('isAppPluginInstalled should return false if the pluginId is not found', async () => {
const result = await isAppPluginInstalled('otherorg-otherplugin-app');
expect(result).toEqual(false);
});
it('getAppPluginVersion should not call initPluginMetas and return correct result', async () => {
const result = await getAppPluginVersion('myorg-someplugin-app');
expect(result).toEqual('1.0.0');
expect(initPluginMetasMock).not.toHaveBeenCalled();
});
it('getAppPluginVersion should return null if the pluginId is not found', async () => {
const result = await getAppPluginVersion('otherorg-otherplugin-app');
expect(result).toEqual(null);
});
});
describe('immutability', () => {
beforeEach(() => {
setAppPluginMetas({ 'myorg-someplugin-app': app });
jest.resetAllMocks();
evaluateBooleanFlagMock.mockReturnValue(false);
});
it('getAppPluginMetas should return a deep clone', async () => {
const mutatedApps = await getAppPluginMetas();
// assert we have correct props
expect(mutatedApps).toHaveLength(1);
expect(mutatedApps[0].dependencies.grafanaDependency).toEqual('>=10.4.0');
expect(mutatedApps[0].extensions.addedLinks).toHaveLength(0);
// mutate deep props
mutatedApps[0].dependencies.grafanaDependency = '';
mutatedApps[0].extensions.addedLinks.push({ targets: [], title: '', description: '' });
// assert we have mutated props
expect(mutatedApps[0].dependencies.grafanaDependency).toEqual('');
expect(mutatedApps[0].extensions.addedLinks).toHaveLength(1);
expect(mutatedApps[0].extensions.addedLinks[0]).toEqual({ targets: [], title: '', description: '' });
const apps = await getAppPluginMetas();
// assert that we have not mutated the source
expect(apps[0].dependencies.grafanaDependency).toEqual('>=10.4.0');
expect(apps[0].extensions.addedLinks).toHaveLength(0);
});
it('getAppPluginMeta should return a deep clone', async () => {
const mutatedApp = await getAppPluginMeta('myorg-someplugin-app');
// assert we have correct props
expect(mutatedApp).toBeDefined();
expect(mutatedApp!.dependencies.grafanaDependency).toEqual('>=10.4.0');
expect(mutatedApp!.extensions.addedLinks).toHaveLength(0);
// mutate deep props
mutatedApp!.dependencies.grafanaDependency = '';
mutatedApp!.extensions.addedLinks.push({ targets: [], title: '', description: '' });
// assert we have mutated props
expect(mutatedApp!.dependencies.grafanaDependency).toEqual('');
expect(mutatedApp!.extensions.addedLinks).toHaveLength(1);
expect(mutatedApp!.extensions.addedLinks[0]).toEqual({ targets: [], title: '', description: '' });
const result = await getAppPluginMeta('myorg-someplugin-app');
// assert that we have not mutated the source
expect(result).toBeDefined();
expect(result!.dependencies.grafanaDependency).toEqual('>=10.4.0');
expect(result!.extensions.addedLinks).toHaveLength(0);
});
});
@@ -1,71 +0,0 @@
import type { AppPluginConfig } from '@grafana/data';
import { config } from '../../config';
import { evaluateBooleanFlag } from '../../internal/openFeature';
import { getAppPluginMapper } from './mappers/mappers';
import { initPluginMetas } from './plugins';
import type { AppPluginMetas } from './types';
let apps: AppPluginMetas = {};
function initialized(): boolean {
return Boolean(Object.keys(apps).length);
}
async function initAppPluginMetas(): Promise<void> {
if (!evaluateBooleanFlag('useMTPlugins', false)) {
// eslint-disable-next-line no-restricted-syntax
apps = config.apps;
return;
}
const metas = await initPluginMetas();
const mapper = getAppPluginMapper();
apps = mapper(metas);
}
export async function getAppPluginMetas(): Promise<AppPluginConfig[]> {
if (!initialized()) {
await initAppPluginMetas();
}
return Object.values(structuredClone(apps));
}
export async function getAppPluginMeta(pluginId: string): Promise<AppPluginConfig | null> {
if (!initialized()) {
await initAppPluginMetas();
}
const app = apps[pluginId];
return app ? structuredClone(app) : null;
}
/**
* Check if an app plugin is installed. The function does not check if the app plugin is enabled.
* @param pluginId - The id of the app plugin.
* @returns True if the app plugin is installed, false otherwise.
*/
export async function isAppPluginInstalled(pluginId: string): Promise<boolean> {
const app = await getAppPluginMeta(pluginId);
return Boolean(app);
}
/**
* Get the version of an app plugin.
* @param pluginId - The id of the app plugin.
* @returns The version of the app plugin, or null if the plugin is not installed.
*/
export async function getAppPluginVersion(pluginId: string): Promise<string | null> {
const app = await getAppPluginMeta(pluginId);
return app?.version ?? null;
}
export function setAppPluginMetas(override: AppPluginMetas): void {
if (process.env.NODE_ENV !== 'test') {
throw new Error('setAppPluginMetas() function can only be called from tests.');
}
apps = structuredClone(override);
}
@@ -1,214 +0,0 @@
import { renderHook, waitFor } from '@testing-library/react';
import {
getAppPluginMeta,
getAppPluginMetas,
getAppPluginVersion,
isAppPluginInstalled,
setAppPluginMetas,
} from './apps';
import { useAppPluginMeta, useAppPluginMetas, useAppPluginInstalled, useAppPluginVersion } from './hooks';
import { apps } from './test-fixtures/config.apps';
const actualApps = jest.requireActual<typeof import('./apps')>('./apps');
jest.mock('./apps', () => ({
...jest.requireActual('./apps'),
getAppPluginMetas: jest.fn(),
getAppPluginMeta: jest.fn(),
isAppPluginInstalled: jest.fn(),
getAppPluginVersion: jest.fn(),
}));
const getAppPluginMetaMock = jest.mocked(getAppPluginMeta);
const getAppPluginMetasMock = jest.mocked(getAppPluginMetas);
const isAppPluginInstalledMock = jest.mocked(isAppPluginInstalled);
const getAppPluginVersionMock = jest.mocked(getAppPluginVersion);
describe('useAppPluginMeta', () => {
beforeEach(() => {
setAppPluginMetas(apps);
jest.resetAllMocks();
getAppPluginMetaMock.mockImplementation(actualApps.getAppPluginMeta);
});
it('should return correct default values', async () => {
const { result } = renderHook(() => useAppPluginMeta('grafana-exploretraces-app'));
expect(result.current.loading).toEqual(true);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toBeUndefined();
await waitFor(() => expect(result.current.loading).toEqual(true));
});
it('should return correct values after loading', async () => {
const { result } = renderHook(() => useAppPluginMeta('grafana-exploretraces-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(apps['grafana-exploretraces-app']);
});
it('should return correct values if the pluginId does not exist', async () => {
const { result } = renderHook(() => useAppPluginMeta('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(null);
});
it('should return correct values if useAppPluginMeta throws', async () => {
getAppPluginMetaMock.mockRejectedValue(new Error('Some error'));
const { result } = renderHook(() => useAppPluginMeta('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toEqual(new Error('Some error'));
expect(result.current.value).toBeUndefined();
});
});
describe('useAppPluginMetas', () => {
beforeEach(() => {
setAppPluginMetas(apps);
jest.resetAllMocks();
getAppPluginMetasMock.mockImplementation(actualApps.getAppPluginMetas);
});
it('should return correct default values', async () => {
const { result } = renderHook(() => useAppPluginMetas());
expect(result.current.loading).toEqual(true);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toBeUndefined();
await waitFor(() => expect(result.current.loading).toEqual(true));
});
it('should return correct values after loading', async () => {
const { result } = renderHook(() => useAppPluginMetas());
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(Object.values(apps));
});
it('should return correct values if useAppPluginMetas throws', async () => {
getAppPluginMetasMock.mockRejectedValue(new Error('Some error'));
const { result } = renderHook(() => useAppPluginMetas());
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toEqual(new Error('Some error'));
expect(result.current.value).toBeUndefined();
});
});
describe('useAppPluginInstalled', () => {
beforeEach(() => {
setAppPluginMetas(apps);
jest.resetAllMocks();
isAppPluginInstalledMock.mockImplementation(actualApps.isAppPluginInstalled);
});
it('should return correct default values', async () => {
const { result } = renderHook(() => useAppPluginInstalled('grafana-exploretraces-app'));
expect(result.current.loading).toEqual(true);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toBeUndefined();
await waitFor(() => expect(result.current.loading).toEqual(true));
});
it('should return correct values after loading', async () => {
const { result } = renderHook(() => useAppPluginInstalled('grafana-exploretraces-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(true);
});
it('should return correct values if the pluginId does not exist', async () => {
const { result } = renderHook(() => useAppPluginInstalled('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(false);
});
it('should return correct values if isAppPluginInstalled throws', async () => {
isAppPluginInstalledMock.mockRejectedValue(new Error('Some error'));
const { result } = renderHook(() => useAppPluginInstalled('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toEqual(new Error('Some error'));
expect(result.current.value).toBeUndefined();
});
});
describe('useAppPluginVersion', () => {
beforeEach(() => {
setAppPluginMetas(apps);
jest.resetAllMocks();
getAppPluginVersionMock.mockImplementation(actualApps.getAppPluginVersion);
});
it('should return correct default values', async () => {
const { result } = renderHook(() => useAppPluginVersion('grafana-exploretraces-app'));
expect(result.current.loading).toEqual(true);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toBeUndefined();
await waitFor(() => expect(result.current.loading).toEqual(true));
});
it('should return correct values after loading', async () => {
const { result } = renderHook(() => useAppPluginVersion('grafana-exploretraces-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual('1.2.2');
});
it('should return correct values if the pluginId does not exist', async () => {
const { result } = renderHook(() => useAppPluginVersion('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toBeUndefined();
expect(result.current.value).toEqual(null);
});
it('should return correct values if getAppPluginVersion throws', async () => {
getAppPluginVersionMock.mockRejectedValue(new Error('Some error'));
const { result } = renderHook(() => useAppPluginVersion('otherorg-otherplugin-app'));
await waitFor(() => expect(result.current.loading).toEqual(false));
expect(result.current.loading).toEqual(false);
expect(result.current.error).toEqual(new Error('Some error'));
expect(result.current.value).toBeUndefined();
});
});
@@ -1,35 +0,0 @@
import { useAsync } from 'react-use';
import { getAppPluginMeta, getAppPluginMetas, getAppPluginVersion, isAppPluginInstalled } from './apps';
export function useAppPluginMetas() {
const { loading, error, value } = useAsync(async () => getAppPluginMetas());
return { loading, error, value };
}
export function useAppPluginMeta(pluginId: string) {
const { loading, error, value } = useAsync(async () => getAppPluginMeta(pluginId));
return { loading, error, value };
}
/**
* Hook that checks if an app plugin is installed. The hook does not check if the app plugin is enabled.
* @param pluginId - The ID of the app plugin.
* @returns loading, error, value of the app plugin installed status.
* The value is true if the app plugin is installed, false otherwise.
*/
export function useAppPluginInstalled(pluginId: string) {
const { loading, error, value } = useAsync(async () => isAppPluginInstalled(pluginId));
return { loading, error, value };
}
/**
* Hook that gets the version of an app plugin.
* @param pluginId - The ID of the app plugin.
* @returns loading, error, value of the app plugin version.
* The value is the version of the app plugin, or null if the plugin is not installed.
*/
export function useAppPluginVersion(pluginId: string) {
const { loading, error, value } = useAsync(async () => getAppPluginVersion(pluginId));
return { loading, error, value };
}
@@ -1,7 +0,0 @@
import { AppPluginMetasMapper, PluginMetasResponse } from '../types';
import { v0alpha1AppMapper } from './v0alpha1AppMapper';
export function getAppPluginMapper(): AppPluginMetasMapper<PluginMetasResponse> {
return v0alpha1AppMapper;
}
@@ -1,84 +0,0 @@
import { apps } from '../test-fixtures/config.apps';
import { v0alpha1Response } from '../test-fixtures/v0alpha1Response';
import { v0alpha1AppMapper } from './v0alpha1AppMapper';
const PLUGIN_IDS = v0alpha1Response.items
.filter((i) => i.spec.pluginJson.type === 'app')
.map((i) => ({ pluginId: i.spec.pluginJson.id }));
describe('v0alpha1AppMapper', () => {
describe.each(PLUGIN_IDS)('when called for pluginId:$pluginId', ({ pluginId }) => {
it('should map id property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].id).toEqual(apps[pluginId].id);
});
it('should map path property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].path).toEqual(apps[pluginId].path);
});
it('should map version property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].version).toEqual(apps[pluginId].version);
});
it('should map preload property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].preload).toEqual(apps[pluginId].preload);
});
it('should map angular property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].angular).toEqual({});
});
it('should map loadingStrategy property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].loadingStrategy).toEqual(apps[pluginId].loadingStrategy);
});
it('should map dependencies property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].dependencies).toEqual(apps[pluginId].dependencies);
});
it('should map extensions property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].extensions.addedComponents).toEqual(apps[pluginId].extensions.addedComponents);
expect(result[pluginId].extensions.addedFunctions).toEqual(apps[pluginId].extensions.addedFunctions);
expect(result[pluginId].extensions.addedLinks).toEqual(apps[pluginId].extensions.addedLinks);
expect(result[pluginId].extensions.exposedComponents).toEqual(apps[pluginId].extensions.exposedComponents);
expect(result[pluginId].extensions.extensionPoints).toEqual(apps[pluginId].extensions.extensionPoints);
});
it('should map moduleHash property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].moduleHash).toEqual(apps[pluginId].moduleHash);
});
it('should map buildMode property correctly', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(result[pluginId].buildMode).toEqual(apps[pluginId].buildMode);
});
});
it('should only map specs with type app', () => {
const result = v0alpha1AppMapper(v0alpha1Response);
expect(v0alpha1Response.items).toHaveLength(58);
expect(Object.keys(result)).toHaveLength(5);
expect(Object.keys(result)).toEqual(Object.keys(apps));
});
});
@@ -1,111 +0,0 @@
import {
type AngularMeta,
type AppPluginConfig,
type PluginDependencies,
type PluginExtensions,
PluginLoadingStrategy,
type PluginType,
} from '@grafana/data';
import type { AppPluginMetas, AppPluginMetasMapper, PluginMetasResponse } from '../types';
import type { Spec as v0alpha1Spec } from '../types/types.spec.gen';
function angularyMapper(spec: v0alpha1Spec): AngularMeta {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {} as AngularMeta;
}
function dependenciesMapper(spec: v0alpha1Spec): PluginDependencies {
const plugins = (spec.pluginJson.dependencies?.plugins ?? []).map((v) => ({
...v,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
type: v.type as PluginType,
version: '',
}));
const dependencies: PluginDependencies = {
...spec.pluginJson.dependencies,
extensions: {
exposedComponents: spec.pluginJson.dependencies.extensions?.exposedComponents ?? [],
},
grafanaDependency: spec.pluginJson.dependencies.grafanaDependency,
grafanaVersion: spec.pluginJson.dependencies.grafanaVersion ?? '',
plugins,
};
return dependencies;
}
function extensionsMapper(spec: v0alpha1Spec): PluginExtensions {
const addedComponents = spec.pluginJson.extensions?.addedComponents ?? [];
const addedFunctions = spec.pluginJson.extensions?.addedFunctions ?? [];
const addedLinks = spec.pluginJson.extensions?.addedLinks ?? [];
const exposedComponents = (spec.pluginJson.extensions?.exposedComponents ?? []).map((v) => ({
...v,
description: v.description ?? '',
title: v.title ?? '',
}));
const extensionPoints = (spec.pluginJson.extensions?.extensionPoints ?? []).map((v) => ({
...v,
description: v.description ?? '',
title: v.title ?? '',
}));
const extensions: PluginExtensions = {
addedComponents,
addedFunctions,
addedLinks,
exposedComponents,
extensionPoints,
};
return extensions;
}
function loadingStrategyMapper(spec: v0alpha1Spec): PluginLoadingStrategy {
const loadingStrategy = spec.module?.loadingStrategy ?? PluginLoadingStrategy.fetch;
if (loadingStrategy === PluginLoadingStrategy.script) {
return PluginLoadingStrategy.script;
}
return PluginLoadingStrategy.fetch;
}
function specMapper(spec: v0alpha1Spec): AppPluginConfig {
const { id, info, preload = false } = spec.pluginJson;
const angular = angularyMapper(spec);
const dependencies = dependenciesMapper(spec);
const extensions = extensionsMapper(spec);
const loadingStrategy = loadingStrategyMapper(spec);
const path = spec.module?.path ?? '';
const version = info.version;
const buildMode = spec.pluginJson.buildMode ?? 'production';
const moduleHash = spec.module?.hash;
return {
id,
angular,
dependencies,
extensions,
loadingStrategy,
path,
preload,
version,
buildMode,
moduleHash,
};
}
export const v0alpha1AppMapper: AppPluginMetasMapper<PluginMetasResponse> = (response) => {
const result: AppPluginMetas = {};
return response.items.reduce((acc, curr) => {
if (curr.spec.pluginJson.type !== 'app') {
return acc;
}
const config = specMapper(curr.spec);
acc[config.id] = config;
return acc;
}, result);
};
@@ -1,153 +0,0 @@
import { evaluateBooleanFlag } from '../../internal/openFeature';
import { clearCache, initPluginMetas } from './plugins';
import { v0alpha1Meta } from './test-fixtures/v0alpha1Response';
jest.mock('../../internal/openFeature', () => ({
...jest.requireActual('../../internal/openFeature'),
evaluateBooleanFlag: jest.fn(),
}));
const evaluateBooleanFlagMock = jest.mocked(evaluateBooleanFlag);
describe('when useMTPlugins toggle is enabled and cache is not initialized', () => {
const originalFetch = global.fetch;
beforeEach(() => {
jest.resetAllMocks();
clearCache();
evaluateBooleanFlagMock.mockReturnValue(true);
});
afterEach(() => {
global.fetch = originalFetch;
});
it('initPluginMetas should call loadPluginMetas and return correct result if response is ok', async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ items: [v0alpha1Meta] }),
});
const response = await initPluginMetas();
expect(response.items).toHaveLength(1);
expect(response.items[0]).toEqual(v0alpha1Meta);
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith('/apis/plugins.grafana.app/v0alpha1/namespaces/default/metas');
});
it('initPluginMetas should call loadPluginMetas and return correct result if response is not ok', async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: false,
status: 404,
statusText: 'Not found',
});
await expect(initPluginMetas()).rejects.toThrow(new Error(`Failed to load plugin metas 404:Not found`));
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith('/apis/plugins.grafana.app/v0alpha1/namespaces/default/metas');
});
});
describe('when useMTPlugins toggle is enabled and cache is initialized', () => {
const originalFetch = global.fetch;
beforeEach(() => {
jest.resetAllMocks();
clearCache();
evaluateBooleanFlagMock.mockReturnValue(true);
});
afterEach(() => {
global.fetch = originalFetch;
});
it('initPluginMetas should return cache', async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ items: [v0alpha1Meta] }),
});
const original = await initPluginMetas();
const cached = await initPluginMetas();
expect(original).toEqual(cached);
expect(global.fetch).toHaveBeenCalledTimes(1);
});
it('initPluginMetas should return inflight promise', async () => {
jest.useFakeTimers();
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ items: [v0alpha1Meta] }),
});
const original = initPluginMetas();
const cached = initPluginMetas();
await jest.runAllTimersAsync();
expect(original).toEqual(cached);
expect(global.fetch).toHaveBeenCalledTimes(1);
});
});
describe('when useMTPlugins toggle is disabled and cache is not initialized', () => {
const originalFetch = global.fetch;
beforeEach(() => {
jest.resetAllMocks();
clearCache();
global.fetch = jest.fn();
evaluateBooleanFlagMock.mockReturnValue(false);
});
afterEach(() => {
global.fetch = originalFetch;
});
it('initPluginMetas should call loadPluginMetas and return correct result if response is ok', async () => {
const response = await initPluginMetas();
expect(response.items).toHaveLength(0);
expect(global.fetch).not.toHaveBeenCalled();
});
});
describe('when useMTPlugins toggle is disabled and cache is initialized', () => {
const originalFetch = global.fetch;
beforeEach(() => {
jest.resetAllMocks();
clearCache();
global.fetch = jest.fn();
evaluateBooleanFlagMock.mockReturnValue(false);
});
afterEach(() => {
global.fetch = originalFetch;
});
it('initPluginMetas should return cache', async () => {
const original = await initPluginMetas();
const cached = await initPluginMetas();
expect(original).toEqual(cached);
expect(global.fetch).not.toHaveBeenCalled();
});
it('initPluginMetas should return inflight promise', async () => {
jest.useFakeTimers();
const original = initPluginMetas();
const cached = initPluginMetas();
await jest.runAllTimersAsync();
expect(original).toEqual(cached);
expect(global.fetch).not.toHaveBeenCalled();
});
});
@@ -1,41 +0,0 @@
import { config } from '../../config';
import { evaluateBooleanFlag } from '../../internal/openFeature';
import type { PluginMetasResponse } from './types';
let initPromise: Promise<PluginMetasResponse> | null = null;
function getApiVersion(): string {
return 'v0alpha1';
}
async function loadPluginMetas(): Promise<PluginMetasResponse> {
if (!evaluateBooleanFlag('useMTPlugins', false)) {
const result = { items: [] };
return result;
}
const metas = await fetch(`/apis/plugins.grafana.app/${getApiVersion()}/namespaces/${config.namespace}/metas`);
if (!metas.ok) {
throw new Error(`Failed to load plugin metas ${metas.status}:${metas.statusText}`);
}
const result = await metas.json();
return result;
}
export function initPluginMetas(): Promise<PluginMetasResponse> {
if (!initPromise) {
initPromise = loadPluginMetas();
}
return initPromise;
}
export function clearCache() {
if (process.env.NODE_ENV !== 'test') {
throw new Error('clearCache() function can only be called from tests.');
}
initPromise = null;
}
@@ -1,303 +0,0 @@
import { cloneDeep } from 'lodash';
import { AngularMeta, AppPluginConfig, PluginLoadingStrategy } from '@grafana/data';
import { AppPluginMetas } from '../types';
export const app: AppPluginConfig = cloneDeep({
id: 'myorg-someplugin-app',
path: 'public/plugins/myorg-someplugin-app/module.js',
version: '1.0.0',
preload: false,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
angular: { detected: false } as AngularMeta,
loadingStrategy: PluginLoadingStrategy.script,
extensions: {
addedLinks: [],
addedComponents: [],
exposedComponents: [],
extensionPoints: [],
addedFunctions: [],
},
dependencies: {
grafanaDependency: '>=10.4.0',
grafanaVersion: '*',
plugins: [],
extensions: {
exposedComponents: [],
},
},
buildMode: 'production',
});
export const apps: AppPluginMetas = cloneDeep({
'grafana-exploretraces-app': {
id: 'grafana-exploretraces-app',
path: 'public/plugins/grafana-exploretraces-app/module.js',
version: '1.2.2',
preload: true,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
angular: { detected: false } as AngularMeta,
loadingStrategy: PluginLoadingStrategy.script,
extensions: {
addedLinks: [
{
targets: ['grafana/dashboard/panel/menu'],
title: 'Open in Traces Drilldown',
description: 'Open current query in the Traces Drilldown app',
},
{
targets: ['grafana/explore/toolbar/action'],
title: 'Open in Grafana Traces Drilldown',
description: 'Try our new queryless experience for traces',
},
],
addedComponents: [
{
targets: ['grafana-asserts-app/entity-assertions-widget/v1'],
title: 'Asserts widget',
description: 'A block with assertions for a given service',
},
{
targets: ['grafana-asserts-app/insights-timeline-widget/v1'],
title: 'Insights Timeline Widget',
description: 'Widget for displaying insights timeline in other apps',
},
],
exposedComponents: [
{
id: 'grafana-exploretraces-app/open-in-explore-traces-button/v1',
title: 'Open in Traces Drilldown button',
description: 'A button that opens a traces view in the Traces Drilldown app.',
},
{
id: 'grafana-exploretraces-app/embedded-trace-exploration/v1',
title: 'Embedded Trace Exploration',
description:
'A component that renders a trace exploration view that can be embedded in other parts of Grafana.',
},
],
extensionPoints: [
{
id: 'grafana-exploretraces-app/investigation/v1',
title: '',
description: '',
},
{
id: 'grafana-exploretraces-app/get-logs-drilldown-link/v1',
title: '',
description: '',
},
],
addedFunctions: [],
},
dependencies: {
grafanaDependency: '>=11.5.0',
grafanaVersion: '*',
plugins: [],
extensions: {
exposedComponents: [
'grafana-asserts-app/entity-assertions-widget/v1',
'grafana-asserts-app/insights-timeline-widget/v1',
],
},
},
buildMode: 'production',
},
'grafana-lokiexplore-app': {
id: 'grafana-lokiexplore-app',
path: 'public/plugins/grafana-lokiexplore-app/module.js',
version: '1.0.32',
preload: true,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
angular: { detected: false } as AngularMeta,
loadingStrategy: PluginLoadingStrategy.script,
extensions: {
addedLinks: [
{
targets: [
'grafana/dashboard/panel/menu',
'grafana/explore/toolbar/action',
'grafana-metricsdrilldown-app/open-in-logs-drilldown/v1',
'grafana-assistant-app/navigateToDrilldown/v1',
],
title: 'Open in Grafana Logs Drilldown',
description: 'Open current query in the Grafana Logs Drilldown view',
},
],
addedComponents: [
{
targets: ['grafana-asserts-app/insights-timeline-widget/v1'],
title: 'Insights Timeline Widget',
description: 'Widget for displaying insights timeline in other apps',
},
],
exposedComponents: [
{
id: 'grafana-lokiexplore-app/open-in-explore-logs-button/v1',
title: 'Open in Logs Drilldown button',
description: 'A button that opens a logs view in the Logs Drilldown app.',
},
{
id: 'grafana-lokiexplore-app/embedded-logs-exploration/v1',
title: 'Embedded Logs Exploration',
description:
'A component that renders a logs exploration view that can be embedded in other parts of Grafana.',
},
],
extensionPoints: [
{
id: 'grafana-lokiexplore-app/investigation/v1',
title: '',
description: '',
},
],
addedFunctions: [
{
targets: ['grafana-exploretraces-app/get-logs-drilldown-link/v1'],
title: 'Open Logs Drilldown',
description: 'Returns url to logs drilldown app',
},
],
},
dependencies: {
grafanaDependency: '>=11.6.0',
grafanaVersion: '*',
plugins: [],
extensions: {
exposedComponents: [
'grafana-adaptivelogs-app/temporary-exemptions/v1',
'grafana-lokiexplore-app/embedded-logs-exploration/v1',
'grafana-asserts-app/insights-timeline-widget/v1',
'grafana/add-to-dashboard-form/v1',
],
},
},
buildMode: 'production',
},
'grafana-metricsdrilldown-app': {
id: 'grafana-metricsdrilldown-app',
path: 'public/plugins/grafana-metricsdrilldown-app/module.js',
version: '1.0.26',
preload: true,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
angular: { detected: false } as AngularMeta,
loadingStrategy: PluginLoadingStrategy.script,
extensions: {
addedLinks: [
{
targets: [
'grafana/dashboard/panel/menu',
'grafana/explore/toolbar/action',
'grafana-assistant-app/navigateToDrilldown/v1',
'grafana/alerting/alertingrule/queryeditor',
],
title: 'Open in Grafana Metrics Drilldown',
description: 'Open current query in the Grafana Metrics Drilldown view',
},
{
targets: ['grafana-metricsdrilldown-app/grafana-assistant-app/navigateToDrilldown/v0-alpha'],
title: 'Navigate to metrics drilldown',
description: 'Build a url path to the metrics drilldown',
},
{
targets: ['grafana/datasources/config/actions', 'grafana/datasources/config/status'],
title: 'Open in Metrics Drilldown',
description: 'Browse metrics in Grafana Metrics Drilldown',
},
],
addedComponents: [],
exposedComponents: [
{
id: 'grafana-metricsdrilldown-app/label-breakdown-component/v1',
title: 'Label Breakdown',
description: 'A metrics label breakdown view from the Metrics Drilldown app.',
},
{
id: 'grafana-metricsdrilldown-app/knowledge-graph-insight-metrics/v1',
title: 'Knowledge Graph Source Metrics',
description: 'Explore the underlying metrics related to a Knowledge Graph insight',
},
],
extensionPoints: [
{
id: 'grafana-exploremetrics-app/investigation/v1',
title: '',
description: '',
},
{
id: 'grafana-metricsdrilldown-app/open-in-logs-drilldown/v1',
title: '',
description: '',
},
],
addedFunctions: [],
},
dependencies: {
grafanaDependency: '>=11.6.0',
grafanaVersion: '*',
plugins: [],
extensions: {
exposedComponents: ['grafana/add-to-dashboard-form/v1'],
},
},
buildMode: 'production',
},
'grafana-pyroscope-app': {
id: 'grafana-pyroscope-app',
path: 'public/plugins/grafana-pyroscope-app/module.js',
version: '1.14.2',
preload: true,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
angular: { detected: false } as AngularMeta,
loadingStrategy: PluginLoadingStrategy.script,
extensions: {
addedLinks: [
{
targets: [
'grafana/explore/toolbar/action',
'grafana/traceview/details',
'grafana-assistant-app/navigateToDrilldown/v1',
],
title: 'Open in Grafana Profiles Drilldown',
description: 'Try our new queryless experience for profiles',
},
],
addedComponents: [],
exposedComponents: [
{
id: 'grafana-pyroscope-app/embedded-profiles-exploration/v1',
title: 'Embedded Profiles Exploration',
description:
'A component that renders a profiles exploration view that can be embedded in other parts of Grafana.',
},
],
extensionPoints: [
{
id: 'grafana-pyroscope-app/investigation/v1',
title: '',
description: '',
},
{
id: 'grafana-pyroscope-app/settings/v1',
title: '',
description: '',
},
],
addedFunctions: [],
},
dependencies: {
grafanaDependency: '>=11.5.0',
grafanaVersion: '*',
plugins: [],
extensions: {
exposedComponents: [
'grafana-o11yinsights-app/insights-launcher/v1',
'grafana-adaptiveprofiles-app/resolution-boost/v1',
],
},
},
buildMode: 'production',
},
[app.id]: app,
});
@@ -1,10 +0,0 @@
import type { AppPluginConfig } from '@grafana/data';
import type { Meta } from './types/meta_object_gen';
export type AppPluginMetas = Record<string, AppPluginConfig>;
export type AppPluginMetasMapper<T> = (response: T) => AppPluginMetas;
export interface PluginMetasResponse {
items: Meta[];
}
@@ -1,49 +0,0 @@
/*
* This file was generated by grafana-app-sdk. DO NOT EDIT.
*/
import { Spec } from './types.spec.gen';
import { Status } from './types.status.gen';
export interface Metadata {
name: string;
namespace: string;
generateName?: string;
selfLink?: string;
uid?: string;
resourceVersion?: string;
generation?: number;
creationTimestamp?: string;
deletionTimestamp?: string;
deletionGracePeriodSeconds?: number;
labels?: Record<string, string>;
annotations?: Record<string, string>;
ownerReferences?: OwnerReference[];
finalizers?: string[];
managedFields?: ManagedFieldsEntry[];
}
export interface OwnerReference {
apiVersion: string;
kind: string;
name: string;
uid: string;
controller?: boolean;
blockOwnerDeletion?: boolean;
}
export interface ManagedFieldsEntry {
manager?: string;
operation?: string;
apiVersion?: string;
time?: string;
fieldsType?: string;
subresource?: string;
}
export interface Meta {
kind: string;
apiVersion: string;
metadata: Metadata;
spec: Spec;
status: Status;
}
@@ -1,278 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
// JSON configuration schema for Grafana plugins
// Converted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json
export interface JSONData {
// Unique name of the plugin
id: string;
// Plugin type
type: "app" | "datasource" | "panel" | "renderer";
// Human-readable name of the plugin
name: string;
// Metadata for the plugin
info: Info;
// Dependency information
dependencies: Dependencies;
// Optional fields
alerting?: boolean;
annotations?: boolean;
autoEnabled?: boolean;
backend?: boolean;
buildMode?: string;
builtIn?: boolean;
category?: "tsdb" | "logging" | "cloud" | "tracing" | "profiling" | "sql" | "enterprise" | "iot" | "other";
enterpriseFeatures?: EnterpriseFeatures;
executable?: string;
hideFromList?: boolean;
// +listType=atomic
includes?: Include[];
logs?: boolean;
metrics?: boolean;
multiValueFilterOperators?: boolean;
pascalName?: string;
preload?: boolean;
queryOptions?: QueryOptions;
// +listType=atomic
routes?: Route[];
skipDataQuery?: boolean;
state?: "alpha" | "beta";
streaming?: boolean;
suggestions?: boolean;
tracing?: boolean;
iam?: IAM;
// +listType=atomic
roles?: Role[];
extensions?: Extensions;
}
export const defaultJSONData = (): JSONData => ({
id: "",
type: "app",
name: "",
info: defaultInfo(),
dependencies: defaultDependencies(),
});
export interface Info {
// Required fields
// +listType=set
keywords: string[];
logos: {
small: string;
large: string;
};
updated: string;
version: string;
// Optional fields
author?: {
name?: string;
email?: string;
url?: string;
};
description?: string;
// +listType=atomic
links?: {
name?: string;
url?: string;
}[];
// +listType=atomic
screenshots?: {
name?: string;
path?: string;
}[];
}
export const defaultInfo = (): Info => ({
keywords: [],
logos: {
small: "",
large: "",
},
updated: "",
version: "",
});
export interface Dependencies {
// Required field
grafanaDependency: string;
// Optional fields
grafanaVersion?: string;
// +listType=set
// +listMapKey=id
plugins?: {
id: string;
type: "app" | "datasource" | "panel";
name: string;
}[];
extensions?: {
// +listType=set
exposedComponents?: string[];
};
}
export const defaultDependencies = (): Dependencies => ({
grafanaDependency: "",
});
export interface EnterpriseFeatures {
// Allow additional properties
healthDiagnosticsErrors?: boolean;
}
export const defaultEnterpriseFeatures = (): EnterpriseFeatures => ({
healthDiagnosticsErrors: false,
});
export interface Include {
uid?: string;
type?: "dashboard" | "page" | "panel" | "datasource";
name?: string;
component?: string;
role?: "Admin" | "Editor" | "Viewer" | "None";
action?: string;
path?: string;
addToNav?: boolean;
defaultNav?: boolean;
icon?: string;
}
export const defaultInclude = (): Include => ({
});
export interface QueryOptions {
maxDataPoints?: boolean;
minInterval?: boolean;
cacheTimeout?: boolean;
}
export const defaultQueryOptions = (): QueryOptions => ({
});
export interface Route {
path?: string;
method?: string;
url?: string;
reqSignedIn?: boolean;
reqRole?: string;
reqAction?: string;
// +listType=atomic
headers?: string[];
body?: Record<string, any>;
tokenAuth?: {
url?: string;
// +listType=set
scopes?: string[];
params?: Record<string, any>;
};
jwtTokenAuth?: {
url?: string;
// +listType=set
scopes?: string[];
params?: Record<string, any>;
};
// +listType=atomic
urlParams?: {
name?: string;
content?: string;
}[];
}
export const defaultRoute = (): Route => ({
});
export interface IAM {
// +listType=atomic
permissions?: {
action?: string;
scope?: string;
}[];
}
export const defaultIAM = (): IAM => ({
});
export interface Role {
role?: {
name?: string;
description?: string;
// +listType=atomic
permissions?: {
action?: string;
scope?: string;
}[];
};
// +listType=set
grants?: string[];
}
export const defaultRole = (): Role => ({
});
export interface Extensions {
// +listType=atomic
addedComponents?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=atomic
addedLinks?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=atomic
addedFunctions?: {
// +listType=set
targets: string[];
title: string;
description?: string;
}[];
// +listType=set
// +listMapKey=id
exposedComponents?: {
id: string;
title?: string;
description?: string;
}[];
// +listType=set
// +listMapKey=id
extensionPoints?: {
id: string;
title?: string;
description?: string;
}[];
}
export const defaultExtensions = (): Extensions => ({
});
export interface Spec {
pluginJson: JSONData;
class: "core" | "external";
module?: {
path: string;
hash?: string;
loadingStrategy?: "fetch" | "script";
};
baseURL?: string;
signature?: {
status: "internal" | "valid" | "invalid" | "modified" | "unsigned";
type?: "grafana" | "commercial" | "community" | "private" | "private-glob";
org?: string;
};
angular?: {
detected: boolean;
};
translations?: Record<string, string>;
// +listType=atomic
children?: string[];
}
export const defaultSpec = (): Spec => ({
pluginJson: defaultJSONData(),
class: "core",
});
@@ -1,30 +0,0 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
export interface OperatorState {
// lastEvaluation is the ResourceVersion last evaluated
lastEvaluation: string;
// state describes the state of the lastEvaluation.
// It is limited to three possible states for machine evaluation.
state: "success" | "in_progress" | "failed";
// descriptiveState is an optional more descriptive state field which has no requirements on format
descriptiveState?: string;
// details contains any extra information that is operator-specific
details?: Record<string, any>;
}
export const defaultOperatorState = (): OperatorState => ({
lastEvaluation: "",
state: "success",
});
export interface Status {
// operatorStates is a map of operator ID to operator state evaluations.
// Any operator which consumes this kind SHOULD add its state evaluation information to this field.
operatorStates?: Record<string, OperatorState>;
// additionalFields is reserved for future use
additionalFields?: Record<string, any>;
}
export const defaultStatus = (): Status => ({
});
@@ -16,6 +16,8 @@ export type PyroscopeQueryType = ('metrics' | 'profile' | 'both');
export const defaultPyroscopeQueryType: PyroscopeQueryType = 'both';
export type HeatmapQueryType = ('individual' | 'span');
export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
/**
* If set to true, the response will contain annotations
@@ -25,10 +27,18 @@ export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
* Allows to group the results.
*/
groupBy: Array<string>;
/**
* Specifies the type of heatmap query
*/
heatmapType: (HeatmapQueryType | 'individual');
/**
* If set to true, exemplars will be requested
*/
includeExemplars: boolean;
/**
* If set to true, heatmap data will be requested
*/
includeHeatmap: boolean;
/**
* Specifies the query label selectors.
*/
@@ -53,7 +63,9 @@ export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
export const defaultGrafanaPyroscopeDataQuery: Partial<GrafanaPyroscopeDataQuery> = {
groupBy: [],
heatmapType: 'individual',
includeExemplars: false,
includeHeatmap: false,
labelSelector: '{}',
spanSelector: [],
};
+10 -12
View File
@@ -42,7 +42,7 @@ func (r *converter) asDataSource(ds *datasources.DataSource) (*datasourceV0.Data
Generation: int64(ds.Version),
},
Spec: datasourceV0.UnstructuredSpec{},
Secure: ToInlineSecureValues("", ds.UID, maps.Keys(ds.SecureJsonData)),
Secure: ToInlineSecureValues(ds.Type, ds.UID, maps.Keys(ds.SecureJsonData)),
}
obj.UID = gapiutil.CalculateClusterWideUID(obj)
obj.Spec.SetTitle(ds.Name).
@@ -82,11 +82,18 @@ func (r *converter) asDataSource(ds *datasources.DataSource) (*datasourceV0.Data
// ToInlineSecureValues converts secure json into InlineSecureValues with reference names
// The names are predictable and can be used while we implement dual writing for secrets
func ToInlineSecureValues(_ string, dsUID string, keys iter.Seq[string]) common.InlineSecureValues {
func ToInlineSecureValues(dsType string, dsUID string, keys iter.Seq[string]) common.InlineSecureValues {
values := make(common.InlineSecureValues)
for k := range keys {
h := sha256.New()
h.Write([]byte(dsType)) // plugin id
h.Write([]byte("|"))
h.Write([]byte(dsUID)) // unique identifier
h.Write([]byte("|"))
h.Write([]byte(k)) // property name
n := hex.EncodeToString(h.Sum(nil))
values[k] = common.InlineSecureValue{
Name: getLegacySecureValueName(dsUID, k),
Name: "ds-" + n[0:10], // predictable name for dual writing
}
}
if len(values) == 0 {
@@ -95,15 +102,6 @@ func ToInlineSecureValues(_ string, dsUID string, keys iter.Seq[string]) common.
return values
}
func getLegacySecureValueName(dsUID string, key string) string {
h := sha256.New()
h.Write([]byte(dsUID)) // unique identifier
h.Write([]byte("|"))
h.Write([]byte(key)) // property name
n := hex.EncodeToString(h.Sum(nil))
return "ds-" + n[0:10] // predictable name for dual writing
}
func (r *converter) toAddCommand(ds *datasourceV0.DataSource) (*datasources.AddDataSourceCommand, error) {
if r.group != "" && ds.APIVersion != "" && !strings.HasPrefix(ds.APIVersion, r.group) {
return nil, fmt.Errorf("expecting APIGroup: %s", r.group)
@@ -11,11 +11,9 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/rest"
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
"github.com/grafana/grafana/pkg/apimachinery/utils"
"github.com/grafana/grafana/pkg/apis/datasource/v0alpha1"
"github.com/grafana/grafana/pkg/infra/metrics/metricutil"
"github.com/grafana/grafana/pkg/storage/legacysql/dualwrite"
)
var (
@@ -92,20 +90,6 @@ func (s *legacyStorage) Create(ctx context.Context, obj runtime.Object, createVa
if !ok {
return nil, fmt.Errorf("expected a datasource object")
}
// Verify the secure value commands
for _, v := range ds.Secure {
if v.Create.IsZero() {
return nil, fmt.Errorf("secure values must use create when creating a new datasource")
}
if v.Remove {
return nil, fmt.Errorf("secure values can not use remove when creating a new datasource")
}
if v.Name != "" {
return nil, fmt.Errorf("secure values can not specify a name when creating a new datasource")
}
}
return s.datasources.CreateDataSource(ctx, ds)
}
@@ -138,26 +122,6 @@ func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.Up
return nil, false, fmt.Errorf("expected a datasource object (old)")
}
// Expose any secure value changes to the dual writer
var secureChanges common.InlineSecureValues
for k, v := range ds.Secure {
if v.Remove || v.Create != "" {
if secureChanges == nil {
secureChanges = make(common.InlineSecureValues)
}
secureChanges[k] = v
dualwrite.SetUpdatedSecureValues(ctx, ds.Secure)
continue
}
// The legacy store must use fixed names generated by the internal system
// we can not support external shared secrets when using the SQL backing for datasources
validName := getLegacySecureValueName(name, k)
if v.Name != validName {
return nil, false, fmt.Errorf("invalid secure value name %q, expected %q", v.Name, validName)
}
}
// Keep all the old secure values
if len(oldDS.Secure) > 0 {
for k, v := range oldDS.Secure {
+2 -9
View File
@@ -30,7 +30,6 @@ import (
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/apiserver/builder"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/storage/unified/apistore"
"github.com/grafana/grafana/pkg/tsdb/grafana-testdata-datasource/kinds"
)
@@ -103,10 +102,10 @@ func RegisterAPIService(
datasources.GetDatasourceProvider(pluginJSON),
contextProvider,
accessControl,
//nolint:staticcheck // not yet migrated to OpenFeature
DataSourceAPIBuilderConfig{
//nolint:staticcheck // not yet migrated to OpenFeature
LoadQueryTypes: features.IsEnabledGlobally(featuremgmt.FlagDatasourceQueryTypes),
UseDualWriter: features.IsEnabledGlobally(featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs),
UseDualWriter: false,
},
)
if err != nil {
@@ -225,12 +224,6 @@ func (b *DataSourceAPIBuilder) AllowedV0Alpha1Resources() []string {
}
func (b *DataSourceAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.APIGroupInfo, opts builder.APIGroupOptions) error {
opts.StorageOptsRegister(b.datasourceResourceInfo.GroupResource(), apistore.StorageOptions{
EnableFolderSupport: false,
Scheme: opts.Scheme, // allows for generic Type applied to multiple groups
})
storage := map[string]rest.Storage{}
// Register the raw datasource connection
@@ -33,7 +33,7 @@
},
"secure": {
"password": {
"name": "ds-0d27eff323"
"name": "ds-d5c1b093af"
}
}
}
@@ -22,10 +22,10 @@
},
"secure": {
"extra": {
"name": "ds-6ed1b76e5d"
"name": "ds-bb8b5d8b32"
},
"password": {
"name": "ds-edc8fde0ac"
"name": "ds-973a1eb29d"
}
}
}
@@ -60,7 +60,7 @@ func (s *LocalInlineSecureValueService) CanReference(ctx context.Context, owner
}
if owner.APIGroup == "" || owner.APIVersion == "" || owner.Kind == "" || owner.Name == "" {
return fmt.Errorf("owner reference must have a valid API group, API version, kind and name [CanReference]")
return fmt.Errorf("owner reference must have a valid API group, API version, kind and name")
}
if len(names) == 0 {
@@ -167,7 +167,7 @@ func (s *LocalInlineSecureValueService) verifyOwnerAndAuth(ctx context.Context,
}
if owner.Namespace == "" || owner.APIGroup == "" || owner.APIVersion == "" || owner.Kind == "" || owner.Name == "" {
return nil, fmt.Errorf("owner reference must have a valid API group, API version, kind, namespace and name [verifyOwnerAndAuth:%+v]", owner)
return nil, fmt.Errorf("owner reference must have a valid API group, API version, kind, namespace and name")
}
return authInfo, nil
+7
View File
@@ -2069,6 +2069,13 @@ var (
Owner: grafanaObservabilityTracesAndProfilingSquad,
FrontendOnly: false,
},
{
Name: "profilesHeatmap",
Description: "Enables heatmap visualization support for Pyroscope profiles",
Stage: FeatureStageExperimental,
Owner: grafanaObservabilityTracesAndProfilingSquad,
FrontendOnly: false,
},
}
)
+1
View File
@@ -280,3 +280,4 @@ multiPropsVariables,experimental,@grafana/dashboards-squad,false,false,true
smoothingTransformation,experimental,@grafana/datapro,false,false,true
secretsManagementAppPlatformAwsKeeper,experimental,@grafana/grafana-operator-experience-squad,false,false,false
profilesExemplars,experimental,@grafana/observability-traces-and-profiling,false,false,false
profilesHeatmap,experimental,@grafana/observability-traces-and-profiling,false,false,false
1 Name Stage Owner requiresDevMode RequiresRestart FrontendOnly
280 smoothingTransformation experimental @grafana/datapro false false true
281 secretsManagementAppPlatformAwsKeeper experimental @grafana/grafana-operator-experience-squad false false false
282 profilesExemplars experimental @grafana/observability-traces-and-profiling false false false
283 profilesHeatmap experimental @grafana/observability-traces-and-profiling false false false
+4
View File
@@ -789,4 +789,8 @@ const (
// FlagProfilesExemplars
// Enables profiles exemplars support in profiles drilldown
FlagProfilesExemplars = "profilesExemplars"
// FlagProfilesHeatmap
// Enables heatmap visualization support for Pyroscope profiles
FlagProfilesHeatmap = "profilesHeatmap"
)
+12
View File
@@ -2955,6 +2955,18 @@
"codeowner": "@grafana/observability-traces-and-profiling"
}
},
{
"metadata": {
"name": "profilesHeatmap",
"resourceVersion": "1767703801452",
"creationTimestamp": "2026-01-06T12:50:01Z"
},
"spec": {
"description": "Enables heatmap visualization support for Pyroscope profiles",
"stage": "experimental",
"codeowner": "@grafana/observability-traces-and-profiling"
}
},
{
"metadata": {
"name": "prometheusAzureOverrideAudience",
@@ -1,35 +0,0 @@
package dualwrite
import (
"context"
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
)
type ctxKey struct{}
type dualWriteContext struct {
updatedSecureValues common.InlineSecureValues
}
func addToContext(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxKey{}, &dualWriteContext{})
}
// Get the Requester from context
func SetUpdatedSecureValues(ctx context.Context, sv common.InlineSecureValues) {
u, ok := ctx.Value(ctxKey{}).(*dualWriteContext)
if !ok || u == nil {
return // OK, this can happen when things are in mode 0 (legacy only)
}
u.updatedSecureValues = sv
}
// Get the Requester from context
func getUpdatedSecureValues(ctx context.Context) common.InlineSecureValues {
u, ok := ctx.Value(ctxKey{}).(*dualWriteContext)
if !ok || u == nil {
return nil
}
return u.updatedSecureValues
}
+22 -41
View File
@@ -16,15 +16,14 @@ import (
"k8s.io/apiserver/pkg/registry/rest"
"github.com/grafana/grafana-app-sdk/logging"
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
"github.com/grafana/grafana/pkg/apimachinery/utils"
grafanarest "github.com/grafana/grafana/pkg/apiserver/rest"
)
var (
_ grafanarest.Storage = (*dualWriter)(nil)
tracer = otel.Tracer("github.com/grafana/grafana/pkg/storage/legacysql/dualwrite")
_ grafanarest.Storage = (*dualWriter)(nil)
tracer = otel.Tracer("github.com/grafana/grafana/pkg/storage/legacysql/dualwrite")
)
const (
@@ -204,7 +203,7 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
log := logging.FromContext(ctx).With("method", "Create")
accIn, err := utils.MetaAccessor(in)
accIn, err := meta.Accessor(in)
if err != nil {
return nil, err
}
@@ -217,19 +216,19 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
return nil, fmt.Errorf("name or generatename have to be set")
}
secure, err := accIn.GetSecureValues()
if err != nil {
return nil, fmt.Errorf("unable to read secure values %w", err)
}
readFromUnifiedWriteToBothStorages := d.readUnified && d.legacy != nil && d.unified != nil
permissions := ""
if readFromUnifiedWriteToBothStorages {
objIn, err := utils.MetaAccessor(in)
if err != nil {
return nil, err
}
// keep permissions, we will set it back after the object is created
permissions = accIn.GetAnnotation(utils.AnnoKeyGrantPermissions)
permissions = objIn.GetAnnotation(utils.AnnoKeyGrantPermissions)
if permissions != "" {
accIn.SetAnnotation(utils.AnnoKeyGrantPermissions, "") // remove the annotation for now
objIn.SetAnnotation(utils.AnnoKeyGrantPermissions, "") // remove the annotation for now
}
}
@@ -242,36 +241,35 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
}
createdCopy := createdFromLegacy.DeepCopyObject()
accCreated, err := utils.MetaAccessor(createdCopy)
accCreated, err := meta.Accessor(createdCopy)
if err != nil {
return nil, err
}
accCreated.SetResourceVersion("")
accCreated.SetUID("")
if secure != nil {
if err = accCreated.SetSecureValues(secure); err != nil {
return nil, fmt.Errorf("unable to set secure values on duplicate object %w", err)
}
}
if readFromUnifiedWriteToBothStorages {
objCopy, err := utils.MetaAccessor(createdCopy)
if err != nil {
return nil, err
}
// restore the permissions annotation, as we removed it before creating in legacy
if permissions != "" {
accCreated.SetAnnotation(utils.AnnoKeyGrantPermissions, permissions)
objCopy.SetAnnotation(utils.AnnoKeyGrantPermissions, permissions)
}
// Propagate annotations and labels to the object saved in
// unified storage, making sure the `deprecatedID` is saved
// as well as provisioning metadata, when present.
for name, val := range accIn.GetAnnotations() {
accCreated.SetAnnotation(name, val)
objCopy.SetAnnotation(name, val)
}
legacyAcc, err := meta.Accessor(createdFromLegacy)
if err != nil {
return nil, err
}
accCreated.SetLabels(legacyAcc.GetLabels())
objCopy.SetLabels(legacyAcc.GetLabels())
}
// If unified storage is the primary storage, let's just create it in the foreground and return it.
@@ -386,7 +384,6 @@ func (d *dualWriter) Update(ctx context.Context, name string, objInfo rest.Updat
// but legacy failed, the user would get a failure, but see the update did apply to the source
// of truth, and be less likely to retry to save (and get the stores in sync again)
ctx = addToContext(ctx)
legacyInfo := objInfo
legacyForceCreate := forceAllowCreate
unifiedInfo := objInfo
@@ -420,14 +417,6 @@ func (d *dualWriter) Update(ctx context.Context, name string, objInfo rest.Updat
}
}
// Propagate secure values from the update request to the unified storage update.
if secure := getUpdatedSecureValues(ctx); secure != nil {
wrapped, ok := unifiedInfo.(*wrappedUpdateInfo)
if ok {
wrapped.updatedSecureValues = secure
}
}
if d.readUnified {
return d.unified.Update(ctx, name, unifiedInfo, createValidation, updateValidation, unifiedForceCreate, options)
} else if d.errorIsOK {
@@ -526,10 +515,9 @@ func (d *dualWriter) ConvertToTable(ctx context.Context, object runtime.Object,
}
type wrappedUpdateInfo struct {
objInfo rest.UpdatedObjectInfo
legacyLabels map[string]string
legacyAnnotations map[string]string
updatedSecureValues common.InlineSecureValues
objInfo rest.UpdatedObjectInfo
legacyLabels map[string]string
legacyAnnotations map[string]string
}
// Preconditions implements rest.UpdatedObjectInfo.
@@ -572,13 +560,6 @@ func (w *wrappedUpdateInfo) UpdatedObject(ctx context.Context, oldObj runtime.Ob
meta.SetResourceVersion("")
meta.SetUID("")
if w.updatedSecureValues != nil {
if err = meta.SetSecureValues(w.updatedSecureValues); err != nil {
return nil, fmt.Errorf("unable to set secure values on duplicate object %w", err)
}
}
return obj, err
}
+5 -55
View File
@@ -3,10 +3,8 @@ package apistore
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/dustin/go-humanize"
@@ -85,9 +83,6 @@ func (s *Storage) prepareObjectForStorage(ctx context.Context, newObject runtime
if !ok {
return v, errors.New("missing auth info")
}
if err := s.checkGVK(newObject); err != nil {
return v, err
}
obj, err := utils.MetaAccessor(newObject)
if err != nil {
@@ -143,7 +138,8 @@ func (s *Storage) prepareObjectForStorage(ctx context.Context, newObject runtime
return v, err
}
if err = s.encode(newObject, &v.raw); err == nil {
err = s.codec.Encode(newObject, &v.raw)
if err == nil {
err = s.handleLargeResources(ctx, obj, &v.raw)
}
return v, err
@@ -156,9 +152,6 @@ func (s *Storage) prepareObjectForUpdate(ctx context.Context, updateObject runti
if !ok {
return v, errors.New("missing auth info")
}
if err := s.checkGVK(updateObject); err != nil {
return v, err
}
obj, err := utils.MetaAccessor(updateObject)
if err != nil {
@@ -240,7 +233,8 @@ func (s *Storage) prepareObjectForUpdate(ctx context.Context, updateObject runti
obj.SetAnnotation(utils.AnnoKeyUpdatedTimestamp, previous.GetAnnotation(utils.AnnoKeyUpdatedTimestamp))
}
if err = s.encode(updateObject, &v.raw); err == nil {
err = s.codec.Encode(updateObject, &v.raw)
if err == nil {
err = s.handleLargeResources(ctx, obj, &v.raw)
}
return v, err
@@ -274,51 +268,7 @@ func (s *Storage) handleLargeResources(ctx context.Context, obj utils.GrafanaMet
}
// Now encode the smaller version
return s.encode(orig, buf)
return s.codec.Encode(orig, buf)
}
return nil
}
func (s *Storage) checkGVK(obj runtime.Object) error {
if s.opts.Scheme == nil {
return nil // we can not do anything
}
// Ensure group+version+kind are configured
info := obj.GetObjectKind()
gvk := info.GroupVersionKind()
if gvk.Group == "" || gvk.Kind == "" || gvk.Version == "" {
gvks, _, err := s.opts.Scheme.ObjectKinds(obj)
if err != nil {
return fmt.Errorf("unknown object kind %w", err)
}
for _, v := range gvks {
if v.Group != s.gr.Group {
continue // skip values not in this group
}
gvk.Group = v.Group
gvk.Kind = v.Kind
if gvk.Version == "" {
gvk.Version = v.Version
}
info.SetGroupVersionKind(gvk)
return nil
}
}
return nil
}
func (s *Storage) encode(obj runtime.Object, w io.Writer) error {
// The standard encoder is fine when only one type maps to a group
if s.opts.Scheme == nil {
return s.codec.Encode(obj, w)
}
if err := s.checkGVK(obj); err != nil {
return err
}
// This will always write the saved GVK, unlike:
// https://github.com/kubernetes/kubernetes/blob/v1.34.3/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go#L267
// that picks an arbitrary GVK that may not match the same group!
return json.NewEncoder(w).Encode(obj)
}
@@ -33,11 +33,9 @@ func TestPrepareObjectForStorage(t *testing.T) {
node, err := snowflake.NewNode(rand.Int64N(1024))
require.NoError(t, err)
s := &Storage{
gr: dashv1.DashboardResourceInfo.GroupResource(),
codec: apitesting.TestCodec(rtcodecs, dashv1.DashboardResourceInfo.GroupVersion()),
snowflake: node,
opts: StorageOptions{
Scheme: rtscheme,
EnableFolderSupport: true,
LargeObjectSupport: nil,
MaximumNameLength: 100,
-2
View File
@@ -57,8 +57,6 @@ type DefaultPermissionSetter = func(ctx context.Context, key *resourcepb.Resourc
// Optional settings that apply to a single resource
type StorageOptions struct {
Scheme *runtime.Scheme
// ????: should we constrain this to only dashboards for now?
// Not yet clear if this is a good general solution, or just a stop-gap
LargeObjectSupport LargeObjectSupport
+99 -183
View File
@@ -5,8 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"testing"
"github.com/stretchr/testify/require"
@@ -15,11 +13,9 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/grafana/grafana/pkg/apimachinery/utils"
grafanarest "github.com/grafana/grafana/pkg/apiserver/rest"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tests/apis"
"github.com/grafana/grafana/pkg/tests/testinfra"
"github.com/grafana/grafana/pkg/tests/testsuite"
@@ -32,192 +28,112 @@ func TestMain(m *testing.M) {
func TestIntegrationTestDatasource(t *testing.T) {
testutil.SkipIntegrationTestInShortMode(t)
expectedAPIVersion := "grafana-testdata-datasource.datasource.grafana.app/v0alpha1"
for _, mode := range []grafanarest.DualWriterMode{
grafanarest.Mode0, // Legacy only
grafanarest.Mode2, // write both, read legacy
grafanarest.Mode3, // write both, read unified
grafanarest.Mode5, // Unified only
} {
t.Run(fmt.Sprintf("testdata (mode:%d)", mode), func(t *testing.T) {
ctx := context.Background()
helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{
DisableAnonymous: true,
EnableFeatureToggles: []string{
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, // Required to start the datasource api servers
featuremgmt.FlagQueryServiceWithConnections, // enables CRUD endpoints
},
UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{
"datasources.grafana-testdata-datasource.datasource.grafana.app": {
DualWriterMode: mode,
},
},
})
helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{
AppModeProduction: false, // dev mode required for datasource connections
DisableAnonymous: true,
EnableFeatureToggles: []string{
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, // Required to start the example service
},
})
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
Group: "grafana-testdata-datasource.datasource.grafana.app",
Version: "v0alpha1",
Resource: "datasources",
}).Namespace("default")
// Create a single datasource
ds := helper.CreateDS(&datasources.AddDataSourceCommand{
Name: "test",
Type: datasources.DS_TESTDATA,
UID: "test",
OrgID: int64(1),
t.Run("create", func(t *testing.T) {
out, err := client.Create(ctx, &unstructured.Unstructured{
Object: map[string]any{
"apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
"kind": "DataSource",
"metadata": map[string]any{
"name": "test",
},
"spec": map[string]any{
"title": "test",
},
"secure": map[string]any{
"aaa": map[string]any{
"create": "AAA",
},
"bbb": map[string]any{
"create": "BBB",
},
},
},
}, metav1.CreateOptions{})
require.NoError(t, err)
require.Equal(t, "test", out.GetName())
require.Equal(t, expectedAPIVersion, out.GetAPIVersion())
// These settings are not actually used, but testing that they get saved
Database: "testdb",
URL: "http://fake.url",
Access: datasources.DS_ACCESS_PROXY,
User: "example",
ReadOnly: true,
JsonData: simplejson.NewFromAny(map[string]any{
"hello": "world",
}),
SecureJsonData: map[string]string{
"aaa": "AAA",
"bbb": "BBB",
},
})
require.Equal(t, "test", ds.UID)
obj, err := utils.MetaAccessor(out)
require.NoError(t, err)
t.Run("Admin configs", func(t *testing.T) {
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
Group: "grafana-testdata-datasource.datasource.grafana.app",
Version: "v0alpha1",
Resource: "datasources",
}).Namespace("default")
ctx := context.Background()
secure, err := obj.GetSecureValues()
require.NoError(t, err)
list, err := client.List(ctx, metav1.ListOptions{})
require.NoError(t, err)
require.Len(t, list.Items, 1, "expected a single connection")
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
keys := slices.Collect(maps.Keys(secure))
require.ElementsMatch(t, []string{"aaa", "bbb"}, keys)
})
spec, _, _ := unstructured.NestedMap(list.Items[0].Object, "spec")
jj, _ := json.MarshalIndent(spec, "", " ")
fmt.Printf("%s\n", string(jj))
require.JSONEq(t, `{
"access": "proxy",
"database": "testdb",
"isDefault": true,
"jsonData": {
"hello": "world"
},
"readOnly": true,
"title": "test",
"url": "http://fake.url",
"user": "example"
}`, string(jj))
})
t.Run("update", func(t *testing.T) {
out, err := client.Update(ctx, &unstructured.Unstructured{
Object: map[string]any{
"apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
"metadata": map[string]any{
"name": "test",
},
"spec": map[string]any{
"title": "test",
"database": "testdb",
"url": "http://fake.url",
"access": datasources.DS_ACCESS_PROXY,
"user": "example",
"isDefault": true,
"readOnly": true,
"jsonData": map[string]any{
"hello": "world",
},
},
"secure": map[string]any{
// "aaa": map[string]any{
// "remove": true, // remove does not really remove in legacy!
// },
"ccc": map[string]any{
"create": "CCC", // add a third value
},
},
},
}, metav1.UpdateOptions{})
require.NoError(t, err)
require.Equal(t, "test", out.GetName())
require.Equal(t, expectedAPIVersion, out.GetAPIVersion())
t.Run("Call subresources", func(t *testing.T) {
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
Group: "grafana-testdata-datasource.datasource.grafana.app",
Version: "v0alpha1",
Resource: "datasources",
}).Namespace("default")
ctx := context.Background()
obj, err := utils.MetaAccessor(out)
require.NoError(t, err)
list, err := client.List(ctx, metav1.ListOptions{})
require.NoError(t, err)
require.Len(t, list.Items, 1, "expected a single connection")
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
secure, err := obj.GetSecureValues()
require.NoError(t, err)
_, err = client.Get(ctx, "test", metav1.GetOptions{}, "health")
// endpoint is disabled currently because it has not been
// sufficiently tested.
// for more info see pkg/registry/apis/datasource/sub_health.go
require.Error(t, err)
var statusErr *apierrors.StatusError
require.True(t, errors.As(err, &statusErr))
require.Equal(t, int32(501), statusErr.ErrStatus.Code)
// require.NoError(t, err)
// body, err := rsp.MarshalJSON()
// require.NoError(t, err)
// //fmt.Printf("GOT: %v\n", string(body))
// require.JSONEq(t, `{
// "apiVersion": "testdata.datasource.grafana.app/v0alpha1",
// "code": 1,
// "kind": "HealthCheckResult",
// "message": "Data source is working",
// "status": "OK"
// }
// `, string(body))
keys := slices.Collect(maps.Keys(secure))
require.ElementsMatch(t, []string{"aaa", "bbb", "ccc"}, keys)
})
t.Run("list", func(t *testing.T) {
list, err := client.List(ctx, metav1.ListOptions{})
require.NoError(t, err)
require.Equal(t, expectedAPIVersion, list.GetAPIVersion())
require.Len(t, list.Items, 1, "expected a single datasource")
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
spec, _, _ := unstructured.NestedMap(list.Items[0].Object, "spec")
jj, _ := json.MarshalIndent(spec, "", " ")
// fmt.Printf("%s\n", string(jj))
require.JSONEq(t, `{
"access": "proxy",
"database": "testdb",
"isDefault": true,
"jsonData": {
"hello": "world"
},
"readOnly": true,
"title": "test",
"url": "http://fake.url",
"user": "example"
}`, string(jj))
})
t.Run("execute", func(t *testing.T) {
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
Group: "grafana-testdata-datasource.datasource.grafana.app",
Version: "v0alpha1",
Resource: "datasources",
}).Namespace("default")
ctx := context.Background()
list, err := client.List(ctx, metav1.ListOptions{})
require.NoError(t, err)
require.Len(t, list.Items, 1, "expected a single connection")
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
_, err = client.Get(ctx, "test", metav1.GetOptions{}, "health")
// endpoint is disabled currently because it has not been
// sufficiently tested.
// for more info see pkg/registry/apis/datasource/sub_health.go
require.Error(t, err)
var statusErr *apierrors.StatusError
require.True(t, errors.As(err, &statusErr))
require.Equal(t, int32(501), statusErr.ErrStatus.Code)
// require.NoError(t, err)
// body, err := rsp.MarshalJSON()
// require.NoError(t, err)
// //fmt.Printf("GOT: %v\n", string(body))
// require.JSONEq(t, `{
// "apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
// "code": 1,
// "kind": "HealthCheckResult",
// "message": "Data source is working",
// "status": "OK"
// }
// `, string(body))
// Test connecting to non-JSON marshaled data
raw := apis.DoRequest[any](helper, apis.RequestParams{
User: helper.Org1.Admin,
Method: "GET",
Path: "/apis/grafana-testdata-datasource.datasource.grafana.app/v0alpha1/namespaces/default/datasources/test/resource",
}, nil)
// endpoint is disabled currently because it has not been
// sufficiently tested.
// for more info see pkg/registry/apis/datasource/sub_resource.go
require.Equal(t, int32(501), raw.Status.Code)
// require.Equal(t, `Hello world from test datasource!`, string(raw.Body))
})
t.Run("delete", func(t *testing.T) {
err := client.Delete(ctx, "test", metav1.DeleteOptions{})
require.NoError(t, err)
list, err := client.List(ctx, metav1.ListOptions{})
require.NoError(t, err)
require.Empty(t, list.Items)
})
})
}
// Test connecting to non-JSON marshaled data
raw := apis.DoRequest[any](helper, apis.RequestParams{
User: helper.Org1.Admin,
Method: "GET",
Path: "/apis/grafana-testdata-datasource.datasource.grafana.app/v0alpha1/namespaces/default/datasources/test/resource",
}, nil)
// endpoint is disabled currently because it has not been
// sufficiently tested.
// for more info see pkg/registry/apis/datasource/sub_resource.go
require.Equal(t, int32(501), raw.Status.Code)
// require.Equal(t, `Hello world from test datasource!`, string(raw.Body))
})
}
@@ -103,98 +103,6 @@
],
"description": "list objects of kind DataSource",
"operationId": "listDataSource",
"parameters": [
{
"name": "allowWatchBookmarks",
"in": "query",
"description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "continue",
"in": "query",
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "labelSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "limit",
"in": "query",
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "resourceVersion",
"in": "query",
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "resourceVersionMatch",
"in": "query",
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "sendInitialEvents",
"in": "query",
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "timeoutSeconds",
"in": "query",
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "watch",
"in": "query",
"description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
}
],
"responses": {
"200": {
"description": "OK",
@@ -234,285 +142,52 @@
"kind": "DataSource"
}
},
"post": {
"tags": [
"DataSource"
],
"description": "create a DataSource",
"operationId": "createDataSource",
"parameters": [
{
"name": "dryRun",
"in": "query",
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldManager",
"in": "query",
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldValidation",
"in": "query",
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
"schema": {
"type": "string",
"uniqueItems": true
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
},
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
},
"202": {
"description": "Accepted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
}
},
"x-kubernetes-action": "post",
"x-kubernetes-group-version-kind": {
"group": "grafana-testdata-datasource.datasource.grafana.app",
"version": "v0alpha1",
"kind": "DataSource"
}
},
"delete": {
"tags": [
"DataSource"
],
"description": "delete collection of DataSource",
"operationId": "deletecollectionDataSource",
"parameters": [
{
"name": "continue",
"in": "query",
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "dryRun",
"in": "query",
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "gracePeriodSeconds",
"in": "query",
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "ignoreStoreReadErrorWithClusterBreakingPotential",
"in": "query",
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "labelSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "limit",
"in": "query",
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "orphanDependents",
"in": "query",
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "propagationPolicy",
"in": "query",
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "resourceVersion",
"in": "query",
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "resourceVersionMatch",
"in": "query",
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "sendInitialEvents",
"in": "query",
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "timeoutSeconds",
"in": "query",
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
"schema": {
"type": "integer",
"uniqueItems": true
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
}
}
}
},
"x-kubernetes-action": "deletecollection",
"x-kubernetes-group-version-kind": {
"group": "grafana-testdata-datasource.datasource.grafana.app",
"version": "v0alpha1",
"kind": "DataSource"
}
},
"parameters": [
{
"name": "allowWatchBookmarks",
"in": "query",
"description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "continue",
"in": "query",
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "labelSelector",
"in": "query",
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "limit",
"in": "query",
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "namespace",
"in": "path",
@@ -531,6 +206,51 @@
"type": "string",
"uniqueItems": true
}
},
{
"name": "resourceVersion",
"in": "query",
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "resourceVersionMatch",
"in": "query",
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "sendInitialEvents",
"in": "query",
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "timeoutSeconds",
"in": "query",
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "watch",
"in": "query",
"description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
}
]
},
@@ -570,330 +290,6 @@
"kind": "DataSource"
}
},
"put": {
"tags": [
"DataSource"
],
"description": "replace the specified DataSource",
"operationId": "replaceDataSource",
"parameters": [
{
"name": "dryRun",
"in": "query",
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldManager",
"in": "query",
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldValidation",
"in": "query",
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
"schema": {
"type": "string",
"uniqueItems": true
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
},
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
}
},
"x-kubernetes-action": "put",
"x-kubernetes-group-version-kind": {
"group": "grafana-testdata-datasource.datasource.grafana.app",
"version": "v0alpha1",
"kind": "DataSource"
}
},
"delete": {
"tags": [
"DataSource"
],
"description": "delete a DataSource",
"operationId": "deleteDataSource",
"parameters": [
{
"name": "dryRun",
"in": "query",
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "gracePeriodSeconds",
"in": "query",
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
"schema": {
"type": "integer",
"uniqueItems": true
}
},
{
"name": "ignoreStoreReadErrorWithClusterBreakingPotential",
"in": "query",
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "orphanDependents",
"in": "query",
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
},
{
"name": "propagationPolicy",
"in": "query",
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
"schema": {
"type": "string",
"uniqueItems": true
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
}
}
},
"202": {
"description": "Accepted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
}
}
}
}
},
"x-kubernetes-action": "delete",
"x-kubernetes-group-version-kind": {
"group": "grafana-testdata-datasource.datasource.grafana.app",
"version": "v0alpha1",
"kind": "DataSource"
}
},
"patch": {
"tags": [
"DataSource"
],
"description": "partially update the specified DataSource",
"operationId": "updateDataSource",
"parameters": [
{
"name": "dryRun",
"in": "query",
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldManager",
"in": "query",
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "fieldValidation",
"in": "query",
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "force",
"in": "query",
"description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.",
"schema": {
"type": "boolean",
"uniqueItems": true
}
}
],
"requestBody": {
"content": {
"application/apply-patch+yaml": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
}
},
"application/json-patch+json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
}
},
"application/merge-patch+json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
}
},
"application/strategic-merge-patch+json": {
"schema": {
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
},
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/vnd.kubernetes.protobuf": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
},
"application/yaml": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
}
}
}
}
},
"x-kubernetes-action": "patch",
"x-kubernetes-group-version-kind": {
"group": "grafana-testdata-datasource.datasource.grafana.app",
"version": "v0alpha1",
"kind": "DataSource"
}
},
"parameters": [
{
"name": "name",
@@ -1550,54 +946,6 @@
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions": {
"description": "DeleteOptions may be provided when deleting an API object.",
"type": "object",
"properties": {
"apiVersion": {
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
"type": "string"
},
"dryRun": {
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
"type": "array",
"items": {
"type": "string",
"default": ""
},
"x-kubernetes-list-type": "atomic"
},
"gracePeriodSeconds": {
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
"type": "integer",
"format": "int64"
},
"ignoreStoreReadErrorWithClusterBreakingPotential": {
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
"type": "boolean"
},
"kind": {
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"type": "string"
},
"orphanDependents": {
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
"type": "boolean"
},
"preconditions": {
"description": "Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.",
"allOf": [
{
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions"
}
]
},
"propagationPolicy": {
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
"type": "string"
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1": {
"description": "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:\u003cname\u003e', where \u003cname\u003e is the name of a field in a struct, or key in a map 'v:\u003cvalue\u003e', where \u003cvalue\u003e is the exact json formatted value of a list item 'i:\u003cindex\u003e', where \u003cindex\u003e is position of a item in a list 'k:\u003ckeys\u003e', where \u003ckeys\u003e is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff",
"type": "object"
@@ -1821,131 +1169,6 @@
},
"x-kubernetes-map-type": "atomic"
},
"io.k8s.apimachinery.pkg.apis.meta.v1.Patch": {
"description": "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.",
"type": "object"
},
"io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions": {
"description": "Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.",
"type": "object",
"properties": {
"resourceVersion": {
"description": "Specifies the target ResourceVersion",
"type": "string"
},
"uid": {
"description": "Specifies the target UID.",
"type": "string"
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.Status": {
"description": "Status is a return value for calls that don't return other objects.",
"type": "object",
"properties": {
"apiVersion": {
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
"type": "string"
},
"code": {
"description": "Suggested HTTP return code for this status, 0 if not set.",
"type": "integer",
"format": "int32"
},
"details": {
"description": "Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type.",
"allOf": [
{
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.StatusDetails"
}
],
"x-kubernetes-list-type": "atomic"
},
"kind": {
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"type": "string"
},
"message": {
"description": "A human-readable description of the status of this operation.",
"type": "string"
},
"metadata": {
"description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"default": {},
"allOf": [
{
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta"
}
]
},
"reason": {
"description": "A machine-readable description of why this operation is in the \"Failure\" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it.",
"type": "string"
},
"status": {
"description": "Status of the operation. One of: \"Success\" or \"Failure\". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status",
"type": "string"
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.StatusCause": {
"description": "StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered.",
"type": "object",
"properties": {
"field": {
"description": "The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.\n\nExamples:\n \"name\" - the field \"name\" on the current resource\n \"items[0].name\" - the field \"name\" on the first array entry in \"items\"",
"type": "string"
},
"message": {
"description": "A human-readable description of the cause of the error. This field may be presented as-is to a reader.",
"type": "string"
},
"reason": {
"description": "A machine-readable description of the cause of the error. If this value is empty there is no information available.",
"type": "string"
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.StatusDetails": {
"description": "StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.",
"type": "object",
"properties": {
"causes": {
"description": "The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.",
"type": "array",
"items": {
"default": {},
"allOf": [
{
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.StatusCause"
}
]
},
"x-kubernetes-list-type": "atomic"
},
"group": {
"description": "The group attribute of the resource associated with the status StatusReason.",
"type": "string"
},
"kind": {
"description": "The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"type": "string"
},
"name": {
"description": "The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).",
"type": "string"
},
"retryAfterSeconds": {
"description": "If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action.",
"type": "integer",
"format": "int32"
},
"uid": {
"description": "UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids",
"type": "string"
}
}
},
"io.k8s.apimachinery.pkg.apis.meta.v1.Time": {
"description": "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.",
"type": "string",
@@ -1,43 +1,110 @@
package exemplar
import (
"sort"
"time"
"github.com/grafana/grafana-plugin-sdk-go/data"
)
type Exemplar struct {
Id string
ProfileId string
SpanId string
Value float64
Timestamp int64
Labels map[string]string
}
func CreateExemplarFrame(labels map[string]string, exemplars []*Exemplar) *data.Frame {
type ExemplarType string
const (
ExemplarTypeProfile ExemplarType = "profile"
ExemplarTypeSpan ExemplarType = "span"
)
func CreateExemplarFrame(labels map[string]string, exemplars []*Exemplar, exemplarType ExemplarType, units string) *data.Frame {
frame := data.NewFrame("exemplar")
frame.Meta = &data.FrameMeta{
DataTopic: data.DataTopicAnnotations,
}
fields := []*data.Field{
data.NewField("Time", nil, []time.Time{}),
data.NewField("Value", labels, []float64{}), // add labels here?
data.NewField("Id", nil, []string{}),
// Determine display name and which ID to use based on exemplar type
displayName := "Profile ID"
if exemplarType == ExemplarTypeSpan {
displayName = "Span ID"
}
fields[2].Config = &data.FieldConfig{
DisplayName: "Profile ID",
// Collect all unique label names across all exemplars
uniqLabelNames := make(map[string]struct{})
for _, e := range exemplars {
for name := range e.Labels {
uniqLabelNames[name] = struct{}{}
}
}
for name := range labels {
fields = append(fields, data.NewField(name, nil, []string{}))
uniqLabelNames[name] = struct{}{}
}
// Initialize fields
const offset = 3
fields := make([]*data.Field, 0, len(uniqLabelNames)+offset)
fields = append(fields, data.NewField("Time", nil, make([]time.Time, 0, len(exemplars))))
fields = append(fields, data.NewField("Value", labels, make([]float64, 0, len(exemplars)))) // Series labels attached to Value field
fields = append(fields, data.NewField("Id", nil, make([]string, 0, len(exemplars))))
// Configure the Value field with units and display name
valueFieldConfig := &data.FieldConfig{
DisplayName: "Value",
Unit: units,
}
fields[1].Config = valueFieldConfig
// Configure the Id field with display name
idFieldConfig := &data.FieldConfig{
DisplayName: displayName,
}
fields[2].Config = idFieldConfig
sortedLabelNames := make([]string, 0, len(uniqLabelNames))
for name := range uniqLabelNames {
sortedLabelNames = append(sortedLabelNames, name)
}
sort.Strings(sortedLabelNames)
// Create fields for all label names
for _, name := range sortedLabelNames {
fields = append(fields, data.NewField(name, nil, make([]string, 0, len(exemplars))))
}
frame.Fields = fields
row := make([]any, len(uniqLabelNames)+offset)
for _, e := range exemplars {
frame.AppendRow(time.UnixMilli(e.Timestamp), e.Value, e.Id)
for name, value := range labels {
field, _ := frame.FieldByName(name)
if field != nil {
field.Append(value)
}
row[0] = time.UnixMilli(e.Timestamp)
row[1] = e.Value
// Use the appropriate ID based on exemplar type
if exemplarType == ExemplarTypeSpan {
row[2] = e.SpanId
} else if exemplarType == ExemplarTypeProfile {
row[2] = e.ProfileId
}
// Append label values: prefer exemplar-specific values over series values
for idx, name := range sortedLabelNames {
// Check if this exemplar has this label
if value, ok := e.Labels[name]; ok {
row[idx+offset] = value
continue
}
if value, ok := labels[name]; ok {
row[idx+offset] = value
continue
}
row[idx+offset] = ""
}
frame.AppendRow(row...)
}
return frame
}
@@ -6,29 +6,220 @@ import (
"github.com/stretchr/testify/require"
)
func TestCreateExemplarFrame(t *testing.T) {
func TestCreateExemplarFrame_ProfileType(t *testing.T) {
exemplars := []*Exemplar{
{Id: "1", Value: 1.0, Timestamp: 100},
{Id: "2", Value: 2.0, Timestamp: 200},
{ProfileId: "profile-1", SpanId: "span-1", Value: 1.0, Timestamp: 100, Labels: map[string]string{"pod": "pod-1"}},
{ProfileId: "profile-2", SpanId: "span-2", Value: 2.0, Timestamp: 200, Labels: map[string]string{"pod": "pod-2"}},
}
labels := map[string]string{
"foo": "bar",
"service": "api",
}
frame := CreateExemplarFrame(labels, exemplars)
frame := CreateExemplarFrame(labels, exemplars, ExemplarTypeProfile, "bytes")
require.Equal(t, "exemplar", frame.Name)
require.Equal(t, 4, len(frame.Fields))
// Time, Value, Id, service (from labels), pod (from exemplar labels)
require.Equal(t, 5, len(frame.Fields))
require.Equal(t, "Time", frame.Fields[0].Name)
require.Equal(t, "Value", frame.Fields[1].Name)
require.Equal(t, "Id", frame.Fields[2].Name)
require.Equal(t, "foo", frame.Fields[3].Name)
// Check that Id field shows Profile ID
require.Equal(t, "Profile ID", frame.Fields[2].Config.DisplayName)
rows, err := frame.RowLen()
require.NoError(t, err)
require.Equal(t, 2, rows)
row := frame.RowCopy(0)
require.Equal(t, 4, len(row))
require.Equal(t, 5, len(row))
require.Equal(t, 1.0, row[1])
require.Equal(t, "1", row[2])
require.Equal(t, "bar", row[3])
require.Equal(t, "profile-1", row[2]) // Should use ProfileId for profile type
}
func TestCreateExemplarFrame_SpanType(t *testing.T) {
exemplars := []*Exemplar{
{
ProfileId: "profile-1",
SpanId: "span-abc123",
Value: 100.0,
Timestamp: 1000,
Labels: map[string]string{
"pod": "pod-xyz",
"namespace": "prod",
"__name__": "cpu",
},
},
}
labels := map[string]string{
"service": "api",
}
frame := CreateExemplarFrame(labels, exemplars, ExemplarTypeSpan, "nanoseconds")
require.Equal(t, "exemplar", frame.Name)
// Check Value field configuration
valueField := frame.Fields[1]
require.Equal(t, "Value", valueField.Name)
require.Equal(t, "Value", valueField.Config.DisplayName)
require.Equal(t, "nanoseconds", valueField.Config.Unit)
// Check Id field configuration
idField := frame.Fields[2]
require.Equal(t, "Id", idField.Name)
require.Equal(t, "Span ID", idField.Config.DisplayName)
// Verify span ID is used for span type
rows, err := frame.RowLen()
require.NoError(t, err)
require.Equal(t, 1, rows)
row := frame.RowCopy(0)
require.Equal(t, "span-abc123", row[2]) // Should use SpanId for span type
}
func TestCreateExemplarFrame_AllLabelsIncluded(t *testing.T) {
exemplars := []*Exemplar{
{
ProfileId: "profile-1",
SpanId: "span-1",
Value: 1.0,
Timestamp: 100,
Labels: map[string]string{
"pod": "pod-1",
"__profile_type__": "cpu",
"__name__": "process_cpu",
},
},
}
labels := map[string]string{
"service": "api",
}
frame := CreateExemplarFrame(labels, exemplars, ExemplarTypeSpan, "count")
// Verify all fields are created (including private labels)
fieldNames := []string{}
for _, field := range frame.Fields {
fieldNames = append(fieldNames, field.Name)
}
require.Contains(t, fieldNames, "Time")
require.Contains(t, fieldNames, "Value")
require.Contains(t, fieldNames, "Id")
require.Contains(t, fieldNames, "service")
require.Contains(t, fieldNames, "pod")
require.Contains(t, fieldNames, "__profile_type__")
require.Contains(t, fieldNames, "__name__")
}
func TestCreateExemplarFrame_NoDuplicateFields(t *testing.T) {
// Test that labels in both series labels and exemplar labels don't create duplicate fields
exemplars := []*Exemplar{
{
ProfileId: "profile-1",
SpanId: "span-1",
Value: 1.0,
Timestamp: 100,
Labels: map[string]string{
"pod": "exemplar-pod-123", // Different value than series label
"namespace": "prod", // This is only in exemplar labels
},
},
}
labels := map[string]string{
"service": "api",
"pod": "series-pod-456", // This is also in exemplar labels but with different value
}
frame := CreateExemplarFrame(labels, exemplars, ExemplarTypeSpan, "short")
// Count how many fields have each name
fieldCounts := make(map[string]int)
for _, field := range frame.Fields {
fieldCounts[field.Name]++
}
// Each field name should appear exactly once
require.Equal(t, 1, fieldCounts["Time"])
require.Equal(t, 1, fieldCounts["Value"])
require.Equal(t, 1, fieldCounts["Id"])
require.Equal(t, 1, fieldCounts["service"])
require.Equal(t, 1, fieldCounts["pod"], "pod field should appear exactly once, not duplicated")
require.Equal(t, 1, fieldCounts["namespace"])
// Verify the exemplar-specific pod value is used (not the series value)
rows, err := frame.RowLen()
require.NoError(t, err)
require.Equal(t, 1, rows)
podField, _ := frame.FieldByName("pod")
require.NotNil(t, podField)
require.Equal(t, "exemplar-pod-123", podField.At(0), "Should use exemplar-specific pod value, not series value")
// Verify series label is used when exemplar doesn't have the label
serviceField, _ := frame.FieldByName("service")
require.NotNil(t, serviceField)
require.Equal(t, "api", serviceField.At(0))
// Verify exemplar-only label
namespaceField, _ := frame.FieldByName("namespace")
require.NotNil(t, namespaceField)
require.Equal(t, "prod", namespaceField.At(0))
}
func TestCreateExemplarFrame_ExemplarValueTakesPrecedence(t *testing.T) {
// Test that exemplar label values take precedence over series label values
exemplars := []*Exemplar{
{
ProfileId: "profile-1",
SpanId: "span-1",
Value: 1.0,
Timestamp: 100,
Labels: map[string]string{
"pod": "pod-abc",
"node": "node-xyz",
"span_name": "my-span",
},
},
{
ProfileId: "profile-2",
SpanId: "span-2",
Value: 2.0,
Timestamp: 200,
Labels: map[string]string{
"pod": "pod-def",
"node": "node-uvw",
"span_name": "another-span",
},
},
}
labels := map[string]string{
"service": "api",
}
frame := CreateExemplarFrame(labels, exemplars, ExemplarTypeSpan, "bytes")
// Verify we have the correct number of rows
rows, err := frame.RowLen()
require.NoError(t, err)
require.Equal(t, 2, rows)
// Verify each exemplar has its own pod, node, and span_name values
podField, _ := frame.FieldByName("pod")
require.NotNil(t, podField)
require.Equal(t, "pod-abc", podField.At(0))
require.Equal(t, "pod-def", podField.At(1))
nodeField, _ := frame.FieldByName("node")
require.NotNil(t, nodeField)
require.Equal(t, "node-xyz", nodeField.At(0))
require.Equal(t, "node-uvw", nodeField.At(1))
spanNameField, _ := frame.FieldByName("span_name")
require.NotNil(t, spanNameField)
require.Equal(t, "my-span", spanNameField.At(0))
require.Equal(t, "another-span", spanNameField.At(1))
// Verify series label is the same for both
serviceField, _ := frame.FieldByName("service")
require.NotNil(t, serviceField)
require.Equal(t, "api", serviceField.At(0))
require.Equal(t, "api", serviceField.At(1))
}
@@ -0,0 +1,194 @@
package heatmap
import (
"fmt"
"sort"
"strings"
"time"
"github.com/grafana/grafana-plugin-sdk-go/data"
)
// Point represents a single heatmap point with timestamp, bucket minimums, and counts
type Point struct {
Timestamp int64
YMin []float64
Counts []int64
}
// generateFrameName creates a unique frame name from labels
// If labels are empty, returns "heatmap"
// Otherwise returns "heatmap{label1=value1,label2=value2,...}"
func generateFrameName(labels map[string]string) string {
if len(labels) == 0 {
return "heatmap"
}
// Sort label keys for consistent ordering
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys)
// Build label string
pairs := make([]string, 0, len(labels))
for _, k := range keys {
pairs = append(pairs, fmt.Sprintf("%s=%s", k, labels[k]))
}
return fmt.Sprintf("heatmap{%s}", strings.Join(pairs, ","))
}
// fillMissingTimeSlices ensures continuous time coverage by filling gaps between data points.
// This prevents visual gaps in the heatmap. Points are assumed to be in increasing timestamp order.
func fillMissingTimeSlices(points []*Point, stepSeconds float64) []*Point {
if len(points) == 0 {
return points
}
// Determine the common bucket structure (YMin values)
// Find the most complete bucket structure across all points
templateYMin := points[0].YMin
for _, point := range points {
if len(point.YMin) > len(templateYMin) {
templateYMin = point.YMin
}
}
stepMs := int64(stepSeconds * 1000)
filled := make([]*Point, 0, len(points)*2) // Estimate: assume some gaps
zeroCounts := make([]int64, len(templateYMin))
// Process first point, normalizing bucket structure if needed
firstPoint := points[0]
if len(firstPoint.YMin) < len(templateYMin) {
paddedCounts := make([]int64, len(templateYMin))
copy(paddedCounts, firstPoint.Counts)
filled = append(filled, &Point{
Timestamp: firstPoint.Timestamp,
YMin: templateYMin,
Counts: paddedCounts,
})
} else {
filled = append(filled, firstPoint)
}
// Iterate through remaining points and fill gaps as we find them
for i := 1; i < len(points); i++ {
prevTimestamp := filled[len(filled)-1].Timestamp
currTimestamp := points[i].Timestamp
// Fill any gaps between previous and current point
expectedTimestamp := prevTimestamp + stepMs
for expectedTimestamp < currTimestamp {
filled = append(filled, &Point{
Timestamp: expectedTimestamp,
YMin: templateYMin,
Counts: append([]int64(nil), zeroCounts...), // Copy to avoid sharing
})
expectedTimestamp += stepMs
}
// Add current point, normalizing bucket structure if needed
currPoint := points[i]
if len(currPoint.YMin) < len(templateYMin) {
paddedCounts := make([]int64, len(templateYMin))
copy(paddedCounts, currPoint.Counts)
filled = append(filled, &Point{
Timestamp: currTimestamp,
YMin: templateYMin,
Counts: paddedCounts,
})
} else {
filled = append(filled, currPoint)
}
}
return filled
}
// CreateHeatmapFrame converts heatmap points to a DataFrame in HeatmapCells format
// This creates a sparse representation where each cell is explicitly defined by:
// - xMax: time value (timestamp)
// - yMin: bucket minimum value
// - yMax: bucket maximum value
// - count: number of matches in that bucket
// - yLayout: bucket layout (0 for linear buckets)
//
// Parameters:
// - labels: metric labels for the heatmap series
// - points: data points in increasing timestamp order (may have gaps in time coverage)
// - units: unit string for Y-axis values
// - stepSeconds: duration of each time bucket in seconds
//
// The function ensures continuous time coverage by filling gaps between points with zero counts.
func CreateHeatmapFrame(labels map[string]string, points []*Point, units string, stepSeconds float64) *data.Frame {
frameName := generateFrameName(labels)
frame := data.NewFrame(frameName)
frame.Meta = &data.FrameMeta{
Type: "heatmap-cells",
}
// Calculate total number of cells across all points
totalCells := 0
for _, point := range points {
totalCells += len(point.Counts)
}
// Create data fields in the order expected by heatmap-cells format
// Set interval (in milliseconds) on xMax field so frontend can calculate xMin for bucket boundaries
intervalMs := int64(stepSeconds * 1000)
frame.Fields = data.Fields{
data.NewField("xMax", nil, make([]time.Time, 0, totalCells)).SetConfig(&data.FieldConfig{
Interval: float64(intervalMs),
}),
data.NewField("yMin", nil, make([]float64, 0, totalCells)).SetConfig(&data.FieldConfig{
Unit: units,
}),
data.NewField("yMax", nil, make([]float64, 0, totalCells)).SetConfig(&data.FieldConfig{
Unit: units,
}),
data.NewField("count", labels, make([]int64, 0, totalCells)),
data.NewField("yLayout", nil, make([]int8, 0, totalCells)),
}
if totalCells == 0 {
return frame
}
// Fill missing time slices and normalize bucket structures
points = fillMissingTimeSlices(points, stepSeconds)
// Populate cells: for each time point, create a cell for each bucket
for _, point := range points {
timestamp := time.UnixMilli(point.Timestamp)
for i := 0; i < len(point.Counts); i++ {
// Calculate yMax: for bucket i, yMax is yMin of bucket i+1
// For the last bucket, use a large value or calculate based on bucket width
var yMax float64
if i < len(point.YMin)-1 {
yMax = point.YMin[i+1]
} else {
// For the last bucket, calculate based on the previous bucket width
if i > 0 {
bucketWidth := point.YMin[i] - point.YMin[i-1]
yMax = point.YMin[i] + bucketWidth
} else {
// Single bucket case: use a reasonable default
yMax = point.YMin[i] * 2
}
}
frame.AppendRow(
timestamp,
point.YMin[i],
yMax,
point.Counts[i],
int8(0), // 0 indicates linear bucket layout
)
}
}
return frame
}
@@ -0,0 +1,398 @@
package heatmap
import (
"testing"
"time"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/stretchr/testify/require"
)
func TestGenerateFrameName(t *testing.T) {
t.Run("empty labels returns default name", func(t *testing.T) {
name := generateFrameName(map[string]string{})
require.Equal(t, "heatmap", name)
})
t.Run("single label", func(t *testing.T) {
name := generateFrameName(map[string]string{"service": "api"})
require.Equal(t, "heatmap{service=api}", name)
})
t.Run("multiple labels sorted", func(t *testing.T) {
name := generateFrameName(map[string]string{
"service": "api",
"env": "prod",
"region": "us-west",
})
// Labels should be sorted alphabetically
require.Equal(t, "heatmap{env=prod,region=us-west,service=api}", name)
})
}
func TestCreateHeatmapFrame(t *testing.T) {
t.Run("creates frame with correct metadata", func(t *testing.T) {
now := time.Now()
points := []*Point{
{
Timestamp: now.UnixMilli(),
YMin: []float64{0, 100, 200},
Counts: []int64{5, 10, 3},
},
}
labels := map[string]string{"service": "api"}
frame := CreateHeatmapFrame(labels, points, "ns", 15.0)
require.NotNil(t, frame)
require.Equal(t, "heatmap{service=api}", frame.Name)
require.NotNil(t, frame.Meta)
require.Equal(t, data.FrameType("heatmap-cells"), frame.Meta.Type)
})
t.Run("creates correct fields structure", func(t *testing.T) {
timestamp := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
points := []*Point{
{
Timestamp: timestamp.UnixMilli(),
YMin: []float64{0, 100, 200},
Counts: []int64{5, 10, 3},
},
}
frame := CreateHeatmapFrame(map[string]string{}, points, "ns", 15.0)
require.Len(t, frame.Fields, 5)
require.Equal(t, "xMax", frame.Fields[0].Name)
require.Equal(t, "yMin", frame.Fields[1].Name)
require.Equal(t, "yMax", frame.Fields[2].Name)
require.Equal(t, "count", frame.Fields[3].Name)
require.Equal(t, "yLayout", frame.Fields[4].Name)
})
t.Run("correctly expands multiple time points into cells", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 0, 15, 0, time.UTC) // 15 seconds later (1 step)
stepDuration := 15.0 // 15 seconds
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
frame := CreateHeatmapFrame(map[string]string{}, points, "ns", stepDuration)
// Should create 4 cells total (2 time points × 2 buckets, no gaps to fill)
require.Equal(t, 4, frame.Fields[0].Len())
require.Equal(t, 4, frame.Fields[1].Len())
require.Equal(t, 4, frame.Fields[2].Len())
require.Equal(t, 4, frame.Fields[3].Len())
require.Equal(t, 4, frame.Fields[4].Len())
// Check xMax values (timestamps) - compare Unix millis to avoid timezone issues
xMaxField := frame.Fields[0]
require.Equal(t, timestamp1.UnixMilli(), xMaxField.At(0).(time.Time).UnixMilli())
require.Equal(t, timestamp1.UnixMilli(), xMaxField.At(1).(time.Time).UnixMilli())
require.Equal(t, timestamp2.UnixMilli(), xMaxField.At(2).(time.Time).UnixMilli())
require.Equal(t, timestamp2.UnixMilli(), xMaxField.At(3).(time.Time).UnixMilli())
// Check yMin values (bucket minimums)
yMinField := frame.Fields[1]
require.Equal(t, float64(0), yMinField.At(0))
require.Equal(t, float64(100), yMinField.At(1))
require.Equal(t, float64(0), yMinField.At(2))
require.Equal(t, float64(100), yMinField.At(3))
// Check yMax values (bucket maximums)
yMaxField := frame.Fields[2]
require.Equal(t, float64(100), yMaxField.At(0)) // yMax for bucket [0-100)
require.Equal(t, float64(200), yMaxField.At(1)) // yMax for bucket [100-200)
require.Equal(t, float64(100), yMaxField.At(2)) // yMax for bucket [0-100)
require.Equal(t, float64(200), yMaxField.At(3)) // yMax for bucket [100-200)
// Check count values
countField := frame.Fields[3]
require.Equal(t, int64(5), countField.At(0))
require.Equal(t, int64(10), countField.At(1))
require.Equal(t, int64(7), countField.At(2))
require.Equal(t, int64(12), countField.At(3))
// Check yLayout values (should all be 0 for linear)
yLayoutField := frame.Fields[4]
require.Equal(t, int8(0), yLayoutField.At(0))
require.Equal(t, int8(0), yLayoutField.At(1))
require.Equal(t, int8(0), yLayoutField.At(2))
require.Equal(t, int8(0), yLayoutField.At(3))
})
t.Run("attaches labels to count field", func(t *testing.T) {
now := time.Now()
points := []*Point{
{
Timestamp: now.UnixMilli(),
YMin: []float64{0},
Counts: []int64{5},
},
}
labels := map[string]string{"service": "api", "env": "prod"}
frame := CreateHeatmapFrame(labels, points, "ns", 15.0)
countField := frame.Fields[3]
require.NotNil(t, countField.Labels)
require.Equal(t, "api", countField.Labels["service"])
require.Equal(t, "prod", countField.Labels["env"])
})
t.Run("creates unique frame name based on labels", func(t *testing.T) {
now := time.Now()
points := []*Point{
{
Timestamp: now.UnixMilli(),
YMin: []float64{0},
Counts: []int64{5},
},
}
labels := map[string]string{"service": "api", "env": "prod"}
frame := CreateHeatmapFrame(labels, points, "ns", 15.0)
// Frame name should include labels in sorted order
require.Equal(t, "heatmap{env=prod,service=api}", frame.Name)
})
t.Run("sets unit on yMin and yMax fields", func(t *testing.T) {
now := time.Now()
points := []*Point{
{
Timestamp: now.UnixMilli(),
YMin: []float64{0},
Counts: []int64{5},
},
}
frame := CreateHeatmapFrame(map[string]string{}, points, "ns", 15.0)
// yMin field should have units
yMinField := frame.Fields[1]
require.NotNil(t, yMinField.Config)
require.Equal(t, "ns", yMinField.Config.Unit)
// yMax field should have units
yMaxField := frame.Fields[2]
require.NotNil(t, yMaxField.Config)
require.Equal(t, "ns", yMaxField.Config.Unit)
// count field should NOT have units (or have empty unit)
countField := frame.Fields[3]
if countField.Config != nil {
require.Empty(t, countField.Config.Unit)
}
})
t.Run("handles empty points", func(t *testing.T) {
frame := CreateHeatmapFrame(map[string]string{}, []*Point{}, "ns", 15.0)
require.NotNil(t, frame)
require.Len(t, frame.Fields, 5)
require.Equal(t, 0, frame.Fields[0].Len())
require.Equal(t, 0, frame.Fields[1].Len())
require.Equal(t, 0, frame.Fields[2].Len())
require.Equal(t, 0, frame.Fields[3].Len())
require.Equal(t, 0, frame.Fields[4].Len())
})
t.Run("handles varying bucket counts per time point", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 0, 15, 0, time.UTC) // 15 seconds later (1 step)
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100, 200},
Counts: []int64{5, 10, 3},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
frame := CreateHeatmapFrame(map[string]string{}, points, "ns", 15.0)
// Should use the most complete bucket structure (3 buckets from first point)
// 2 time points × 3 buckets = 6 cells
require.Equal(t, 6, frame.Fields[0].Len())
})
t.Run("fills missing time slices with zero counts", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 0, 45, 0, time.UTC) // 45 seconds later (3 steps of 15s)
stepDuration := 15.0 // 15 seconds
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
frame := CreateHeatmapFrame(map[string]string{}, points, "ns", stepDuration)
// Should fill gaps: original 2 points + 2 gap points = 4 points
// Each point has 2 buckets, so 4 * 2 = 8 cells total
require.Equal(t, 8, frame.Fields[0].Len())
// Check timestamps are continuous
xMaxField := frame.Fields[0]
expectedTimestamps := []int64{
timestamp1.UnixMilli(), // Original point
timestamp1.Add(15 * time.Second).UnixMilli(), // Gap fill
timestamp1.Add(30 * time.Second).UnixMilli(), // Gap fill
timestamp2.UnixMilli(), // Original point
}
for i, expected := range expectedTimestamps {
// Each timestamp should appear twice (once per bucket)
require.Equal(t, expected, xMaxField.At(i*2).(time.Time).UnixMilli())
require.Equal(t, expected, xMaxField.At(i*2+1).(time.Time).UnixMilli())
}
// Check that gap-filled cells have zero counts
countField := frame.Fields[3]
require.Equal(t, int64(5), countField.At(0)) // Original
require.Equal(t, int64(10), countField.At(1)) // Original
require.Equal(t, int64(0), countField.At(2)) // Gap fill
require.Equal(t, int64(0), countField.At(3)) // Gap fill
require.Equal(t, int64(0), countField.At(4)) // Gap fill
require.Equal(t, int64(0), countField.At(5)) // Gap fill
require.Equal(t, int64(7), countField.At(6)) // Original
require.Equal(t, int64(12), countField.At(7)) // Original
})
}
func TestFillMissingTimeSlices(t *testing.T) {
t.Run("no gaps returns original points", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 0, 15, 0, time.UTC)
stepDuration := 15.0
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
filled := fillMissingTimeSlices(points, stepDuration)
require.Len(t, filled, 2)
require.Equal(t, timestamp1.UnixMilli(), filled[0].Timestamp)
require.Equal(t, timestamp2.UnixMilli(), filled[1].Timestamp)
})
t.Run("fills single gap", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 0, 30, 0, time.UTC) // 2 steps later
stepDuration := 15.0
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
filled := fillMissingTimeSlices(points, stepDuration)
require.Len(t, filled, 3)
require.Equal(t, timestamp1.UnixMilli(), filled[0].Timestamp)
require.Equal(t, timestamp1.Add(15*time.Second).UnixMilli(), filled[1].Timestamp)
require.Equal(t, timestamp2.UnixMilli(), filled[2].Timestamp)
// Check gap point has zero counts
require.Equal(t, []int64{0, 0}, filled[1].Counts)
require.Equal(t, []float64{0, 100}, filled[1].YMin)
})
t.Run("fills multiple gaps", func(t *testing.T) {
timestamp1 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
timestamp2 := time.Date(2024, 1, 1, 0, 1, 0, 0, time.UTC) // 4 steps later
stepDuration := 15.0
points := []*Point{
{
Timestamp: timestamp1.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
{
Timestamp: timestamp2.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{7, 12},
},
}
filled := fillMissingTimeSlices(points, stepDuration)
require.Len(t, filled, 5)
require.Equal(t, timestamp1.UnixMilli(), filled[0].Timestamp)
require.Equal(t, timestamp1.Add(15*time.Second).UnixMilli(), filled[1].Timestamp)
require.Equal(t, timestamp1.Add(30*time.Second).UnixMilli(), filled[2].Timestamp)
require.Equal(t, timestamp1.Add(45*time.Second).UnixMilli(), filled[3].Timestamp)
require.Equal(t, timestamp2.UnixMilli(), filled[4].Timestamp)
// Check all gap points have zero counts
for i := 1; i <= 3; i++ {
require.Equal(t, []int64{0, 0}, filled[i].Counts)
}
})
t.Run("handles empty points", func(t *testing.T) {
filled := fillMissingTimeSlices([]*Point{}, 15.0)
require.Len(t, filled, 0)
})
t.Run("handles single point", func(t *testing.T) {
timestamp := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
points := []*Point{
{
Timestamp: timestamp.UnixMilli(),
YMin: []float64{0, 100},
Counts: []int64{5, 10},
},
}
filled := fillMissingTimeSlices(points, 15.0)
require.Len(t, filled, 1)
require.Equal(t, timestamp.UnixMilli(), filled[0].Timestamp)
})
}
@@ -19,6 +19,7 @@ import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
querierv1 "github.com/grafana/pyroscope/api/gen/proto/go/querier/v1"
typesv1 "github.com/grafana/pyroscope/api/gen/proto/go/types/v1"
)
@@ -36,6 +37,7 @@ type ProfilingClient interface {
GetSeries(ctx context.Context, profileTypeID string, labelSelector string, start int64, end int64, groupBy []string, limit *int64, step float64, exemplarType typesv1.ExemplarType) (*SeriesResponse, error)
GetProfile(ctx context.Context, profileTypeID string, labelSelector string, start int64, end int64, maxNodes *int64) (*ProfileResponse, error)
GetSpanProfile(ctx context.Context, profileTypeID string, labelSelector string, spanSelector []string, start int64, end int64, maxNodes *int64) (*ProfileResponse, error)
GetHeatmap(ctx context.Context, profileTypeID string, labelSelector string, start int64, end int64, groupBy []string, step float64, queryType querierv1.HeatmapQueryType, limit *int64, includeExemplars bool) (*HeatmapResponse, error)
}
// PyroscopeDatasource is a datasource for querying application performance profiles.
@@ -19,6 +19,13 @@ const (
PyroscopeQueryTypeBoth PyroscopeQueryType = "both"
)
type HeatmapQueryType string
const (
HeatmapQueryTypeIndividual HeatmapQueryType = "individual"
HeatmapQueryTypeSpan HeatmapQueryType = "span"
)
type GrafanaPyroscopeDataQuery struct {
// Specifies the query label selectors.
LabelSelector string `json:"labelSelector"`
@@ -34,6 +41,12 @@ type GrafanaPyroscopeDataQuery struct {
MaxNodes *int64 `json:"maxNodes,omitempty"`
// If set to true, the response will contain annotations
Annotations *bool `json:"annotations,omitempty"`
// If set to true, exemplars will be requested
IncludeExemplars bool `json:"includeExemplars"`
// If set to true, heatmap data will be requested
IncludeHeatmap bool `json:"includeHeatmap"`
// Specifies the type of heatmap query
HeatmapType string `json:"heatmapType"`
// A unique identifier for the query within the list of targets.
// In server side expressions, the refId is used as a variable name to identify results.
// By default, the UI will assign A->Z; however setting meaningful names may be useful.
@@ -43,8 +56,6 @@ type GrafanaPyroscopeDataQuery struct {
// Specify the query flavor
// TODO make this required and give it a default
QueryType *string `json:"queryType,omitempty"`
// If set to true, exemplars will be requested
IncludeExemplars bool `json:"includeExemplars"`
// For mixed data sources the selected datasource is on the query level.
// For non mixed scenarios this is undefined.
// TODO find a better way to do this ^ that's friendly to schema
@@ -58,5 +69,7 @@ func NewGrafanaPyroscopeDataQuery() *GrafanaPyroscopeDataQuery {
LabelSelector: "{}",
GroupBy: []string{},
IncludeExemplars: false,
IncludeHeatmap: false,
HeatmapType: "individual",
}
}
@@ -55,9 +55,11 @@ type Point struct {
}
type Exemplar struct {
Id string
ProfileId string
SpanId string
Value uint64
Timestamp int64
Labels []*LabelPair
}
type ProfileResponse struct {
@@ -71,6 +73,23 @@ type SeriesResponse struct {
Label string
}
type HeatmapPoint struct {
Timestamp int64
YMin []float64
Counts []int64
Exemplars []*Exemplar
}
type HeatmapSeries struct {
Labels []*LabelPair
Points []*HeatmapPoint
}
type HeatmapResponse struct {
Series []*HeatmapSeries
Units string
}
type PyroscopeClient struct {
connectClient querierv1connect.QuerierServiceClient
}
@@ -150,10 +169,20 @@ func (c *PyroscopeClient) GetSeries(ctx context.Context, profileTypeID string, l
if len(p.Exemplars) > 0 {
points[i].Exemplars = make([]*Exemplar, len(p.Exemplars))
for j, e := range p.Exemplars {
// Convert API labels to our LabelPair type
exemplarLabels := make([]*LabelPair, len(e.Labels))
for k, l := range e.Labels {
exemplarLabels[k] = &LabelPair{
Name: l.Name,
Value: l.Value,
}
}
points[i].Exemplars[j] = &Exemplar{
Id: e.ProfileId,
ProfileId: e.ProfileId,
SpanId: e.SpanId,
Value: e.Value,
Timestamp: e.Timestamp,
Labels: exemplarLabels,
}
}
}
@@ -174,6 +203,98 @@ func (c *PyroscopeClient) GetSeries(ctx context.Context, profileTypeID string, l
}, nil
}
func (c *PyroscopeClient) GetHeatmap(ctx context.Context, profileTypeID string, labelSelector string, start int64, end int64, groupBy []string, step float64, queryType querierv1.HeatmapQueryType, limit *int64, includeExemplars bool) (*HeatmapResponse, error) {
ctx, span := tracing.DefaultTracer().Start(ctx, "datasource.pyroscope.GetHeatmap", trace.WithAttributes(attribute.String("profileTypeID", profileTypeID), attribute.String("labelSelector", labelSelector)))
defer span.End()
// Determine exemplar type based on includeExemplars flag and query type
exemplarType := typesv1.ExemplarType_EXEMPLAR_TYPE_NONE
if includeExemplars {
switch queryType {
case querierv1.HeatmapQueryType_HEATMAP_QUERY_TYPE_SPAN:
exemplarType = typesv1.ExemplarType_EXEMPLAR_TYPE_SPAN
case querierv1.HeatmapQueryType_HEATMAP_QUERY_TYPE_INDIVIDUAL:
exemplarType = typesv1.ExemplarType_EXEMPLAR_TYPE_INDIVIDUAL
}
}
req := connect.NewRequest(&querierv1.SelectHeatmapRequest{
ProfileTypeID: profileTypeID,
LabelSelector: labelSelector,
Start: start,
End: end,
Step: step,
GroupBy: groupBy,
QueryType: queryType,
Limit: limit,
ExemplarType: exemplarType,
})
resp, err := c.connectClient.SelectHeatmap(ctx, req)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, backend.DownstreamErrorf("received error from client while getting heatmap: %w", err)
}
series := make([]*HeatmapSeries, len(resp.Msg.Series))
for i, s := range resp.Msg.Series {
labels := make([]*LabelPair, len(s.Labels))
for j, l := range s.Labels {
labels[j] = &LabelPair{
Name: l.Name,
Value: l.Value,
}
}
points := make([]*HeatmapPoint, len(s.Slots))
for j, slot := range s.Slots {
// Convert []int32 to []int64
counts := make([]int64, len(slot.Counts))
for k, c := range slot.Counts {
counts[k] = int64(c)
}
// Process exemplars if present
exemplars := make([]*Exemplar, len(slot.Exemplars))
for k, e := range slot.Exemplars {
// Convert API labels to our LabelPair type
exemplarLabels := make([]*LabelPair, len(e.Labels))
for i, l := range e.Labels {
exemplarLabels[i] = &LabelPair{
Name: l.Name,
Value: l.Value,
}
}
exemplars[k] = &Exemplar{
ProfileId: e.ProfileId,
SpanId: e.SpanId,
Value: e.Value,
Timestamp: e.Timestamp,
Labels: exemplarLabels,
}
}
points[j] = &HeatmapPoint{
Timestamp: slot.Timestamp,
YMin: slot.YMin,
Counts: counts,
Exemplars: exemplars,
}
}
series[i] = &HeatmapSeries{
Labels: labels,
Points: points,
}
}
return &HeatmapResponse{
Series: series,
Units: getUnits(profileTypeID),
}, nil
}
func (c *PyroscopeClient) GetProfile(ctx context.Context, profileTypeID, labelSelector string, start, end int64, maxNodes *int64) (*ProfileResponse, error) {
ctx, span := tracing.DefaultTracer().Start(ctx, "datasource.pyroscope.GetProfile", trace.WithAttributes(attribute.String("profileTypeID", profileTypeID), attribute.String("labelSelector", labelSelector)))
defer span.End()
@@ -40,7 +40,7 @@ func Test_PyroscopeClient(t *testing.T) {
series := &SeriesResponse{
Series: []*Series{
{Labels: []*LabelPair{{Name: "foo", Value: "bar"}}, Points: []*Point{{Timestamp: int64(1000), Value: 30, Exemplars: []*Exemplar{{Id: "id1", Value: 3, Timestamp: 1000}}}, {Timestamp: int64(2000), Value: 10, Exemplars: []*Exemplar{{Id: "id2", Value: 1, Timestamp: 2000}}}}},
{Labels: []*LabelPair{{Name: "foo", Value: "bar"}}, Points: []*Point{{Timestamp: int64(1000), Value: 30, Exemplars: []*Exemplar{{ProfileId: "id1", SpanId: "", Value: 3, Timestamp: 1000, Labels: []*LabelPair{}}}}, {Timestamp: int64(2000), Value: 10, Exemplars: []*Exemplar{{ProfileId: "id2", SpanId: "", Value: 1, Timestamp: 2000, Labels: []*LabelPair{}}}}}},
},
Units: "short",
Label: "alloc_objects",
@@ -158,6 +158,22 @@ func (f *FakePyroscopeConnectClient) SelectSeries(ctx context.Context, req *conn
}, nil
}
func (f *FakePyroscopeConnectClient) SelectHeatmap(ctx context.Context, req *connect.Request[querierv1.SelectHeatmapRequest]) (*connect.Response[querierv1.SelectHeatmapResponse], error) {
f.Req = req
return &connect.Response[querierv1.SelectHeatmapResponse]{
Msg: &querierv1.SelectHeatmapResponse{
Series: []*typesv1.HeatmapSeries{
{
Labels: []*typesv1.LabelPair{{Name: "foo", Value: "bar"}},
Slots: []*typesv1.HeatmapSlot{
{Timestamp: int64(1000), YMin: []float64{0, 100, 200}, Counts: []int32{5, 10, 3}},
},
},
},
},
}, nil
}
func (f *FakePyroscopeConnectClient) SelectMergeProfile(ctx context.Context, c *connect.Request[querierv1.SelectMergeProfileRequest]) (*connect.Response[googlev1.Profile], error) {
panic("implement me")
}
+97 -3
View File
@@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana-plugin-sdk-go/live"
"github.com/grafana/grafana/pkg/tsdb/grafana-pyroscope-datasource/exemplar"
"github.com/grafana/grafana/pkg/tsdb/grafana-pyroscope-datasource/heatmap"
"github.com/xlab/treeprint"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
@@ -23,6 +24,7 @@ import (
"github.com/grafana/grafana/pkg/tsdb/grafana-pyroscope-datasource/annotation"
"github.com/grafana/grafana/pkg/tsdb/grafana-pyroscope-datasource/kinds/dataquery"
querierv1 "github.com/grafana/pyroscope/api/gen/proto/go/querier/v1"
typesv1 "github.com/grafana/pyroscope/api/gen/proto/go/types/v1"
)
@@ -41,6 +43,7 @@ const (
queryTypeBoth = string(dataquery.PyroscopeQueryTypeBoth)
exemplarsFeatureToggle = "profilesExemplars"
heatmapFeatureToggle = "profilesHeatmap"
)
var identityTransformation = func(value float64) float64 { return value }
@@ -84,6 +87,88 @@ func (d *PyroscopeDatasource) query(ctx context.Context, pCtx backend.PluginCont
logger.Error("Failed to parse the MinStep using default", "MinStep", dsJson.MinStep, "function", logEntrypoint())
}
}
// Heatmap handling
if qm.IncludeHeatmap && backend.GrafanaConfigFromContext(ctx).FeatureToggles().IsEnabled(heatmapFeatureToggle) {
heatmapType := querierv1.HeatmapQueryType_HEATMAP_QUERY_TYPE_INDIVIDUAL
if qm.HeatmapType == "span" {
heatmapType = querierv1.HeatmapQueryType_HEATMAP_QUERY_TYPE_SPAN
}
// Check if exemplars should be included
includeExemplars := qm.IncludeExemplars && backend.GrafanaConfigFromContext(ctx).FeatureToggles().IsEnabled(exemplarsFeatureToggle)
stepDuration := math.Max(query.Interval.Seconds(), parsedInterval.Seconds())
heatmapResp, err := d.client.GetHeatmap(
gCtx,
profileTypeId,
labelSelector,
query.TimeRange.From.UnixMilli(),
query.TimeRange.To.UnixMilli(),
qm.GroupBy,
stepDuration,
heatmapType,
qm.Limit,
includeExemplars,
)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
logger.Error("Querying SelectHeatmap()", "err", err, "function", logEntrypoint())
return err
}
responseMutex.Lock()
defer responseMutex.Unlock()
// Determine exemplar type based on heatmap type
exemplarType := exemplar.ExemplarTypeProfile
if heatmapType == querierv1.HeatmapQueryType_HEATMAP_QUERY_TYPE_SPAN {
exemplarType = exemplar.ExemplarTypeSpan
}
for _, series := range heatmapResp.Series {
labels := make(map[string]string)
for _, label := range series.Labels {
labels[label.Name] = label.Value
}
// Convert HeatmapPoint to heatmap.Point and collect exemplars
points := make([]*heatmap.Point, len(series.Points))
exemplars := []*exemplar.Exemplar{}
for i, p := range series.Points {
points[i] = &heatmap.Point{
Timestamp: p.Timestamp,
YMin: p.YMin,
Counts: p.Counts,
}
// Collect exemplars from this point
for _, e := range p.Exemplars {
// Convert exemplar labels from slice to map
exemplarLabels := make(map[string]string)
for _, l := range e.Labels {
exemplarLabels[l.Name] = l.Value
}
exemplars = append(exemplars, &exemplar.Exemplar{
ProfileId: e.ProfileId,
SpanId: e.SpanId,
Value: float64(e.Value),
Timestamp: e.Timestamp,
Labels: exemplarLabels,
})
}
}
heatmapFrame := heatmap.CreateHeatmapFrame(labels, points, heatmapResp.Units, stepDuration)
response.Frames = append(response.Frames, heatmapFrame)
// Create exemplar frame if we have exemplars
if len(exemplars) > 0 {
exemplarFrame := exemplar.CreateExemplarFrame(labels, exemplars, exemplarType, heatmapResp.Units)
response.Frames = append(response.Frames, exemplarFrame)
}
}
return nil
}
exemplarType := typesv1.ExemplarType_EXEMPLAR_TYPE_NONE
if qm.IncludeExemplars && backend.GrafanaConfigFromContext(ctx).FeatureToggles().IsEnabled(exemplarsFeatureToggle) {
exemplarType = typesv1.ExemplarType_EXEMPLAR_TYPE_INDIVIDUAL
@@ -107,6 +192,7 @@ func (d *PyroscopeDatasource) query(ctx context.Context, pCtx backend.PluginCont
}
// add the frames to the response.
responseMutex.Lock()
defer responseMutex.Unlock()
withAnnotations := qm.Annotations != nil && *qm.Annotations
stepDuration := math.Max(query.Interval.Seconds(), parsedInterval.Seconds())
frames, err := seriesToDataFrames(seriesResp, withAnnotations, stepDuration, profileTypeId)
@@ -117,7 +203,7 @@ func (d *PyroscopeDatasource) query(ctx context.Context, pCtx backend.PluginCont
return err
}
response.Frames = append(response.Frames, frames...)
responseMutex.Unlock()
return nil
})
}
@@ -553,10 +639,17 @@ func seriesToDataFrames(resp *SeriesResponse, withAnnotations bool, stepDuration
}
}
for _, e := range point.Exemplars {
// Convert exemplar labels from slice to map
exemplarLabels := make(map[string]string)
for _, l := range e.Labels {
exemplarLabels[l.Name] = l.Value
}
exemplars = append(exemplars, &exemplar.Exemplar{
Id: e.Id,
ProfileId: e.ProfileId,
SpanId: e.SpanId,
Value: transformation(float64(e.Value)),
Timestamp: e.Timestamp,
Labels: exemplarLabels,
})
}
}
@@ -565,7 +658,8 @@ func seriesToDataFrames(resp *SeriesResponse, withAnnotations bool, stepDuration
frames = append(frames, frame)
if len(exemplars) > 0 {
frame := exemplar.CreateExemplarFrame(labels, exemplars)
// Series queries always use individual profiles
frame := exemplar.CreateExemplarFrame(labels, exemplars, exemplar.ExemplarTypeProfile, displayUnit)
frames = append(frames, frame)
}
}
@@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
querierv1 "github.com/grafana/pyroscope/api/gen/proto/go/querier/v1"
typesv1 "github.com/grafana/pyroscope/api/gen/proto/go/types/v1"
"github.com/grafana/grafana/pkg/tsdb/grafana-pyroscope-datasource/annotation"
@@ -660,3 +661,17 @@ func (f *FakeClient) GetSeries(ctx context.Context, profileTypeID, labelSelector
Label: "test",
}, nil
}
func (f *FakeClient) GetHeatmap(ctx context.Context, profileTypeID, labelSelector string, start, end int64, groupBy []string, step float64, queryType querierv1.HeatmapQueryType, limit *int64, includeExemplars bool) (*HeatmapResponse, error) {
return &HeatmapResponse{
Series: []*HeatmapSeries{
{
Labels: []*LabelPair{{Name: "foo", Value: "bar"}},
Points: []*HeatmapPoint{
{Timestamp: start, YMin: []float64{0, 100, 200}, Counts: []int64{5, 10, 3}},
},
},
},
Units: "nanoseconds",
}, nil
}
@@ -1108,7 +1108,12 @@ export class ElementState implements LayerElement {
tabIndex={0}
style={{ userSelect: 'none' }}
>
<item.display key={this.UID} config={this.options.config} data={this.data} isSelected={isSelected} />
<item.display
key={`${this.UID}/${this.revId}`}
config={this.options.config}
data={this.data}
isSelected={isSelected}
/>
</div>
{this.showActionConfirmation && this.renderActionsConfirmModal(this.getPrimaryAction())}
{this.showActionVarsModal && this.renderVariablesInputModal(this.getPrimaryAction())}
@@ -95,6 +95,7 @@ const dummyProps: Props = {
showCustom: true,
showNodeGraph: true,
showFlameGraph: true,
showHeatmap: false,
splitOpen: jest.fn(),
splitted: false,
eventBus: new EventBusSrv(),
+31
View File
@@ -45,6 +45,7 @@ import { CustomContainer } from './CustomContainer';
import { ExploreToolbar } from './ExploreToolbar';
import { FlameGraphExploreContainer } from './FlameGraph/FlameGraphExploreContainer';
import { GraphContainer } from './Graph/GraphContainer';
import { HeatmapContainer } from './Heatmap/HeatmapContainer';
import LogsContainer from './Logs/LogsContainer';
import { LogsSamplePanel } from './Logs/LogsSamplePanel';
import { NoData } from './NoData';
@@ -409,6 +410,27 @@ export class Explore extends PureComponent<Props, ExploreState> {
);
}
renderHeatmapPanel(width: number) {
const { queryResponse, timeZone } = this.props;
return (
<ContentOutlineItem panelId="Heatmap" title={t('explore.explore.title-heatmap', 'Heatmap')} icon="fire">
<HeatmapContainer
data={queryResponse.heatmapFrames}
annotations={queryResponse.annotations}
height={400}
width={width}
timeRange={queryResponse.timeRange}
timeZone={timeZone}
onChangeTime={this.onUpdateTimeRange}
splitOpenFn={this.onSplitOpen('heatmap')}
loadingState={queryResponse.state}
eventBus={this.graphEventBus}
/>
</ContentOutlineItem>
);
}
renderTablePanel(width: number) {
const { exploreId, timeZone, eventBus } = this.props;
return (
@@ -587,6 +609,7 @@ export class Explore extends PureComponent<Props, ExploreState> {
showTrace,
showCustom,
showNodeGraph,
showHeatmap,
showFlameGraph,
showLogsSample,
correlationEditorDetails,
@@ -611,6 +634,7 @@ export class Explore extends PureComponent<Props, ExploreState> {
queryResponse.rawPrometheusFrames,
queryResponse.traceFrames,
queryResponse.customFrames,
queryResponse.heatmapFrames,
].every((e) => e.length === 0);
let correlationsBox = undefined;
@@ -721,6 +745,11 @@ export class Explore extends PureComponent<Props, ExploreState> {
{this.renderGraphPanel(width)}
</ErrorBoundaryAlert>
)}
{showHeatmap && (
<ErrorBoundaryAlert boundaryName="explore-heatmap-panel">
{this.renderHeatmapPanel(width)}
</ErrorBoundaryAlert>
)}
{showRawPrometheus && (
<ErrorBoundaryAlert boundaryName="explore-raw-prometheus">
{this.renderRawPrometheus(width)}
@@ -808,6 +837,7 @@ function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
queryResponse,
showNodeGraph,
showFlameGraph,
showHeatmap,
showRawPrometheus,
supplementaryQueries,
correlationEditorHelperData,
@@ -836,6 +866,7 @@ function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
showTrace,
showCustom,
showNodeGraph,
showHeatmap,
showRawPrometheus,
showFlameGraph,
splitted: isSplit(state),
@@ -62,6 +62,7 @@ const setup = (propOverrides = {}) => {
customFrames: [],
nodeGraphFrames: [],
flameGraphFrames: [],
heatmapFrames: [],
rawPrometheusFrames: [],
graphResult: null,
logsResult: null,
@@ -0,0 +1,73 @@
import {
AbsoluteTimeRange,
DataFrame,
EventBus,
LoadingState,
SplitOpen,
TimeRange,
TimeZone,
} from '@grafana/data';
import { t } from '@grafana/i18n';
import { PanelChrome, PanelChromeProps } from '@grafana/ui';
import { HeatmapExploreContainer } from './HeatmapExploreContainer';
// Fixed height for each heatmap panel
const HEATMAP_HEIGHT = 400;
interface Props extends Pick<PanelChromeProps, 'statusMessage'> {
width: number;
height: number;
data: DataFrame[];
annotations?: DataFrame[];
eventBus: EventBus;
timeRange: TimeRange;
timeZone: TimeZone;
onChangeTime: (absoluteRange: AbsoluteTimeRange) => void;
splitOpenFn: SplitOpen;
loadingState: LoadingState;
}
export const HeatmapContainer = ({
data,
annotations,
eventBus,
width,
timeRange,
timeZone,
onChangeTime,
splitOpenFn,
loadingState,
statusMessage,
}: Props) => {
// Backend already respects query limit parameter, so render all frames
return (
<>
{data.map((frame, index) => (
<PanelChrome
key={frame.name || `heatmap-${index}`}
title={frame.name || t('heatmap.container.title', 'Heatmap')}
width={width}
height={HEATMAP_HEIGHT}
loadingState={loadingState}
statusMessage={statusMessage}
>
{(innerWidth, innerHeight) => (
<HeatmapExploreContainer
data={[frame]}
annotations={annotations}
height={innerHeight}
width={innerWidth}
timeRange={timeRange}
timeZone={timeZone}
onChangeTime={onChangeTime}
splitOpenFn={splitOpenFn}
loadingState={loadingState}
eventBus={eventBus}
/>
)}
</PanelChrome>
))}
</>
);
};
@@ -0,0 +1,91 @@
import { createContext, useMemo } from 'react';
import {
AbsoluteTimeRange,
DataFrame,
DataLinksContext,
EventBus,
LoadingState,
SplitOpen,
TimeRange,
TimeZone,
} from '@grafana/data';
import { PanelRenderer } from '@grafana/runtime';
import { TooltipDisplayMode } from '@grafana/schema';
import { useExploreDataLinkPostProcessor } from '../hooks/useExploreDataLinkPostProcessor';
// Context to provide splitOpen function to components that need to manually construct explore links
export const ExploreSplitOpenContext = createContext<{ splitOpen?: SplitOpen; timeRange?: TimeRange }>({});
interface Props {
data: DataFrame[];
annotations?: DataFrame[];
height: number;
width: number;
timeRange: TimeRange;
timeZone: TimeZone;
loadingState: LoadingState;
splitOpenFn: SplitOpen;
onChangeTime?: (timeRange: AbsoluteTimeRange) => void;
eventBus: EventBus;
}
export function HeatmapExploreContainer({
data,
annotations,
height,
width,
timeZone,
timeRange,
onChangeTime,
loadingState,
splitOpenFn,
eventBus,
}: Props) {
const dataLinkPostProcessor = useExploreDataLinkPostProcessor(splitOpenFn, timeRange);
const panelOptions = useMemo(
() => ({
calculate: false, // Data already in heatmap-cells format
color: {
scheme: 'Spectral',
steps: 64,
},
tooltip: {
mode: TooltipDisplayMode.Single,
yHistogram: true,
showColorScale: true,
},
legend: {
show: true,
},
exemplars: {
color: 'rgba(31, 120, 193, 0.7)', // Standard Grafana blue to match graph series
},
}),
[]
);
return (
<DataLinksContext.Provider value={{ dataLinkPostProcessor }}>
<ExploreSplitOpenContext.Provider value={{ splitOpen: splitOpenFn, timeRange }}>
<PanelRenderer
data={{
series: data,
annotations,
timeRange,
state: loadingState,
}}
pluginId="heatmap"
title=""
width={width}
height={height}
onChangeTimeRange={onChangeTime}
timeZone={timeZone}
options={panelOptions}
/>
</ExploreSplitOpenContext.Provider>
</DataLinksContext.Provider>
);
}
@@ -133,6 +133,8 @@ export default function SpanFlameGraph(props: SpanFlameGraphProps) {
uid: profilesDataSourceSettings.uid,
},
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual' as const,
},
],
};
@@ -100,6 +100,7 @@ function createEmptyQueryResponse(): ExplorePanelData {
traceFrames: [],
nodeGraphFrames: [],
flameGraphFrames: [],
heatmapFrames: [],
customFrames: [],
tableFrames: [],
rawPrometheusFrames: [],
@@ -25,6 +25,7 @@ export const mockExplorePanelData = (props?: MockProps): Observable<ExplorePanel
nodeGraphFrames: [],
rawPrometheusFrames: [],
rawPrometheusResult: null,
heatmapFrames: [],
series: [],
state: LoadingState.Done,
tableFrames: [],
@@ -1324,6 +1324,7 @@ const processQueryResponse = (state: ExploreItemState, action: PayloadAction<Que
flameGraphFrames,
rawPrometheusFrames,
customFrames,
heatmapFrames,
} = response;
if (error) {
@@ -1353,6 +1354,7 @@ const processQueryResponse = (state: ExploreItemState, action: PayloadAction<Que
showNodeGraph: !!nodeGraphFrames.length,
showRawPrometheus: !!rawPrometheusFrames.length,
showFlameGraph: !!flameGraphFrames.length,
showHeatmap: !!heatmapFrames.length,
showCustom: !!customFrames?.length,
clearedAtIndex: state.isLive ? state.clearedAtIndex : null,
};
@@ -88,6 +88,7 @@ export const createEmptyQueryResponse = (): ExplorePanelData => ({
traceFrames: [],
nodeGraphFrames: [],
flameGraphFrames: [],
heatmapFrames: [],
customFrames: [],
tableFrames: [],
rawPrometheusFrames: [],
@@ -108,6 +108,7 @@ const createExplorePanelData = (args: Partial<ExplorePanelData>): ExplorePanelDa
nodeGraphFrames: [],
customFrames: [],
flameGraphFrames: [],
heatmapFrames: [],
rawPrometheusFrames: [],
rawPrometheusResult: null,
};
@@ -37,6 +37,7 @@ export const decorateWithFrameTypeMetadata = (data: PanelData): ExplorePanelData
const traceFrames: DataFrame[] = [];
const nodeGraphFrames: DataFrame[] = [];
const flameGraphFrames: DataFrame[] = [];
const heatmapFrames: DataFrame[] = [];
const customFrames: DataFrame[] = [];
for (const frame of data.series) {
@@ -44,6 +45,13 @@ export const decorateWithFrameTypeMetadata = (data: PanelData): ExplorePanelData
customFrames.push(frame);
continue;
}
// Check for heatmap-cells type BEFORE the switch statement
if (frame.meta?.type === 'heatmap-cells') {
heatmapFrames.push(frame);
continue;
}
switch (frame.meta?.preferredVisualisationType) {
case 'logs':
logsFrames.push(frame);
@@ -87,6 +95,7 @@ export const decorateWithFrameTypeMetadata = (data: PanelData): ExplorePanelData
customFrames,
flameGraphFrames,
rawPrometheusFrames,
heatmapFrames,
graphResult: null,
tableResult: null,
logsResult: null,
@@ -34,6 +34,8 @@ describe('QueryEditor', () => {
maxNodes: 1000,
groupBy: [],
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
},
},
});
@@ -127,6 +129,8 @@ function setup(options: { props: Partial<Props> } = { props: {} }) {
groupBy: [],
limit: 42,
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
}}
datasource={setupDs()}
onChange={onChange}
@@ -5,6 +5,7 @@ import { CoreApp, GrafanaTheme2, SelectableValue } from '@grafana/data';
import { config } from '@grafana/runtime';
import { useStyles2, RadioButtonGroup, MultiSelect, Input, InlineSwitch } from '@grafana/ui';
import { HeatmapQueryType } from '../dataquery.gen';
import { Query } from '../types';
import { EditorField } from './EditorField';
@@ -60,6 +61,9 @@ export function QueryOptions({ query, onQueryChange, app, labels }: Props) {
if (query.includeExemplars) {
collapsedInfo.push(`With exemplars`);
}
if (query.includeHeatmap) {
collapsedInfo.push(`Heatmap: ${query.heatmapType || 'individual'}`);
}
return (
<Stack gap={0} direction="column">
@@ -156,6 +160,30 @@ export function QueryOptions({ query, onQueryChange, app, labels }: Props) {
/>
</EditorField>
)}
{config.featureToggles.profilesHeatmap && (
<>
<EditorField label={'Heatmap'} tooltip={<>Include heatmap visualization of profile data over time.</>}>
<InlineSwitch
value={query.includeHeatmap || false}
onChange={(event: React.SyntheticEvent<HTMLInputElement>) => {
onQueryChange({ ...query, includeHeatmap: event.currentTarget.checked });
}}
/>
</EditorField>
{query.includeHeatmap && (
<EditorField label={'Heatmap Type'} tooltip={<>Select the type of heatmap aggregation.</>}>
<RadioButtonGroup
options={[
{ value: 'individual', label: 'Individual', description: 'Show individual profile samples' },
{ value: 'span', label: 'Span', description: 'Aggregate by span duration' },
]}
value={query.heatmapType || 'individual'}
onChange={(value) => onQueryChange({ ...query, heatmapType: value as HeatmapQueryType })}
/>
</EditorField>
)}
</>
)}
</div>
</QueryOptionGroup>
</Stack>
@@ -46,6 +46,11 @@ composableKinds: DataQuery: {
annotations?: bool
// If set to true, exemplars will be requested
includeExemplars: bool | *false
// If set to true, heatmap data will be requested
includeHeatmap: bool | *false
// Specifies the type of heatmap query
heatmapType: #HeatmapQueryType | *"individual"
#HeatmapQueryType: "individual" | "span" @cuetsy(kind="type")
}
}]
lenses: []
@@ -14,6 +14,8 @@ export type PyroscopeQueryType = ('metrics' | 'profile' | 'both');
export const defaultPyroscopeQueryType: PyroscopeQueryType = 'both';
export type HeatmapQueryType = ('individual' | 'span');
export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
/**
* If set to true, the response will contain annotations
@@ -23,10 +25,18 @@ export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
* Allows to group the results.
*/
groupBy: Array<string>;
/**
* Specifies the type of heatmap query
*/
heatmapType: (HeatmapQueryType | 'individual');
/**
* If set to true, exemplars will be requested
*/
includeExemplars: boolean;
/**
* If set to true, heatmap data will be requested
*/
includeHeatmap: boolean;
/**
* Specifies the query label selectors.
*/
@@ -51,7 +61,9 @@ export interface GrafanaPyroscopeDataQuery extends common.DataQuery {
export const defaultGrafanaPyroscopeDataQuery: Partial<GrafanaPyroscopeDataQuery> = {
groupBy: [],
heatmapType: 'individual',
includeExemplars: false,
includeHeatmap: false,
labelSelector: '{}',
spanSelector: [],
};
@@ -44,6 +44,8 @@ describe('Pyroscope data source', () => {
profileTypeId: '',
groupBy: [''],
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
},
]);
expect(queries).toMatchObject([
@@ -120,6 +122,8 @@ describe('normalizeQuery', () => {
profileTypeId: 'cpu',
refId: '',
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
});
expect(normalized).toMatchObject({
labelSelector: '{app="myapp"}',
@@ -148,6 +152,8 @@ const defaultQuery = (query: Partial<Query>): Query => {
profileTypeId: '',
queryType: defaultPyroscopeQueryType,
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
...query,
};
};
@@ -130,6 +130,8 @@ export class PyroscopeDataSource extends DataSourceWithBackend<Query, PyroscopeD
profileTypeId: '',
groupBy: [],
includeExemplars: false,
includeHeatmap: false,
heatmapType: 'individual',
};
}
@@ -1,4 +1,4 @@
import { ReactElement, useEffect, useRef, useState, ReactNode } from 'react';
import { ReactElement, useContext, useEffect, useRef, useState, ReactNode } from 'react';
import * as React from 'react';
import uPlot from 'uplot';
@@ -13,7 +13,7 @@ import {
PanelData,
} from '@grafana/data';
import { HeatmapCellLayout } from '@grafana/schema';
import { TooltipDisplayMode, useTheme2 } from '@grafana/ui';
import { TextLink, TooltipDisplayMode, useTheme2 } from '@grafana/ui';
import {
VizTooltipContent,
VizTooltipFooter,
@@ -25,9 +25,8 @@ import {
} from '@grafana/ui/internal';
import { ColorScale } from 'app/core/components/ColorScale/ColorScale';
import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { ExploreSplitOpenContext } from 'app/features/explore/Heatmap/HeatmapExploreContainer';
import { readHeatmapRowsCustomMeta } from 'app/features/transformers/calculateHeatmap/heatmap';
import { getDisplayValuesAndLinks } from 'app/features/visualization/data-hover/DataHoverView';
import { ExemplarTooltip } from 'app/features/visualization/data-hover/ExemplarTooltip';
import { getDataLinks, getFieldActions } from '../status-history/utils';
import { isTooltipScrollable } from '../timeseries/utils';
@@ -59,25 +58,194 @@ interface HeatmapTooltipProps {
canExecuteActions?: boolean;
}
export const HeatmapTooltip = (props: HeatmapTooltipProps) => {
if (props.seriesIdx === 2) {
const dispValuesAndLinks = getDisplayValuesAndLinks(props.dataRef.current!.exemplars!, props.dataIdxs[2]!);
// Custom exemplar tooltip that renders field values with inline links
const HeatmapExemplarTooltip = ({
exemplarFrame,
rowIndex,
isPinned,
maxHeight,
}: {
exemplarFrame: PanelData['series'][0];
rowIndex: number;
isPinned: boolean;
maxHeight?: number;
}) => {
const { splitOpen, timeRange } = useContext(ExploreSplitOpenContext);
if (dispValuesAndLinks == null) {
return null;
// Get visible fields (excluding private labels starting with __)
const visibleFields = exemplarFrame.fields.filter(
(f) => !Boolean(f.config.custom?.hideFrom?.tooltip) && !f.name.startsWith('__')
);
if (visibleFields.length === 0) {
return null;
}
// Find time field
const timeField = visibleFields.find((f) => f.name === 'Time');
const timeValue = timeField
? formattedValueToString(
timeField.display ? timeField.display(timeField.values[rowIndex]) : { text: `${timeField.values[rowIndex]}` }
)
: '';
// Prepare fields to display (excluding time)
const displayFields = visibleFields.filter((f) => f !== timeField);
const theme = useTheme2();
// Helper to check if this is a Span ID field (not Profile ID)
const isSpanIdField = (field: Field) => {
return field.config.displayName === 'Span ID';
};
// Helper to check if a label name needs quoting
// Label names with non-alphanumeric characters (except _) need to be quoted
const needsQuoting = (labelName: string): boolean => {
// Valid unquoted label names: start with letter or underscore, followed by alphanumeric or underscore
return !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(labelName);
};
// Helper to quote a label name if needed
const quoteLabelName = (labelName: string): string => {
if (needsQuoting(labelName)) {
// Escape any quotes in the label name itself, then wrap in quotes
return `"${labelName.replace(/"/g, '\\"')}"`;
}
return labelName;
};
// Helper to escape label values for Pyroscope label selector
// Need to escape backslashes and quotes
const escapeLabelValue = (value: string): string => {
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
};
// Helper to manually generate Explore query for span profile
const handleSpanIdClick = (spanId: string) => {
if (!splitOpen || !timeRange) {
return;
}
const { displayValues, links } = dispValuesAndLinks;
// Extract profileTypeId from __profile_type__ field
const profileTypeField = exemplarFrame.fields.find((f) => f.name === '__profile_type__');
const profileTypeId = profileTypeField ? String(profileTypeField.values[rowIndex]) : '';
// Collect all label fields (excluding Time, Value, Id, and private labels starting with __)
const labelFields = exemplarFrame.fields.filter(
(f) => f.name !== 'Time' && f.name !== 'Value' && f.name !== 'Id' && !f.name.startsWith('__')
);
// Build label selector with properly escaped values and quoted label names if needed
// Format: {label1="value1", "label-2"="value2", ...}
const labelParts = labelFields.map((field) => {
const value = field.values[rowIndex];
const quotedLabelName = quoteLabelName(field.name);
const escapedValue = escapeLabelValue(String(value));
return `${quotedLabelName}="${escapedValue}"`;
});
const labelSelector = labelParts.length > 0 ? `{${labelParts.join(', ')}}` : '';
// Get timestamp from Time field and create a narrow time window around it (+/- 30 seconds)
const timeMs = timeField?.values[rowIndex];
const timestamp = timeMs instanceof Date ? timeMs.getTime() : timeMs;
// Create a 60-second window centered on the exemplar (30s before and after)
const windowMs = 30 * 1000; // 30 seconds in milliseconds
const narrowRange = {
from: new Date(timestamp - windowMs).toISOString(),
to: new Date(timestamp + windowMs).toISOString(),
};
// Construct the query for span profile
const query = {
queryType: 'profile',
spanSelector: [spanId],
labelSelector,
profileTypeId,
groupBy: [],
};
// Open in explore with the span profile query and narrow time range
splitOpen({
queries: [query],
range: narrowRange,
});
};
return (
<VizTooltipWrapper>
<VizTooltipHeader
item={{
label: 'Exemplar',
value: timeValue,
}}
isPinned={isPinned}
/>
<VizTooltipContent items={[]} isPinned={isPinned} maxHeight={maxHeight} scrollable={maxHeight != null}>
<div style={{ padding: `${theme.spacing(1)} 0` }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<tbody>
{displayFields.map((field, i) => {
const value = field.values[rowIndex];
const fieldDisplay = field.display ? field.display(value) : { text: `${value}`, numeric: +value };
const fieldName = getFieldDisplayName(field, exemplarFrame);
const valueString = formattedValueToString(fieldDisplay);
// Check if this is a Span ID field that should have a link
const isSpanId = isSpanIdField(field);
const hasLink = isSpanId && splitOpen;
return (
<tr key={i}>
<td
style={{
padding: `${theme.spacing(0.25)} ${theme.spacing(2)} ${theme.spacing(0.25)} 0`,
fontWeight: theme.typography.fontWeightMedium,
}}
>
{fieldName}:
</td>
<td style={{ padding: `${theme.spacing(0.25)} 0` }}>
{hasLink ? (
<TextLink
href="#"
onClick={(e) => {
e.preventDefault();
handleSpanIdClick(valueString);
}}
external={false}
weight="medium"
inline={false}
>
{valueString}
</TextLink>
) : (
valueString
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</VizTooltipContent>
</VizTooltipWrapper>
);
};
export const HeatmapTooltip = (props: HeatmapTooltipProps) => {
if (props.seriesIdx === 2) {
const exemplarFrame = props.dataRef.current!.exemplars!;
const rowIndex = props.dataIdxs[2]!;
return (
<ExemplarTooltip
items={displayValues.map((dispVal) => ({
label: dispVal.name,
value: dispVal.valueString,
}))}
links={links}
maxHeight={props.maxHeight}
<HeatmapExemplarTooltip
exemplarFrame={exemplarFrame}
rowIndex={rowIndex}
isPinned={props.isPinned}
maxHeight={props.maxHeight}
/>
);
}
+28 -1
View File
@@ -95,7 +95,34 @@ export function prepareHeatmapData({
cacheFieldDisplayNames(frames);
const exemplars = annotations?.find((f) => f.name === 'exemplar');
// Helper function to check if two label sets match
const labelsMatch = (labels1: Record<string, string> | undefined, labels2: Record<string, string> | undefined) => {
if (!labels1 && !labels2) {
return true;
}
if (!labels1 || !labels2) {
return false;
}
const keys1 = Object.keys(labels1);
const keys2 = Object.keys(labels2);
if (keys1.length !== keys2.length) {
return false;
}
return keys1.every((key) => labels1[key] === labels2[key]);
};
// Find the first heatmap frame to get its labels
const heatmapFrame = frames.find((f) => f.meta?.type === DataFrameType.HeatmapCells);
const heatmapLabels = heatmapFrame?.fields.find((f) => f.name === 'count')?.labels;
// Find the exemplar frame that matches the heatmap frame's labels
const exemplars = annotations?.find((f) => {
if (f.name !== 'exemplar') {
return false;
}
const valueField = f.fields.find((field) => field.name === 'Value');
return labelsMatch(heatmapLabels, valueField?.labels);
});
exemplars?.fields.forEach((field) => {
field.getLinks = getLinksSupplier(exemplars, field, field.state?.scopedVars ?? {}, replaceVariables);
+2
View File
@@ -215,6 +215,7 @@ export interface ExploreItemState {
showTrace?: boolean;
showNodeGraph?: boolean;
showFlameGraph?: boolean;
showHeatmap?: boolean;
showCustom?: boolean;
/**
@@ -281,6 +282,7 @@ export interface ExplorePanelData extends PanelData {
nodeGraphFrames: DataFrame[];
rawPrometheusFrames: DataFrame[];
flameGraphFrames: DataFrame[];
heatmapFrames: DataFrame[];
graphResult: DataFrame[] | null;
tableResult: DataFrame[] | null;
logsResult: LogsModel | null;
-47
View File
@@ -11906,53 +11906,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Odstranit",
"confirm-delete-keep-resources": "Opravdu chcete odstranit konfiguraci úložiště, ale ponechat jeho zdroje?",
"confirm-delete-with-resources": "Opravdu chcete odstranit konfiguraci úložiště a všechny jeho zdroje?",
@@ -12220,7 +12174,6 @@
"jobs": "Práce"
},
"repository-actions": {
"connections": "",
"settings": "Nastavení",
"source-code": "Zdrojový kód"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Löschen",
"confirm-delete-keep-resources": "Sind Sie sicher, dass Sie die Repository-Konfiguration löschen, aber ihre Ressourcen behalten möchten?",
"confirm-delete-with-resources": "Sind Sie sicher, dass Sie die Repository-Konfiguration und alle ihre Ressourcen löschen möchten?",
@@ -12116,7 +12070,6 @@
"jobs": "Aufträge"
},
"repository-actions": {
"connections": "",
"settings": "Einstellungen",
"source-code": "Quellcode"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Eliminar",
"confirm-delete-keep-resources": "¿Seguro que quieres eliminar la configuración del repositorio pero conservar sus recursos?",
"confirm-delete-with-resources": "¿Seguro que quieres eliminar la configuración del repositorio y todos sus recursos?",
@@ -12116,7 +12070,6 @@
"jobs": "Trabajos"
},
"repository-actions": {
"connections": "",
"settings": "Configuración",
"source-code": "Código fuente"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Supprimer",
"confirm-delete-keep-resources": "Voulez-vous vraiment supprimer la configuration du référentiel tout en conservant ses ressources ?",
"confirm-delete-with-resources": "Voulez-vous vraiment supprimer la configuration du référentiel ainsi que toutes ses ressources ?",
@@ -12116,7 +12070,6 @@
"jobs": "Missions"
},
"repository-actions": {
"connections": "",
"settings": "Paramètres",
"source-code": "Code source"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Törlés",
"confirm-delete-keep-resources": "Biztosan törli az adattár konfigurációját, és megtartja az erőforrásait?",
"confirm-delete-with-resources": "Biztosan törli az adattár konfigurációját és az összes erőforrását?",
@@ -12116,7 +12070,6 @@
"jobs": "Feladatok"
},
"repository-actions": {
"connections": "",
"settings": "Beállítások",
"source-code": "Forráskód"
},
-47
View File
@@ -11756,53 +11756,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Hapus",
"confirm-delete-keep-resources": "Anda yakin ingin menghapus konfigurasi repositori, tetapi menyimpan sumber dayanya?",
"confirm-delete-with-resources": "Anda yakin ingin menghapus konfigurasi repositori dan semua sumber dayanya?",
@@ -12064,7 +12018,6 @@
"jobs": "Pekerjaan"
},
"repository-actions": {
"connections": "",
"settings": "Pengaturan",
"source-code": "Kode sumber"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Elimina",
"confirm-delete-keep-resources": "Vuoi davvero eliminare la configurazione del repository ma conservarne le risorse?",
"confirm-delete-with-resources": "Vuoi davvero eliminare la configurazione del repository e tutte le sue risorse?",
@@ -12116,7 +12070,6 @@
"jobs": "Attività"
},
"repository-actions": {
"connections": "",
"settings": "Impostazioni",
"source-code": "Codice sorgente"
},
-47
View File
@@ -11756,53 +11756,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "削除",
"confirm-delete-keep-resources": "リポジトリ設定を削除するものの、そのリソースを保持してもよろしいですか?",
"confirm-delete-with-resources": "リポジトリ設定とそのすべてのリソースを削除してもよろしいですか?",
@@ -12064,7 +12018,6 @@
"jobs": "ジョブ"
},
"repository-actions": {
"connections": "",
"settings": "設定",
"source-code": "ソースコード"
},
-47
View File
@@ -11756,53 +11756,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "삭제",
"confirm-delete-keep-resources": "정말 리포지토리 구성만 삭제하고 해당 리소스는 그대로 유지하시겠어요?",
"confirm-delete-with-resources": "정말 리포지토리 구성과 해당하는 모든 리소스를 삭제하시겠어요?",
@@ -12064,7 +12018,6 @@
"jobs": "작업"
},
"repository-actions": {
"connections": "",
"settings": "설정",
"source-code": "소스 코드"
},
-47
View File
@@ -11806,53 +11806,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Verwijderen",
"confirm-delete-keep-resources": "Weet je zeker dat je de repository-configuratie wilt verwijderen, maar de bronnen wilt behouden?",
"confirm-delete-with-resources": "Weet je zeker dat je de repository-configuratie en alle bronnen wilt verwijderen?",
@@ -12116,7 +12070,6 @@
"jobs": "Taken"
},
"repository-actions": {
"connections": "",
"settings": "Instellingen",
"source-code": "Broncode"
},
-47
View File
@@ -11906,53 +11906,7 @@
"free-tier-limit-tooltip": "",
"instance-fully-managed-tooltip": ""
},
"connection-form": {
"alert-connection-deleted": "",
"alert-connection-saved": "",
"alert-connection-updated": "",
"back-to-connections": "",
"button-save": "",
"button-saving": "",
"description-app-id": "",
"description-installation-id": "",
"description-private-key": "",
"description-provider": "",
"error-delete-connection": "",
"error-required": "",
"error-save-connection": "",
"label-app-id": "",
"label-installation-id": "",
"label-private-key": "",
"label-provider": "",
"not-found": "",
"not-found-description": "",
"page-subtitle": "",
"page-title-create": "",
"page-title-edit": "",
"placeholder-app-id": "",
"placeholder-installation-id": "",
"placeholder-private-key": ""
},
"connections": {
"add-connection": "",
"cancel": "",
"delete": "",
"delete-confirm": "",
"delete-title": "",
"error-loading": "",
"no-connections": "",
"no-connections-message": "",
"no-results": "",
"page-subtitle": "",
"page-title": "",
"search-placeholder": "",
"status-connected": "",
"status-disconnected": "",
"status-unknown": "",
"view": ""
},
"delete-repository-button": {
"button-cancel": "",
"button-delete": "Usuń",
"confirm-delete-keep-resources": "Na pewno chcesz usunąć konfigurację repozytorium, ale zachować jego zasoby?",
"confirm-delete-with-resources": "Na pewno chcesz usunąć konfigurację repozytorium i wszystkie jego zasoby?",
@@ -12220,7 +12174,6 @@
"jobs": "Zadania"
},
"repository-actions": {
"connections": "",
"settings": "Ustawienia",
"source-code": "Kod źródłowy"
},

Some files were not shown because too many files have changed in this diff Show More