Query Library: Move backend to enterprise (#100371)

* Move files to enterprise

* Remove last parts of QL api

* Fix CODEOWNERS
pull/100717/head
Andrej Ocenas 4 months ago committed by GitHub
parent ba3a90d8fd
commit d092998927
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 2
      .github/CODEOWNERS
  2. 6
      pkg/apis/peakq/v0alpha1/doc.go
  3. 52
      pkg/apis/peakq/v0alpha1/register.go
  4. 32
      pkg/apis/peakq/v0alpha1/types.go
  5. 105
      pkg/apis/peakq/v0alpha1/zz_generated.deepcopy.go
  6. 19
      pkg/apis/peakq/v0alpha1/zz_generated.defaults.go
  7. 155
      pkg/apis/peakq/v0alpha1/zz_generated.openapi.go
  8. 2
      pkg/registry/apis/apis.go
  9. 175
      pkg/registry/apis/peakq/register.go
  10. 107
      pkg/registry/apis/peakq/render.go
  11. 74
      pkg/registry/apis/peakq/render_examples.go
  12. 21
      pkg/registry/apis/peakq/render_examples_test.go
  13. 2
      pkg/registry/apis/wireset.go
  14. 2136
      pkg/tests/apis/openapi_snapshots/peakq.grafana.app-v0alpha1.json
  15. 3
      pkg/tests/apis/openapi_test.go
  16. 71
      pkg/tests/apis/peakq/peakq_test.go
  17. 7
      pkg/tests/apis/peakq/testdata/query-generate.yaml
  18. 2
      public/app/core/reducers/root.ts
  19. 20
      public/app/features/explore/spec/helper/mocks.ts
  20. 11
      public/app/features/explore/spec/helper/setup.tsx
  21. 0
      public/app/features/explore/spec/helper/testdata/identityDisplayList.ts
  22. 0
      public/app/features/explore/spec/helper/testdata/testQueryList.ts
  23. 16
      public/app/features/query-library/api/api.ts
  24. 475
      public/app/features/query-library/api/endpoints.gen.ts
  25. 54
      public/app/features/query-library/api/mappers.ts
  26. 13
      public/app/features/query-library/api/mocks.ts
  27. 53
      public/app/features/query-library/index.ts
  28. 42
      public/app/features/query-library/types.ts
  29. 2
      public/app/store/configureStore.ts
  30. 9
      scripts/generate-rtk-apis.ts

@ -515,7 +515,6 @@ playwright.config.ts @grafana/plugins-platform-frontend
/public/app/features/playlist/ @grafana/dashboards-squad
/public/app/features/plugins/ @grafana/plugins-platform-frontend
/public/app/features/profile/ @grafana/grafana-frontend-platform
/public/app/features/query-library/ @grafana/grafana-frontend-platform
/public/app/features/runtime/ @ryantxu
/public/app/features/query/ @grafana/dashboards-squad
/public/app/features/sandbox/ @grafana/grafana-frontend-platform
@ -593,6 +592,7 @@ playwright.config.ts @grafana/plugins-platform-frontend
/public/app/features/explore/NodeGraph/ @grafana/observability-traces-and-profiling
/public/app/features/explore/FlameGraph/ @grafana/observability-traces-and-profiling
/public/app/features/explore/TraceView/ @grafana/observability-traces-and-profiling
/public/app/features/explore/QueryLibrary/ @grafana/grafana-frontend-platform
/public/api-merged.json @grafana/grafana-backend-group
/public/api-enterprise-spec.json @grafana/grafana-backend-group

@ -1,6 +0,0 @@
// +k8s:deepcopy-gen=package
// +k8s:openapi-gen=true
// +k8s:defaulter-gen=TypeMeta
// +groupName=peakq.grafana.app
package v0alpha1 // import "github.com/grafana/grafana/pkg/apis/peakq/v0alpha1"

@ -1,52 +0,0 @@
package v0alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/grafana/grafana/pkg/apimachinery/utils"
)
const (
GROUP = "peakq.grafana.app"
VERSION = "v0alpha1"
APIVERSION = GROUP + "/" + VERSION
)
var QueryTemplateResourceInfo = utils.NewResourceInfo(GROUP, VERSION,
"querytemplates", "querytemplate", "QueryTemplate",
func() runtime.Object { return &QueryTemplate{} },
func() runtime.Object { return &QueryTemplateList{} },
utils.TableColumns{}, // default table converter
)
var (
// SchemeGroupVersion is group version used to register these objects
SchemeGroupVersion = schema.GroupVersion{Group: GROUP, Version: VERSION}
// SchemaBuilder is used by standard codegen
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
func init() {
localSchemeBuilder.Register(addKnownTypes)
}
// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&QueryTemplate{},
&QueryTemplateList{},
&RenderedQuery{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}

@ -1,32 +0,0 @@
package v0alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type QueryTemplate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec template.QueryTemplate `json:"spec,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type QueryTemplateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []QueryTemplate `json:"items,omitempty"`
}
// Dummy object that represents a real query object
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type RenderedQuery struct {
metav1.TypeMeta `json:",inline"`
// +listType=atomic
Targets []template.Target `json:"targets,omitempty"`
}

@ -1,105 +0,0 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
// SPDX-License-Identifier: AGPL-3.0-only
// Code generated by deepcopy-gen. DO NOT EDIT.
package v0alpha1
import (
template "github.com/grafana/grafana/pkg/apis/query/v0alpha1/template"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *QueryTemplate) DeepCopyInto(out *QueryTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QueryTemplate.
func (in *QueryTemplate) DeepCopy() *QueryTemplate {
if in == nil {
return nil
}
out := new(QueryTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *QueryTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *QueryTemplateList) DeepCopyInto(out *QueryTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]QueryTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QueryTemplateList.
func (in *QueryTemplateList) DeepCopy() *QueryTemplateList {
if in == nil {
return nil
}
out := new(QueryTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *QueryTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RenderedQuery) DeepCopyInto(out *RenderedQuery) {
*out = *in
out.TypeMeta = in.TypeMeta
if in.Targets != nil {
in, out := &in.Targets, &out.Targets
*out = make([]template.Target, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RenderedQuery.
func (in *RenderedQuery) DeepCopy() *RenderedQuery {
if in == nil {
return nil
}
out := new(RenderedQuery)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *RenderedQuery) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}

@ -1,19 +0,0 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
// SPDX-License-Identifier: AGPL-3.0-only
// Code generated by defaulter-gen. DO NOT EDIT.
package v0alpha1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// RegisterDefaults adds defaulters functions to the given scheme.
// Public to allow building arbitrary schemes.
// All generated defaulters are covering - they call all nested defaulters.
func RegisterDefaults(scheme *runtime.Scheme) error {
return nil
}

@ -1,155 +0,0 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
// SPDX-License-Identifier: AGPL-3.0-only
// Code generated by openapi-gen. DO NOT EDIT.
package v0alpha1
import (
common "k8s.io/kube-openapi/pkg/common"
spec "k8s.io/kube-openapi/pkg/validation/spec"
)
func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
return map[string]common.OpenAPIDefinition{
"github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.QueryTemplate": schema_pkg_apis_peakq_v0alpha1_QueryTemplate(ref),
"github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.QueryTemplateList": schema_pkg_apis_peakq_v0alpha1_QueryTemplateList(ref),
"github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.RenderedQuery": schema_pkg_apis_peakq_v0alpha1_RenderedQuery(ref),
}
}
func schema_pkg_apis_peakq_v0alpha1_QueryTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
},
},
"spec": {
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/pkg/apis/query/v0alpha1/template.QueryTemplate"),
},
},
},
},
},
Dependencies: []string{
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template.QueryTemplate", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
}
}
func schema_pkg_apis_peakq_v0alpha1_QueryTemplateList(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"),
},
},
"items": {
SchemaProps: spec.SchemaProps{
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.QueryTemplate"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.QueryTemplate", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
}
}
func schema_pkg_apis_peakq_v0alpha1_RenderedQuery(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "Dummy object that represents a real query object",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
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{"string"},
Format: "",
},
},
"targets": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/pkg/apis/query/v0alpha1/template.Target"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template.Target"},
}
}

@ -11,7 +11,6 @@ import (
"github.com/grafana/grafana/pkg/registry/apis/featuretoggle"
"github.com/grafana/grafana/pkg/registry/apis/folders"
"github.com/grafana/grafana/pkg/registry/apis/iam"
"github.com/grafana/grafana/pkg/registry/apis/peakq"
"github.com/grafana/grafana/pkg/registry/apis/provisioning"
"github.com/grafana/grafana/pkg/registry/apis/query"
"github.com/grafana/grafana/pkg/registry/apis/scope"
@ -31,7 +30,6 @@ func ProvideRegistryServiceSink(
_ *featuretoggle.FeatureFlagAPIBuilder,
_ *datasource.DataSourceAPIBuilder,
_ *folders.FolderAPIBuilder,
_ *peakq.PeakQAPIBuilder,
_ *iam.IdentityAccessManagementAPIBuilder,
_ *scope.ScopeAPIBuilder,
_ *query.QueryAPIBuilder,

@ -1,175 +0,0 @@
package peakq
import (
"github.com/prometheus/client_golang/prometheus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/kube-openapi/pkg/common"
"k8s.io/kube-openapi/pkg/spec3"
"k8s.io/kube-openapi/pkg/validation/spec"
peakq "github.com/grafana/grafana/pkg/apis/peakq/v0alpha1"
grafanaregistry "github.com/grafana/grafana/pkg/apiserver/registry/generic"
"github.com/grafana/grafana/pkg/services/apiserver/builder"
"github.com/grafana/grafana/pkg/services/featuremgmt"
)
var _ builder.APIGroupBuilder = (*PeakQAPIBuilder)(nil)
// This is used just so wire has something unique to return
type PeakQAPIBuilder struct{}
func NewPeakQAPIBuilder() *PeakQAPIBuilder {
return &PeakQAPIBuilder{}
}
func RegisterAPIService(features featuremgmt.FeatureToggles, apiregistration builder.APIRegistrar, reg prometheus.Registerer) *PeakQAPIBuilder {
if !featuremgmt.AnyEnabled(features,
featuremgmt.FlagQueryService,
featuremgmt.FlagQueryLibrary,
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs) {
return nil // skip registration unless explicitly added (or all experimental are added)
}
builder := NewPeakQAPIBuilder()
apiregistration.RegisterAPI(builder)
return builder
}
func (b *PeakQAPIBuilder) GetAuthorizer() authorizer.Authorizer {
return nil // default authorizer is fine
}
func (b *PeakQAPIBuilder) GetGroupVersion() schema.GroupVersion {
return peakq.SchemeGroupVersion
}
func (b *PeakQAPIBuilder) InstallSchema(scheme *runtime.Scheme) error {
gv := peakq.SchemeGroupVersion
err := peakq.AddToScheme(scheme)
if err != nil {
return err
}
// Link this version to the internal representation.
// This is used for server-side-apply (PATCH), and avoids the error:
// "no kind is registered for the type"
// addKnownTypes(scheme, schema.GroupVersion{
// Group: peakq.GROUP,
// Version: runtime.APIVersionInternal,
// })
metav1.AddToGroupVersion(scheme, gv)
return scheme.SetVersionPriority(gv)
}
func (b *PeakQAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.APIGroupInfo, opts builder.APIGroupOptions) error {
resourceInfo := peakq.QueryTemplateResourceInfo
storage := map[string]rest.Storage{}
peakqStorage, err := grafanaregistry.NewRegistryStore(opts.Scheme, resourceInfo, opts.OptsGetter)
if err != nil {
return err
}
storage[resourceInfo.StoragePath()] = peakqStorage
storage[resourceInfo.StoragePath("render")] = &renderREST{
getter: peakqStorage,
}
apiGroupInfo.VersionedResourcesStorageMap[peakq.VERSION] = storage
return nil
}
func (b *PeakQAPIBuilder) GetOpenAPIDefinitions() common.GetOpenAPIDefinitions {
return peakq.GetOpenAPIDefinitions
}
// NOT A GREAT APPROACH... BUT will make a UI for statically defined
func (b *PeakQAPIBuilder) GetAPIRoutes() *builder.APIRoutes {
defs := peakq.GetOpenAPIDefinitions(func(path string) spec.Ref { return spec.Ref{} })
renderedQuerySchema := defs["github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.RenderedQuery"].Schema
queryTemplateSpecSchema := defs["github.com/grafana/grafana/pkg/apis/peakq/v0alpha1.QueryTemplateSpec"].Schema
params := []*spec3.Parameter{
{
ParameterProps: spec3.ParameterProps{
// Arbitrary name. It won't appear in the request URL,
// but will be used in code generated from this OAS spec
Name: "variables",
In: "query",
Schema: spec.MapProperty(spec.ArrayProperty(spec.StringProperty())),
Style: "form",
Explode: true,
Description: "Each variable is prefixed with var-{variable}={value}",
Example: map[string][]string{
"var-metricName": {"up"},
"var-another": {"first", "second"},
},
},
},
}
return &builder.APIRoutes{
Root: []builder.APIRouteHandler{
{
Path: "render",
Spec: &spec3.PathProps{
Summary: "an example at the root level",
Description: "longer description here?",
Post: &spec3.Operation{
OperationProps: spec3.OperationProps{
Parameters: params,
RequestBody: &spec3.RequestBody{
RequestBodyProps: spec3.RequestBodyProps{
Content: map[string]*spec3.MediaType{
"application/json": {
MediaTypeProps: spec3.MediaTypeProps{
Schema: &queryTemplateSpecSchema,
// Example: basicTemplateSpec,
Examples: map[string]*spec3.Example{
"test": {
ExampleProps: spec3.ExampleProps{
Summary: "hello",
Value: basicTemplateSpec,
},
},
"test2": {
ExampleProps: spec3.ExampleProps{
Summary: "hello2",
Value: basicTemplateSpec,
},
},
},
},
},
},
},
},
Responses: &spec3.Responses{
ResponsesProps: spec3.ResponsesProps{
StatusCodeResponses: map[int]*spec3.Response{
200: {
ResponseProps: spec3.ResponseProps{
Description: "OK",
Content: map[string]*spec3.MediaType{
"application/json": {
MediaTypeProps: spec3.MediaTypeProps{
Schema: &renderedQuerySchema,
},
},
},
},
},
},
},
},
},
},
},
Handler: renderPOSTHandler,
},
},
}
}

@ -1,107 +0,0 @@
package peakq
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/rest"
peakq "github.com/grafana/grafana/pkg/apis/peakq/v0alpha1"
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template"
)
type renderREST struct {
getter rest.Getter
}
var _ = rest.Connecter(&renderREST{})
func (r *renderREST) New() runtime.Object {
return &peakq.RenderedQuery{}
}
func (r *renderREST) Destroy() {
}
func (r *renderREST) ConnectMethods() []string {
return []string{"GET"}
}
func (r *renderREST) NewConnectOptions() (runtime.Object, bool, string) {
return nil, false, "" // true means you can use the trailing path as a variable
}
func (r *renderREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {
obj, err := r.getter.Get(ctx, name, &v1.GetOptions{})
if err != nil {
return nil, err
}
t, ok := obj.(*peakq.QueryTemplate)
if !ok {
return nil, fmt.Errorf("expected template")
}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
input, err := makeVarMapFromParams(req.URL.Query())
if err != nil {
responder.Error(err)
return
}
out, err := template.RenderTemplate(t.Spec, input)
if err != nil {
responder.Error(fmt.Errorf("failed to render: %w", err))
return
}
responder.Object(http.StatusOK, &peakq.RenderedQuery{
Targets: out,
})
}), nil
}
func renderPOSTHandler(w http.ResponseWriter, req *http.Request) {
input, err := makeVarMapFromParams(req.URL.Query())
if err != nil {
_, _ = w.Write([]byte("ERROR: " + err.Error()))
w.WriteHeader(500)
return
}
var qT peakq.QueryTemplate
err = json.NewDecoder(req.Body).Decode(&qT.Spec)
if err != nil {
_, _ = w.Write([]byte("ERROR: " + err.Error()))
w.WriteHeader(500)
return
}
results, err := template.RenderTemplate(qT.Spec, input)
if err != nil {
_, _ = w.Write([]byte("ERROR: " + err.Error()))
w.WriteHeader(500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(peakq.RenderedQuery{
Targets: results,
})
}
// Replicate the grafana dashboard URL syntax
// &var-abc=1&var=abc=2&var-xyz=3...
func makeVarMapFromParams(v url.Values) (map[string][]string, error) {
input := make(map[string][]string, len(v))
for key, vals := range v {
if !strings.HasPrefix(key, "var-") {
continue
}
input[key[4:]] = vals
}
return input, nil
}

@ -1,74 +0,0 @@
package peakq
import (
"github.com/grafana/grafana-plugin-sdk-go/data"
apidata "github.com/grafana/grafana-plugin-sdk-go/experimental/apis/data/v0alpha1"
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template"
)
var basicTemplateSpec = template.QueryTemplate{
Title: "Test",
Variables: []template.TemplateVariable{
{
Key: "metricName",
DefaultValues: []string{`down`},
},
},
Targets: []template.Target{
{
DataType: data.FrameTypeUnknown,
//DataTypeVersion: data.FrameTypeVersion{0, 0},
Variables: map[string][]template.VariableReplacement{
"metricName": {
{
Path: "$.expr",
Position: &template.Position{
Start: 0,
End: 10,
},
},
{
Path: "$.expr",
Position: &template.Position{
Start: 13,
End: 23,
},
},
},
},
Properties: apidata.NewDataQuery(map[string]any{
"refId": "A", // TODO: Set when Where?
"datasource": map[string]any{
"type": "prometheus",
"uid": "foo", // TODO: Probably a default templating thing to set this.
},
"editorMode": "builder",
"expr": "metricName + metricName + 42",
"instant": true,
"range": false,
"exemplar": false,
}),
},
},
}
var basicTemplateRenderedTargets = []template.Target{
{
DataType: data.FrameTypeUnknown,
//DataTypeVersion: data.FrameTypeVersion{0, 0},
Properties: apidata.NewDataQuery(map[string]any{
"refId": "A", // TODO: Set when Where?
"datasource": map[string]any{
"type": "prometheus",
"uid": "foo", // TODO: Probably a default templating thing to set this.
},
"editorMode": "builder",
"expr": "up + up + 42",
"instant": true,
"range": false,
"exemplar": false,
}),
},
}

@ -1,21 +0,0 @@
package peakq
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/apis/query/v0alpha1/template"
)
func TestRender(t *testing.T) {
rT, err := template.RenderTemplate(basicTemplateSpec, map[string][]string{"metricName": {"up"}})
require.NoError(t, err)
require.Equal(t,
basicTemplateRenderedTargets[0].Properties.GetString("expr"),
rT[0].Properties.GetString("expr"))
b, _ := json.MarshalIndent(basicTemplateSpec, "", " ")
fmt.Println(string(b))
}

@ -13,7 +13,6 @@ import (
"github.com/grafana/grafana/pkg/registry/apis/featuretoggle"
"github.com/grafana/grafana/pkg/registry/apis/folders"
"github.com/grafana/grafana/pkg/registry/apis/iam"
"github.com/grafana/grafana/pkg/registry/apis/peakq"
"github.com/grafana/grafana/pkg/registry/apis/provisioning"
"github.com/grafana/grafana/pkg/registry/apis/query"
"github.com/grafana/grafana/pkg/registry/apis/scope"
@ -40,7 +39,6 @@ var WireSet = wire.NewSet(
datasource.RegisterAPIService,
folders.RegisterAPIService,
iam.RegisterAPIService,
peakq.RegisterAPIService,
provisioning.RegisterAPIService,
service.RegisterAPIService,
query.RegisterAPIService,

@ -64,9 +64,6 @@ func TestIntegrationOpenAPIs(t *testing.T) {
}, {
Group: "folder.grafana.app",
Version: "v0alpha1",
}, {
Group: "peakq.grafana.app",
Version: "v0alpha1",
}, {
Group: "iam.grafana.app",
Version: "v0alpha1",

@ -1,71 +0,0 @@
package peakq
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/tests/apis"
"github.com/grafana/grafana/pkg/tests/testinfra"
"github.com/grafana/grafana/pkg/tests/testsuite"
)
func TestMain(m *testing.M) {
testsuite.Run(m)
}
func TestIntegrationPeakQ(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{
AppModeProduction: false, // required for experimental APIs
EnableFeatureToggles: []string{
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, // Required to start the example service
},
})
t.Run("Check discovery client", func(t *testing.T) {
disco := helper.NewDiscoveryClient()
resources, err := disco.ServerResourcesForGroupVersion("peakq.grafana.app/v0alpha1")
require.NoError(t, err)
v1Disco, err := json.MarshalIndent(resources, "", " ")
require.NoError(t, err)
//fmt.Printf("%s", string(v1Disco))
require.JSONEq(t, `{
"kind": "APIResourceList",
"apiVersion": "v1",
"groupVersion": "peakq.grafana.app/v0alpha1",
"resources": [
{
"name": "querytemplates",
"singularName": "querytemplate",
"namespaced": true,
"kind": "QueryTemplate",
"verbs": [
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch"
]
},
{
"name": "querytemplates/render",
"singularName": "",
"namespaced": true,
"kind": "RenderedQuery",
"verbs": [
"get"
]
}
]
}`, string(v1Disco))
})
}

@ -1,7 +0,0 @@
apiVersion: peakq.grafana.app/v0alpha1
kind: QueryTemplate
metadata:
generateName: x # anything is ok here... except yes or true -- they become boolean!
spec:
title: Generated query template
description: A description from here

@ -30,7 +30,6 @@ import templatingReducers from 'app/features/variables/state/keyedVariablesReduc
import { alertingApi } from '../../features/alerting/unified/api/alertingApi';
import { iamApi } from '../../features/iam/api/api';
import { userPreferencesAPI } from '../../features/preferences/api';
import { queryLibraryApi } from '../../features/query-library/api/api';
import { cleanUpAction } from '../actions/cleanUp';
const rootReducers = {
@ -60,7 +59,6 @@ const rootReducers = {
[publicDashboardApi.reducerPath]: publicDashboardApi.reducer,
[browseDashboardsAPI.reducerPath]: browseDashboardsAPI.reducer,
[cloudMigrationAPI.reducerPath]: cloudMigrationAPI.reducer,
[queryLibraryApi.reducerPath]: queryLibraryApi.reducer,
[iamApi.reducerPath]: iamApi.reducer,
[userPreferencesAPI.reducerPath]: userPreferencesAPI.reducer,
};

@ -0,0 +1,20 @@
import { getAPIBaseURL } from '../../../../api/utils';
import { getIdentityDisplayList } from './testdata/identityDisplayList';
import { getTestQueryList } from './testdata/testQueryList';
// This is not ideal but not sure how to fix it right now as this is duplicated from the API definition which is in
// Enterprise and so we cannot import it here.
// We have some tests for testing QL inside Explore. The whole Explore setup is in OSS, and it needs these mocks but the
// test itself is in Enterprise. Ideally we would inject the mocks in the tests somehow.
export const BASE_URL = getAPIBaseURL('peakq.grafana.app', 'v0alpha1');
export const mockData = {
all: {
url: BASE_URL,
response: getTestQueryList(),
},
identityDisplay: {
response: getIdentityDisplayList(),
},
};

@ -37,7 +37,6 @@ import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { setLastUsedDatasourceUID } from 'app/core/utils/explore';
import { IdentityServiceMocks, QueryLibraryMocks } from 'app/features/query-library';
import { MIXED_DATASOURCE_NAME } from 'app/plugins/datasource/mixed/MixedDataSource';
import { configureStore } from 'app/store/configureStore';
@ -49,6 +48,16 @@ import { initialUserState } from '../../../profile/state/reducers';
import ExplorePage from '../../ExplorePage';
import { QueriesDrawerContextProvider } from '../../QueriesDrawer/QueriesDrawerContext';
import { mockData } from './mocks';
export const QueryLibraryMocks = {
data: mockData.all,
};
export const IdentityServiceMocks = {
data: mockData.identityDisplay,
};
type DatasourceSetup = { settings: DataSourceInstanceSettings; api: DataSourceApi };
type SetupOptions = {

@ -1,16 +0,0 @@
import { createApi } from '@reduxjs/toolkit/query/react';
import { createBaseQuery } from '../../../api/createBaseQuery';
import { getAPIBaseURL } from '../../../api/utils';
// Currently, we are loading all query templates
// Organizations can have maximum of 1000 query templates
export const QUERY_LIBRARY_GET_LIMIT = 1000;
export const BASE_URL = getAPIBaseURL('peakq.grafana.app', 'v0alpha1');
export const queryLibraryApi = createApi({
baseQuery: createBaseQuery({ baseURL: BASE_URL }),
reducerPath: 'queryLibraryAPI',
endpoints: () => ({}),
});

@ -1,475 +0,0 @@
import { queryLibraryApi as api } from './api';
export const addTagTypes = ['QueryTemplate'] as const;
const injectedRtkApi = api
.enhanceEndpoints({
addTagTypes,
})
.injectEndpoints({
endpoints: (build) => ({
listQueryTemplate: build.query<ListQueryTemplateApiResponse, ListQueryTemplateApiArg>({
query: (queryArg) => ({
url: `/querytemplates`,
params: {
pretty: queryArg.pretty,
allowWatchBookmarks: queryArg.allowWatchBookmarks,
continue: queryArg['continue'],
fieldSelector: queryArg.fieldSelector,
labelSelector: queryArg.labelSelector,
limit: queryArg.limit,
resourceVersion: queryArg.resourceVersion,
resourceVersionMatch: queryArg.resourceVersionMatch,
sendInitialEvents: queryArg.sendInitialEvents,
timeoutSeconds: queryArg.timeoutSeconds,
watch: queryArg.watch,
},
}),
providesTags: ['QueryTemplate'],
}),
createQueryTemplate: build.mutation<CreateQueryTemplateApiResponse, CreateQueryTemplateApiArg>({
query: (queryArg) => ({
url: `/querytemplates`,
method: 'POST',
body: queryArg.queryTemplate,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['QueryTemplate'],
}),
deleteQueryTemplate: build.mutation<DeleteQueryTemplateApiResponse, DeleteQueryTemplateApiArg>({
query: (queryArg) => ({
url: `/querytemplates/${queryArg.name}`,
method: 'DELETE',
body: queryArg.deleteOptions,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
gracePeriodSeconds: queryArg.gracePeriodSeconds,
ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential,
orphanDependents: queryArg.orphanDependents,
propagationPolicy: queryArg.propagationPolicy,
},
}),
invalidatesTags: ['QueryTemplate'],
}),
updateQueryTemplate: build.mutation<UpdateQueryTemplateApiResponse, UpdateQueryTemplateApiArg>({
query: (queryArg) => ({
url: `/querytemplates/${queryArg.name}`,
method: 'PATCH',
body: queryArg.patch,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
force: queryArg.force,
},
}),
invalidatesTags: ['QueryTemplate'],
}),
}),
overrideExisting: false,
});
export { injectedRtkApi as generatedQueryLibraryApi };
export type ListQueryTemplateApiResponse = /** status 200 OK */ QueryTemplateList;
export type ListQueryTemplateApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** 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. */
allowWatchBookmarks?: boolean;
/** 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".
This 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. */
continue?: string;
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
fieldSelector?: string;
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
labelSelector?: string;
/** 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.
The 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. */
limit?: number;
/** 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.
Defaults to unset */
resourceVersion?: string;
/** 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.
Defaults to unset */
resourceVersionMatch?: string;
/** `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.
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
is interpreted as "data at least as new as the provided `resourceVersion`"
and the bookmark event is send when the state is synced
to a `resourceVersion` at least as fresh as the one provided by the ListOptions.
If `resourceVersion` is unset, this is interpreted as "consistent read" and the
bookmark event is send when the state is synced at least to the moment
when request started being processed.
- `resourceVersionMatch` set to any other value or unset
Invalid error is returned.
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
sendInitialEvents?: boolean;
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
timeoutSeconds?: number;
/** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
watch?: boolean;
};
export type CreateQueryTemplateApiResponse = /** status 200 OK */
| QueryTemplate
| /** status 201 Created */ QueryTemplate
| /** status 202 Accepted */ QueryTemplate;
export type CreateQueryTemplateApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** 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 */
dryRun?: string;
/** 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. */
fieldManager?: string;
/** 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. */
fieldValidation?: string;
queryTemplate: QueryTemplate;
};
export type DeleteQueryTemplateApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status;
export type DeleteQueryTemplateApiArg = {
/** name of the QueryTemplate */
name: string;
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** 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 */
dryRun?: string;
/** 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. */
gracePeriodSeconds?: number;
/** 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 */
ignoreStoreReadErrorWithClusterBreakingPotential?: boolean;
/** 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. */
orphanDependents?: boolean;
/** 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. */
propagationPolicy?: string;
deleteOptions: DeleteOptions;
};
export type UpdateQueryTemplateApiResponse = /** status 200 OK */
| QueryTemplate
| /** status 201 Created */ QueryTemplate;
export type UpdateQueryTemplateApiArg = {
/** name of the QueryTemplate */
name: string;
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** 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 */
dryRun?: string;
/** 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). */
fieldManager?: string;
/** 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. */
fieldValidation?: string;
/** 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. */
force?: boolean;
patch: Patch;
};
export type Time = string;
export type FieldsV1 = object;
export type ManagedFieldsEntry = {
/** APIVersion defines the version of this resource that this field set applies to. The format is "group/version" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. */
apiVersion?: string;
/** FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: "FieldsV1" */
fieldsType?: string;
/** FieldsV1 holds the first JSON version format as described in the "FieldsV1" type. */
fieldsV1?: FieldsV1;
/** Manager is an identifier of the workflow managing these fields. */
manager?: string;
/** Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. */
operation?: string;
/** Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. */
subresource?: string;
/** Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. */
time?: Time;
};
export type OwnerReference = {
/** API version of the referent. */
apiVersion: string;
/** If true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs "delete" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. */
blockOwnerDeletion?: boolean;
/** If true, this reference points to the managing controller. */
controller?: boolean;
/** Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind: string;
/** Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
name: string;
/** UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid: string;
};
export type ObjectMeta = {
/** Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations */
annotations?: {
[key: string]: string;
};
/** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.
Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
creationTimestamp?: Time;
/** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */
deletionGracePeriodSeconds?: number;
/** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
deletionTimestamp?: Time;
/** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */
finalizers?: string[];
/** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
If this field is specified and the generated name exists, the server will return a 409.
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */
generateName?: string;
/** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */
generation?: number;
/** Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels */
labels?: {
[key: string]: string;
};
/** ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object. */
managedFields?: ManagedFieldsEntry[];
/** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
name?: string;
/** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */
namespace?: string;
/** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */
ownerReferences?: OwnerReference[];
/** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
resourceVersion?: string;
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
selfLink?: string;
/** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid?: string;
};
export type DataQuery = {
/** The datasource */
datasource?: {
/** The apiserver version */
apiVersion?: string;
/** The datasource plugin type */
type: string;
/** Datasource UID (NOTE: name in k8s) */
uid?: string;
};
/** true if query is disabled (ie should not be returned to the dashboard)
NOTE: this does not always imply that the query should not be executed since
the results from a hidden query may be used as the input to other queries (SSE etc) */
hide?: boolean;
/** Interval is the suggested duration between time points in a time series query.
NOTE: the values for intervalMs is not saved in the query model. It is typically calculated
from the interval required to fill a pixels in the visualization */
intervalMs?: number;
/** MaxDataPoints is the maximum number of data points that should be returned from a time series query.
NOTE: the values for maxDataPoints is not saved in the query model. It is typically calculated
from the number of pixels visible in a visualization */
maxDataPoints?: number;
/** QueryType is an optional identifier for the type of query.
It can be used to distinguish different types of queries. */
queryType?: string;
/** RefID is the unique identifier of the query, set by the frontend call. */
refId?: string;
/** Optionally define expected query result behavior */
resultAssertions?: {
/** Maximum frame count */
maxFrames?: number;
/** Type asserts that the frame matches a known type structure.
Possible enum values:
- `""`
- `"timeseries-wide"`
- `"timeseries-long"`
- `"timeseries-many"`
- `"timeseries-multi"`
- `"directory-listing"`
- `"table"`
- `"numeric-wide"`
- `"numeric-multi"`
- `"numeric-long"`
- `"log-lines"` */
type?:
| ''
| 'timeseries-wide'
| 'timeseries-long'
| 'timeseries-many'
| 'timeseries-multi'
| 'directory-listing'
| 'table'
| 'numeric-wide'
| 'numeric-multi'
| 'numeric-long'
| 'log-lines';
/** TypeVersion is the version of the Type property. Versions greater than 0.0 correspond to the dataplane
contract documentation https://grafana.github.io/dataplane/contract/. */
typeVersion: number[];
};
/** TimeRange represents the query range
NOTE: unlike generic /ds/query, we can now send explicit time values in each query
NOTE: the values for timeRange are not saved in a dashboard, they are constructed on the fly */
timeRange?: {
/** From is the start time of the query. */
from: string;
/** To is the end time of the query. */
to: string;
};
[key: string]: any;
};
export type TemplatePosition = {
/** End is the byte offset of the end of the variable. */
end: number;
/** Start is the byte offset within TargetKey's property of the variable. It is the start location for replacements). */
start: number;
};
export type TemplateVariableReplacement = {
/** How values should be interpolated
Possible enum values:
- `"csv"` Formats variables with multiple values as a comma-separated string.
- `"doublequote"` Formats single- and multi-valued variables into a comma-separated string
- `"json"` Formats variables with multiple values as a comma-separated string.
- `"pipe"` Formats variables with multiple values into a pipe-separated string.
- `"raw"` Formats variables with multiple values into comma-separated string. This is the default behavior when no format is specified
- `"singlequote"` Formats single- and multi-valued variables into a comma-separated string */
format?: 'csv' | 'doublequote' | 'json' | 'pipe' | 'raw' | 'singlequote';
/** Path is the location of the property within a target. The format for this is not figured out yet (Maybe JSONPath?). Idea: ["string", int, "string"] where int indicates array offset */
path: string;
/** Positions is a list of where to perform the interpolation within targets during render. The first string is the Idx of the target as a string, since openAPI does not support ints as map keys */
position?: TemplatePosition;
};
export type TemplateTarget = {
/** DataType is the returned Dataplane type from the query. */
dataType?: string;
/** Query target */
properties: DataQuery;
/** Variables that will be replaced in the query */
variables: {
[key: string]: TemplateVariableReplacement[];
};
};
export type Unstructured = {
[key: string]: any;
};
export type TemplateTemplateVariable = {
/** DefaultValue is the value to be used when there is no selected value during render. */
defaultValues?: string[];
/** Key is the name of the variable. */
key: string;
/** ValueListDefinition is the object definition used by the FE to get a list of possible values to select for render. */
valueListDefinition?: Unstructured;
};
export type TemplateQueryTemplate = {
/** Longer description for why it is interesting */
description?: string;
/** Output variables */
targets: TemplateTarget[];
/** A display name */
title?: string;
/** The variables that can be used to render */
vars?: TemplateTemplateVariable[];
};
export type QueryTemplate = {
/** 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 */
apiVersion?: string;
/** 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 */
kind?: string;
metadata?: ObjectMeta;
spec?: TemplateQueryTemplate;
};
export type ListMeta = {
/** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */
continue?: string;
/** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */
remainingItemCount?: number;
/** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
resourceVersion?: string;
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
selfLink?: string;
};
export type QueryTemplateList = {
/** 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 */
apiVersion?: string;
items?: QueryTemplate[];
/** 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 */
kind?: string;
metadata?: ListMeta;
};
export type StatusCause = {
/** 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.
Examples:
"name" - the field "name" on the current resource
"items[0].name" - the field "name" on the first array entry in "items" */
field?: string;
/** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */
message?: string;
/** A machine-readable description of the cause of the error. If this value is empty there is no information available. */
reason?: string;
};
export type StatusDetails = {
/** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */
causes?: StatusCause[];
/** The group attribute of the resource associated with the status StatusReason. */
group?: string;
/** 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 */
kind?: string;
/** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */
name?: string;
/** 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. */
retryAfterSeconds?: number;
/** 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 */
uid?: string;
};
export type Status = {
/** 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 */
apiVersion?: string;
/** Suggested HTTP return code for this status, 0 if not set. */
code?: number;
/** 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. */
details?: StatusDetails;
/** 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 */
kind?: string;
/** A human-readable description of the status of this operation. */
message?: string;
/** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
metadata?: ListMeta;
/** 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. */
reason?: string;
/** 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 */
status?: string;
};
export type Preconditions = {
/** Specifies the target ResourceVersion */
resourceVersion?: string;
/** Specifies the target UID. */
uid?: string;
};
export type DeleteOptions = {
/** 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 */
apiVersion?: string;
/** 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 */
dryRun?: string[];
/** 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. */
gracePeriodSeconds?: number;
/** 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 */
ignoreStoreReadErrorWithClusterBreakingPotential?: boolean;
/** 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 */
kind?: string;
/** 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. */
orphanDependents?: boolean;
/** Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */
preconditions?: Preconditions;
/** 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. */
propagationPolicy?: string;
};
export type Patch = object;

@ -1,54 +0,0 @@
import { v4 as uuidv4 } from 'uuid';
import { AnnoKeyCreatedBy } from '../../apiserver/types';
import { AddQueryTemplateCommand, QueryTemplate } from '../types';
import { ListQueryTemplateApiResponse, QueryTemplate as QT } from './endpoints.gen';
export const convertDataQueryResponseToQueryTemplates = (result: ListQueryTemplateApiResponse): QueryTemplate[] => {
if (!result.items) {
return [];
}
return result.items.map((spec) => {
return {
uid: spec.metadata?.name ?? '',
title: spec.spec?.title ?? '',
targets:
spec.spec?.targets.map((target) => ({
...target.properties,
refId: target.properties.refId ?? '',
})) ?? [],
createdAtTimestamp: new Date(spec.metadata?.creationTimestamp ?? '').getTime(),
user: {
uid: spec.metadata?.annotations?.[AnnoKeyCreatedBy] ?? '',
},
};
});
};
export const convertAddQueryTemplateCommandToDataQuerySpec = (addQueryTemplateCommand: AddQueryTemplateCommand): QT => {
const { title, targets } = addQueryTemplateCommand;
return {
metadata: {
/**
* Server will append to whatever is passed here, but just to be safe we generate a uuid
* More info https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#idempotency
*/
generateName: uuidv4(),
},
spec: {
title: title,
vars: [], // TODO: Detect variables in #86838
targets: targets.map((dataQuery) => ({
variables: {},
properties: {
...dataQuery,
datasource: {
...dataQuery.datasource,
type: dataQuery.datasource?.type ?? '',
},
},
})),
},
};
};

@ -1,13 +0,0 @@
import { BASE_URL } from './api';
import { getIdentityDisplayList } from './testdata/identityDisplayList';
import { getTestQueryList } from './testdata/testQueryList';
export const mockData = {
all: {
url: BASE_URL,
response: getTestQueryList(),
},
identityDisplay: {
response: getIdentityDisplayList(),
},
};

@ -1,53 +0,0 @@
/**
* This is a temporary place for Query Library API and data types.
* To be exposed via grafana-runtime/data in the future.
*
* Query Library is an experimental feature, the API and components are subject to change
*
* @alpha
*/
import { QUERY_LIBRARY_GET_LIMIT } from './api/api';
import { generatedQueryLibraryApi } from './api/endpoints.gen';
import { mockData } from './api/mocks';
export const {
useCreateQueryTemplateMutation,
useDeleteQueryTemplateMutation,
useListQueryTemplateQuery,
useUpdateQueryTemplateMutation,
} = generatedQueryLibraryApi.enhanceEndpoints({
endpoints: {
// Need to mutate the generated query to force query limit
listQueryTemplate: (endpointDefinition) => {
const originalQuery = endpointDefinition.query;
if (originalQuery) {
endpointDefinition.query = (requestOptions) =>
originalQuery({
...requestOptions,
limit: QUERY_LIBRARY_GET_LIMIT,
});
}
},
// Need to mutate the generated query to set the Content-Type header correctly
updateQueryTemplate: (endpointDefinition) => {
const originalQuery = endpointDefinition.query;
if (originalQuery) {
endpointDefinition.query = (requestOptions) => ({
...originalQuery(requestOptions),
headers: {
'Content-Type': 'application/merge-patch+json',
},
});
}
},
},
});
export const QueryLibraryMocks = {
data: mockData.all,
};
export const IdentityServiceMocks = {
data: mockData.identityDisplay,
};

@ -1,42 +0,0 @@
import { DataQuery } from '@grafana/schema';
export type DataQueryTarget = {
variables: object; // TODO: Detect variables in #86838
properties: DataQuery;
};
export type DataQuerySpec = {
title: string;
vars: object[]; // TODO: Detect variables in #86838
targets: DataQueryTarget[];
};
export type DataQueryPartialSpec = Partial<DataQuerySpec>;
export type QueryTemplate = {
uid: string;
title: string;
targets: DataQuery[];
createdAtTimestamp: number;
user?: User;
};
export type AddQueryTemplateCommand = {
title: string;
targets: DataQuery[];
};
export type EditQueryTemplateCommand = {
uid: string;
partialSpec: DataQueryPartialSpec;
};
export type DeleteQueryTemplateCommand = {
uid: string;
};
export type User = {
uid: string;
displayName?: string;
avatarUrl?: string;
};

@ -12,7 +12,6 @@ import { buildInitialState } from '../core/reducers/navModel';
import { addReducer, createRootReducer } from '../core/reducers/root';
import { alertingApi } from '../features/alerting/unified/api/alertingApi';
import { iamApi } from '../features/iam/api/api';
import { queryLibraryApi } from '../features/query-library/api/api';
import { setStore } from './store';
@ -40,7 +39,6 @@ export function configureStore(initialState?: Partial<StoreState>) {
publicDashboardApi.middleware,
browseDashboardsAPI.middleware,
cloudMigrationAPI.middleware,
queryLibraryApi.middleware,
userPreferencesAPI.middleware,
iamApi.middleware,
...extraMiddleware

@ -48,15 +48,6 @@ const config: ConfigFile = {
flattenArg: false,
tag: true,
},
'../public/app/features/query-library/api/endpoints.gen.ts': {
schemaFile: '../data/openapi/peakq.grafana.app-v0alpha1.json',
apiFile: '../public/app/features/query-library/api/api.ts',
apiImport: 'queryLibraryApi',
filterEndpoints: ['listQueryTemplate', 'createQueryTemplate', 'deleteQueryTemplate', 'updateQueryTemplate'],
exportName: 'generatedQueryLibraryApi',
flattenArg: false,
tag: true,
},
},
};

Loading…
Cancel
Save