add alerting v2beta1 apis (#5115)

* generate alerting resource client

Signed-off-by: junot <junotxiang@kubesphere.io>

* add alerting v2beta1 apis

Signed-off-by: junot <junotxiang@kubesphere.io>

* tweak some varibles and descs

Signed-off-by: junot <junotxiang@kubesphere.io>
This commit is contained in:
junot
2022-08-04 13:38:41 +08:00
committed by GitHub
parent d87d7d2428
commit 74e127e1a6
35 changed files with 2947 additions and 15 deletions

View File

@@ -0,0 +1,144 @@
/*
Copyright 2020 KubeSphere Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v2beta1
import (
"strings"
"time"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
)
const (
// for rulegroup/alert
FieldState = "state"
// for rulegroup
FieldRuleGroupEvaluationTime = "evaluationTime"
FieldRuleGroupLastEvaluation = "lastEvalution"
// for alert
FieldAlertLabelFilters = "label_filters"
FieldAlertActiveAt = "activeAt"
)
var SortableFields = []string{
FieldRuleGroupEvaluationTime,
FieldRuleGroupLastEvaluation,
FieldAlertActiveAt,
}
var ComparableFields = []string{
FieldState,
FieldAlertLabelFilters,
}
type RuleGroup struct {
alertingv2beta1.RuleGroup `json:",inline"`
Status RuleGroupStatus `json:"status,omitempty"`
}
type ClusterRuleGroup struct {
alertingv2beta1.ClusterRuleGroup `json:",inline"`
Status RuleGroupStatus `json:"status,omitempty"`
}
type GlobalRuleGroup struct {
alertingv2beta1.GlobalRuleGroup `json:",inline"`
Status RuleGroupStatus `json:"status,omitempty"`
}
type RuleGroupStatus struct {
State string `json:"state,omitempty" description:"state of a rulegroup, one of firing, pending or inactive depending on its rules"`
EvaluationTime *float64 `json:"evaluationTime,omitempty" description:"time spent on rule group evaluation in seconds"`
LastEvaluation *time.Time `json:"lastEvaluation,omitempty" description:"time of last evaluation"`
RulesStatus []RuleStatus `json:"rulesStatus,omitempty" description:"status of rules in one RuleGroup"`
}
type RuleStatus struct {
State string `json:"state,omitempty" description:"state of a rule, one of firing, pending or inactive depending on its alerts"`
Health string `json:"health,omitempty" description:"health state of a rule, one of ok, err, unknown depending on the last execution result"`
LastError string `json:"lastError,omitempty" description:"error of the last evaluation"`
EvaluationTime *float64 `json:"evaluationTime,omitempty" description:"time spent on the expression evaluation in seconds"`
LastEvaluation *time.Time `json:"lastEvaluation,omitempty" description:"time of last evaluation"`
Alerts []*Alert `json:"alerts,omitempty" description:"alerts"`
}
type Alert struct {
ActiveAt *time.Time `json:"activeAt,omitempty" description:"time when this alert became active"`
Annotations map[string]string `json:"annotations,omitempty" description:"annotations"`
Labels map[string]string `json:"labels,omitempty" description:"labels"`
State string `json:"state,omitempty" description:"state"`
Value string `json:"value,omitempty" description:"the value from the last expression evaluation"`
}
type LabelFilterOperator string
const (
LabelFilterOperatorEqual = "="
LabelFilterOperatorContain = "~"
)
type LabelFilter struct {
LabelName string
LabelValue string
Operator LabelFilterOperator
}
func (f *LabelFilter) Matches(labels map[string]string) bool {
v, ok := labels[f.LabelName]
if ok {
switch f.Operator {
case LabelFilterOperatorEqual:
return v == f.LabelValue
case LabelFilterOperatorContain:
return strings.Contains(v, f.LabelValue)
}
}
return false
}
type LabelFilters []LabelFilter
func (fs LabelFilters) Matches(labels map[string]string) bool {
for _, f := range fs {
if !f.Matches(labels) {
return false
}
}
return true
}
func ParseLabelFilters(filters string) LabelFilters {
var fs LabelFilters
for _, filter := range strings.Split(filters, ",") {
if i := strings.Index(filter, LabelFilterOperatorEqual); i > 0 {
fs = append(fs, LabelFilter{
Operator: LabelFilterOperatorEqual,
LabelName: filter[:i],
LabelValue: filter[i+1:],
})
} else if i := strings.Index(filter, LabelFilterOperatorContain); i > 0 {
fs = append(fs, LabelFilter{
Operator: LabelFilterOperatorContain,
LabelName: filter[:i],
LabelValue: filter[i+1:],
})
}
}
return fs
}

View File

@@ -67,6 +67,7 @@ import (
"kubesphere.io/kubesphere/pkg/informers"
alertingv1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v1"
alertingv2alpha1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2alpha1"
alertingv2beta1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2beta1"
clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1"
configv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/config/v1alpha2"
"kubesphere.io/kubesphere/pkg/kapis/crd"
@@ -264,6 +265,7 @@ func (s *APIServer) installKubeSphereAPIs(stopCh <-chan struct{}) {
urlruntime.Must(alertingv1.AddToContainer(s.container, s.Config.AlertingOptions.Endpoint))
urlruntime.Must(alertingv2alpha1.AddToContainer(s.container, s.InformerFactory,
s.KubernetesClient.Prometheus(), s.AlertingClient, s.Config.AlertingOptions))
urlruntime.Must(alertingv2beta1.AddToContainer(s.container, s.KubernetesClient.KubeSphere(), s.AlertingClient))
urlruntime.Must(version.AddToContainer(s.container, s.KubernetesClient.Kubernetes().Discovery()))
urlruntime.Must(kubeedgev1alpha1.AddToContainer(s.container, s.Config.KubeEdgeOptions.Endpoint))
urlruntime.Must(edgeruntimev1alpha1.AddToContainer(s.container, s.Config.EdgeRuntimeOptions.Endpoint))

View File

@@ -24,6 +24,7 @@ import (
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
alertingv2beta1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/alerting/v2beta1"
applicationv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/application/v1alpha1"
auditingv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/auditing/v1alpha1"
clusterv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/cluster/v1alpha1"
@@ -44,6 +45,7 @@ import (
type Interface interface {
Discovery() discovery.DiscoveryInterface
AlertingV2beta1() alertingv2beta1.AlertingV2beta1Interface
ApplicationV1alpha1() applicationv1alpha1.ApplicationV1alpha1Interface
AuditingV1alpha1() auditingv1alpha1.AuditingV1alpha1Interface
ClusterV1alpha1() clusterv1alpha1.ClusterV1alpha1Interface
@@ -66,6 +68,7 @@ type Interface interface {
// version included in a Clientset.
type Clientset struct {
*discovery.DiscoveryClient
alertingV2beta1 *alertingv2beta1.AlertingV2beta1Client
applicationV1alpha1 *applicationv1alpha1.ApplicationV1alpha1Client
auditingV1alpha1 *auditingv1alpha1.AuditingV1alpha1Client
clusterV1alpha1 *clusterv1alpha1.ClusterV1alpha1Client
@@ -84,6 +87,11 @@ type Clientset struct {
typesV1beta2 *typesv1beta2.TypesV1beta2Client
}
// AlertingV2beta1 retrieves the AlertingV2beta1Client
func (c *Clientset) AlertingV2beta1() alertingv2beta1.AlertingV2beta1Interface {
return c.alertingV2beta1
}
// ApplicationV1alpha1 retrieves the ApplicationV1alpha1Client
func (c *Clientset) ApplicationV1alpha1() applicationv1alpha1.ApplicationV1alpha1Interface {
return c.applicationV1alpha1
@@ -185,6 +193,10 @@ func NewForConfig(c *rest.Config) (*Clientset, error) {
}
var cs Clientset
var err error
cs.alertingV2beta1, err = alertingv2beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.applicationV1alpha1, err = applicationv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
@@ -261,6 +273,7 @@ func NewForConfig(c *rest.Config) (*Clientset, error) {
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.alertingV2beta1 = alertingv2beta1.NewForConfigOrDie(c)
cs.applicationV1alpha1 = applicationv1alpha1.NewForConfigOrDie(c)
cs.auditingV1alpha1 = auditingv1alpha1.NewForConfigOrDie(c)
cs.clusterV1alpha1 = clusterv1alpha1.NewForConfigOrDie(c)
@@ -285,6 +298,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset {
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.alertingV2beta1 = alertingv2beta1.New(c)
cs.applicationV1alpha1 = applicationv1alpha1.New(c)
cs.auditingV1alpha1 = auditingv1alpha1.New(c)
cs.clusterV1alpha1 = clusterv1alpha1.New(c)

View File

@@ -25,6 +25,8 @@ import (
fakediscovery "k8s.io/client-go/discovery/fake"
"k8s.io/client-go/testing"
clientset "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
alertingv2beta1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/alerting/v2beta1"
fakealertingv2beta1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/alerting/v2beta1/fake"
applicationv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/application/v1alpha1"
fakeapplicationv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/application/v1alpha1/fake"
auditingv1alpha1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/auditing/v1alpha1"
@@ -106,6 +108,11 @@ func (c *Clientset) Tracker() testing.ObjectTracker {
var _ clientset.Interface = &Clientset{}
// AlertingV2beta1 retrieves the AlertingV2beta1Client
func (c *Clientset) AlertingV2beta1() alertingv2beta1.AlertingV2beta1Interface {
return &fakealertingv2beta1.FakeAlertingV2beta1{Fake: &c.Fake}
}
// ApplicationV1alpha1 retrieves the ApplicationV1alpha1Client
func (c *Clientset) ApplicationV1alpha1() applicationv1alpha1.ApplicationV1alpha1Interface {
return &fakeapplicationv1alpha1.FakeApplicationV1alpha1{Fake: &c.Fake}

View File

@@ -24,6 +24,7 @@ import (
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
applicationv1alpha1 "kubesphere.io/api/application/v1alpha1"
auditingv1alpha1 "kubesphere.io/api/auditing/v1alpha1"
clusterv1alpha1 "kubesphere.io/api/cluster/v1alpha1"
@@ -46,6 +47,7 @@ var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
alertingv2beta1.AddToScheme,
applicationv1alpha1.AddToScheme,
auditingv1alpha1.AddToScheme,
clusterv1alpha1.AddToScheme,

View File

@@ -24,6 +24,7 @@ import (
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
applicationv1alpha1 "kubesphere.io/api/application/v1alpha1"
auditingv1alpha1 "kubesphere.io/api/auditing/v1alpha1"
clusterv1alpha1 "kubesphere.io/api/cluster/v1alpha1"
@@ -46,6 +47,7 @@ var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
alertingv2beta1.AddToScheme,
applicationv1alpha1.AddToScheme,
auditingv1alpha1.AddToScheme,
clusterv1alpha1.AddToScheme,

View File

@@ -0,0 +1,99 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v2beta1
import (
rest "k8s.io/client-go/rest"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
"kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
)
type AlertingV2beta1Interface interface {
RESTClient() rest.Interface
ClusterRuleGroupsGetter
GlobalRuleGroupsGetter
RuleGroupsGetter
}
// AlertingV2beta1Client is used to interact with features provided by the alerting.kubesphere.io group.
type AlertingV2beta1Client struct {
restClient rest.Interface
}
func (c *AlertingV2beta1Client) ClusterRuleGroups() ClusterRuleGroupInterface {
return newClusterRuleGroups(c)
}
func (c *AlertingV2beta1Client) GlobalRuleGroups() GlobalRuleGroupInterface {
return newGlobalRuleGroups(c)
}
func (c *AlertingV2beta1Client) RuleGroups(namespace string) RuleGroupInterface {
return newRuleGroups(c, namespace)
}
// NewForConfig creates a new AlertingV2beta1Client for the given config.
func NewForConfig(c *rest.Config) (*AlertingV2beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &AlertingV2beta1Client{client}, nil
}
// NewForConfigOrDie creates a new AlertingV2beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *AlertingV2beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new AlertingV2beta1Client for the given RESTClient.
func New(c rest.Interface) *AlertingV2beta1Client {
return &AlertingV2beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v2beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *AlertingV2beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}

View File

@@ -0,0 +1,184 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v2beta1
import (
"context"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
scheme "kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
)
// ClusterRuleGroupsGetter has a method to return a ClusterRuleGroupInterface.
// A group's client should implement this interface.
type ClusterRuleGroupsGetter interface {
ClusterRuleGroups() ClusterRuleGroupInterface
}
// ClusterRuleGroupInterface has methods to work with ClusterRuleGroup resources.
type ClusterRuleGroupInterface interface {
Create(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.CreateOptions) (*v2beta1.ClusterRuleGroup, error)
Update(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (*v2beta1.ClusterRuleGroup, error)
UpdateStatus(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (*v2beta1.ClusterRuleGroup, error)
Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
Get(ctx context.Context, name string, opts v1.GetOptions) (*v2beta1.ClusterRuleGroup, error)
List(ctx context.Context, opts v1.ListOptions) (*v2beta1.ClusterRuleGroupList, error)
Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.ClusterRuleGroup, err error)
ClusterRuleGroupExpansion
}
// clusterRuleGroups implements ClusterRuleGroupInterface
type clusterRuleGroups struct {
client rest.Interface
}
// newClusterRuleGroups returns a ClusterRuleGroups
func newClusterRuleGroups(c *AlertingV2beta1Client) *clusterRuleGroups {
return &clusterRuleGroups{
client: c.RESTClient(),
}
}
// Get takes name of the clusterRuleGroup, and returns the corresponding clusterRuleGroup object, and an error if there is any.
func (c *clusterRuleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.ClusterRuleGroup, err error) {
result = &v2beta1.ClusterRuleGroup{}
err = c.client.Get().
Resource("clusterrulegroups").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of ClusterRuleGroups that match those selectors.
func (c *clusterRuleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.ClusterRuleGroupList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v2beta1.ClusterRuleGroupList{}
err = c.client.Get().
Resource("clusterrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested clusterRuleGroups.
func (c *clusterRuleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Resource("clusterrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a clusterRuleGroup and creates it. Returns the server's representation of the clusterRuleGroup, and an error, if there is any.
func (c *clusterRuleGroups) Create(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.CreateOptions) (result *v2beta1.ClusterRuleGroup, err error) {
result = &v2beta1.ClusterRuleGroup{}
err = c.client.Post().
Resource("clusterrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Body(clusterRuleGroup).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a clusterRuleGroup and updates it. Returns the server's representation of the clusterRuleGroup, and an error, if there is any.
func (c *clusterRuleGroups) Update(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (result *v2beta1.ClusterRuleGroup, err error) {
result = &v2beta1.ClusterRuleGroup{}
err = c.client.Put().
Resource("clusterrulegroups").
Name(clusterRuleGroup.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(clusterRuleGroup).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *clusterRuleGroups) UpdateStatus(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (result *v2beta1.ClusterRuleGroup, err error) {
result = &v2beta1.ClusterRuleGroup{}
err = c.client.Put().
Resource("clusterrulegroups").
Name(clusterRuleGroup.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(clusterRuleGroup).
Do(ctx).
Into(result)
return
}
// Delete takes name of the clusterRuleGroup and deletes it. Returns an error if one occurs.
func (c *clusterRuleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
return c.client.Delete().
Resource("clusterrulegroups").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *clusterRuleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Resource("clusterrulegroups").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched clusterRuleGroup.
func (c *clusterRuleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.ClusterRuleGroup, err error) {
result = &v2beta1.ClusterRuleGroup{}
err = c.client.Patch(pt).
Resource("clusterrulegroups").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}

View File

@@ -0,0 +1,20 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
// This package has the automatically generated typed clients.
package v2beta1

View File

@@ -0,0 +1,20 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
// Package fake has the automatically generated clients.
package fake

View File

@@ -0,0 +1,48 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
v2beta1 "kubesphere.io/kubesphere/pkg/client/clientset/versioned/typed/alerting/v2beta1"
)
type FakeAlertingV2beta1 struct {
*testing.Fake
}
func (c *FakeAlertingV2beta1) ClusterRuleGroups() v2beta1.ClusterRuleGroupInterface {
return &FakeClusterRuleGroups{c}
}
func (c *FakeAlertingV2beta1) GlobalRuleGroups() v2beta1.GlobalRuleGroupInterface {
return &FakeGlobalRuleGroups{c}
}
func (c *FakeAlertingV2beta1) RuleGroups(namespace string) v2beta1.RuleGroupInterface {
return &FakeRuleGroups{c, namespace}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeAlertingV2beta1) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
}

View File

@@ -0,0 +1,133 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// FakeClusterRuleGroups implements ClusterRuleGroupInterface
type FakeClusterRuleGroups struct {
Fake *FakeAlertingV2beta1
}
var clusterrulegroupsResource = schema.GroupVersionResource{Group: "alerting.kubesphere.io", Version: "v2beta1", Resource: "clusterrulegroups"}
var clusterrulegroupsKind = schema.GroupVersionKind{Group: "alerting.kubesphere.io", Version: "v2beta1", Kind: "ClusterRuleGroup"}
// Get takes name of the clusterRuleGroup, and returns the corresponding clusterRuleGroup object, and an error if there is any.
func (c *FakeClusterRuleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.ClusterRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(clusterrulegroupsResource, name), &v2beta1.ClusterRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.ClusterRuleGroup), err
}
// List takes label and field selectors, and returns the list of ClusterRuleGroups that match those selectors.
func (c *FakeClusterRuleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.ClusterRuleGroupList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(clusterrulegroupsResource, clusterrulegroupsKind, opts), &v2beta1.ClusterRuleGroupList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v2beta1.ClusterRuleGroupList{ListMeta: obj.(*v2beta1.ClusterRuleGroupList).ListMeta}
for _, item := range obj.(*v2beta1.ClusterRuleGroupList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested clusterRuleGroups.
func (c *FakeClusterRuleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(clusterrulegroupsResource, opts))
}
// Create takes the representation of a clusterRuleGroup and creates it. Returns the server's representation of the clusterRuleGroup, and an error, if there is any.
func (c *FakeClusterRuleGroups) Create(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.CreateOptions) (result *v2beta1.ClusterRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(clusterrulegroupsResource, clusterRuleGroup), &v2beta1.ClusterRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.ClusterRuleGroup), err
}
// Update takes the representation of a clusterRuleGroup and updates it. Returns the server's representation of the clusterRuleGroup, and an error, if there is any.
func (c *FakeClusterRuleGroups) Update(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (result *v2beta1.ClusterRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(clusterrulegroupsResource, clusterRuleGroup), &v2beta1.ClusterRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.ClusterRuleGroup), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeClusterRuleGroups) UpdateStatus(ctx context.Context, clusterRuleGroup *v2beta1.ClusterRuleGroup, opts v1.UpdateOptions) (*v2beta1.ClusterRuleGroup, error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateSubresourceAction(clusterrulegroupsResource, "status", clusterRuleGroup), &v2beta1.ClusterRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.ClusterRuleGroup), err
}
// Delete takes name of the clusterRuleGroup and deletes it. Returns an error if one occurs.
func (c *FakeClusterRuleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteAction(clusterrulegroupsResource, name), &v2beta1.ClusterRuleGroup{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeClusterRuleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(clusterrulegroupsResource, listOpts)
_, err := c.Fake.Invokes(action, &v2beta1.ClusterRuleGroupList{})
return err
}
// Patch applies the patch and returns the patched clusterRuleGroup.
func (c *FakeClusterRuleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.ClusterRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(clusterrulegroupsResource, name, pt, data, subresources...), &v2beta1.ClusterRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.ClusterRuleGroup), err
}

View File

@@ -0,0 +1,133 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// FakeGlobalRuleGroups implements GlobalRuleGroupInterface
type FakeGlobalRuleGroups struct {
Fake *FakeAlertingV2beta1
}
var globalrulegroupsResource = schema.GroupVersionResource{Group: "alerting.kubesphere.io", Version: "v2beta1", Resource: "globalrulegroups"}
var globalrulegroupsKind = schema.GroupVersionKind{Group: "alerting.kubesphere.io", Version: "v2beta1", Kind: "GlobalRuleGroup"}
// Get takes name of the globalRuleGroup, and returns the corresponding globalRuleGroup object, and an error if there is any.
func (c *FakeGlobalRuleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.GlobalRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(globalrulegroupsResource, name), &v2beta1.GlobalRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.GlobalRuleGroup), err
}
// List takes label and field selectors, and returns the list of GlobalRuleGroups that match those selectors.
func (c *FakeGlobalRuleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.GlobalRuleGroupList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(globalrulegroupsResource, globalrulegroupsKind, opts), &v2beta1.GlobalRuleGroupList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v2beta1.GlobalRuleGroupList{ListMeta: obj.(*v2beta1.GlobalRuleGroupList).ListMeta}
for _, item := range obj.(*v2beta1.GlobalRuleGroupList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested globalRuleGroups.
func (c *FakeGlobalRuleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(globalrulegroupsResource, opts))
}
// Create takes the representation of a globalRuleGroup and creates it. Returns the server's representation of the globalRuleGroup, and an error, if there is any.
func (c *FakeGlobalRuleGroups) Create(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.CreateOptions) (result *v2beta1.GlobalRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(globalrulegroupsResource, globalRuleGroup), &v2beta1.GlobalRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.GlobalRuleGroup), err
}
// Update takes the representation of a globalRuleGroup and updates it. Returns the server's representation of the globalRuleGroup, and an error, if there is any.
func (c *FakeGlobalRuleGroups) Update(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (result *v2beta1.GlobalRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(globalrulegroupsResource, globalRuleGroup), &v2beta1.GlobalRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.GlobalRuleGroup), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeGlobalRuleGroups) UpdateStatus(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (*v2beta1.GlobalRuleGroup, error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateSubresourceAction(globalrulegroupsResource, "status", globalRuleGroup), &v2beta1.GlobalRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.GlobalRuleGroup), err
}
// Delete takes name of the globalRuleGroup and deletes it. Returns an error if one occurs.
func (c *FakeGlobalRuleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteAction(globalrulegroupsResource, name), &v2beta1.GlobalRuleGroup{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeGlobalRuleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(globalrulegroupsResource, listOpts)
_, err := c.Fake.Invokes(action, &v2beta1.GlobalRuleGroupList{})
return err
}
// Patch applies the patch and returns the patched globalRuleGroup.
func (c *FakeGlobalRuleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.GlobalRuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(globalrulegroupsResource, name, pt, data, subresources...), &v2beta1.GlobalRuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.GlobalRuleGroup), err
}

View File

@@ -0,0 +1,142 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// FakeRuleGroups implements RuleGroupInterface
type FakeRuleGroups struct {
Fake *FakeAlertingV2beta1
ns string
}
var rulegroupsResource = schema.GroupVersionResource{Group: "alerting.kubesphere.io", Version: "v2beta1", Resource: "rulegroups"}
var rulegroupsKind = schema.GroupVersionKind{Group: "alerting.kubesphere.io", Version: "v2beta1", Kind: "RuleGroup"}
// Get takes name of the ruleGroup, and returns the corresponding ruleGroup object, and an error if there is any.
func (c *FakeRuleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.RuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(rulegroupsResource, c.ns, name), &v2beta1.RuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.RuleGroup), err
}
// List takes label and field selectors, and returns the list of RuleGroups that match those selectors.
func (c *FakeRuleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.RuleGroupList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(rulegroupsResource, rulegroupsKind, c.ns, opts), &v2beta1.RuleGroupList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v2beta1.RuleGroupList{ListMeta: obj.(*v2beta1.RuleGroupList).ListMeta}
for _, item := range obj.(*v2beta1.RuleGroupList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested ruleGroups.
func (c *FakeRuleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(rulegroupsResource, c.ns, opts))
}
// Create takes the representation of a ruleGroup and creates it. Returns the server's representation of the ruleGroup, and an error, if there is any.
func (c *FakeRuleGroups) Create(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.CreateOptions) (result *v2beta1.RuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(rulegroupsResource, c.ns, ruleGroup), &v2beta1.RuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.RuleGroup), err
}
// Update takes the representation of a ruleGroup and updates it. Returns the server's representation of the ruleGroup, and an error, if there is any.
func (c *FakeRuleGroups) Update(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (result *v2beta1.RuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(rulegroupsResource, c.ns, ruleGroup), &v2beta1.RuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.RuleGroup), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeRuleGroups) UpdateStatus(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (*v2beta1.RuleGroup, error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(rulegroupsResource, "status", c.ns, ruleGroup), &v2beta1.RuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.RuleGroup), err
}
// Delete takes name of the ruleGroup and deletes it. Returns an error if one occurs.
func (c *FakeRuleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(rulegroupsResource, c.ns, name), &v2beta1.RuleGroup{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeRuleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(rulegroupsResource, c.ns, listOpts)
_, err := c.Fake.Invokes(action, &v2beta1.RuleGroupList{})
return err
}
// Patch applies the patch and returns the patched ruleGroup.
func (c *FakeRuleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.RuleGroup, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(rulegroupsResource, c.ns, name, pt, data, subresources...), &v2beta1.RuleGroup{})
if obj == nil {
return nil, err
}
return obj.(*v2beta1.RuleGroup), err
}

View File

@@ -0,0 +1,25 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v2beta1
type ClusterRuleGroupExpansion interface{}
type GlobalRuleGroupExpansion interface{}
type RuleGroupExpansion interface{}

View File

@@ -0,0 +1,184 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v2beta1
import (
"context"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
scheme "kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
)
// GlobalRuleGroupsGetter has a method to return a GlobalRuleGroupInterface.
// A group's client should implement this interface.
type GlobalRuleGroupsGetter interface {
GlobalRuleGroups() GlobalRuleGroupInterface
}
// GlobalRuleGroupInterface has methods to work with GlobalRuleGroup resources.
type GlobalRuleGroupInterface interface {
Create(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.CreateOptions) (*v2beta1.GlobalRuleGroup, error)
Update(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (*v2beta1.GlobalRuleGroup, error)
UpdateStatus(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (*v2beta1.GlobalRuleGroup, error)
Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
Get(ctx context.Context, name string, opts v1.GetOptions) (*v2beta1.GlobalRuleGroup, error)
List(ctx context.Context, opts v1.ListOptions) (*v2beta1.GlobalRuleGroupList, error)
Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.GlobalRuleGroup, err error)
GlobalRuleGroupExpansion
}
// globalRuleGroups implements GlobalRuleGroupInterface
type globalRuleGroups struct {
client rest.Interface
}
// newGlobalRuleGroups returns a GlobalRuleGroups
func newGlobalRuleGroups(c *AlertingV2beta1Client) *globalRuleGroups {
return &globalRuleGroups{
client: c.RESTClient(),
}
}
// Get takes name of the globalRuleGroup, and returns the corresponding globalRuleGroup object, and an error if there is any.
func (c *globalRuleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.GlobalRuleGroup, err error) {
result = &v2beta1.GlobalRuleGroup{}
err = c.client.Get().
Resource("globalrulegroups").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of GlobalRuleGroups that match those selectors.
func (c *globalRuleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.GlobalRuleGroupList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v2beta1.GlobalRuleGroupList{}
err = c.client.Get().
Resource("globalrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested globalRuleGroups.
func (c *globalRuleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Resource("globalrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a globalRuleGroup and creates it. Returns the server's representation of the globalRuleGroup, and an error, if there is any.
func (c *globalRuleGroups) Create(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.CreateOptions) (result *v2beta1.GlobalRuleGroup, err error) {
result = &v2beta1.GlobalRuleGroup{}
err = c.client.Post().
Resource("globalrulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Body(globalRuleGroup).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a globalRuleGroup and updates it. Returns the server's representation of the globalRuleGroup, and an error, if there is any.
func (c *globalRuleGroups) Update(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (result *v2beta1.GlobalRuleGroup, err error) {
result = &v2beta1.GlobalRuleGroup{}
err = c.client.Put().
Resource("globalrulegroups").
Name(globalRuleGroup.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(globalRuleGroup).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *globalRuleGroups) UpdateStatus(ctx context.Context, globalRuleGroup *v2beta1.GlobalRuleGroup, opts v1.UpdateOptions) (result *v2beta1.GlobalRuleGroup, err error) {
result = &v2beta1.GlobalRuleGroup{}
err = c.client.Put().
Resource("globalrulegroups").
Name(globalRuleGroup.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(globalRuleGroup).
Do(ctx).
Into(result)
return
}
// Delete takes name of the globalRuleGroup and deletes it. Returns an error if one occurs.
func (c *globalRuleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
return c.client.Delete().
Resource("globalrulegroups").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *globalRuleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Resource("globalrulegroups").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched globalRuleGroup.
func (c *globalRuleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.GlobalRuleGroup, err error) {
result = &v2beta1.GlobalRuleGroup{}
err = c.client.Patch(pt).
Resource("globalrulegroups").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}

View File

@@ -0,0 +1,195 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v2beta1
import (
"context"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
scheme "kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
)
// RuleGroupsGetter has a method to return a RuleGroupInterface.
// A group's client should implement this interface.
type RuleGroupsGetter interface {
RuleGroups(namespace string) RuleGroupInterface
}
// RuleGroupInterface has methods to work with RuleGroup resources.
type RuleGroupInterface interface {
Create(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.CreateOptions) (*v2beta1.RuleGroup, error)
Update(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (*v2beta1.RuleGroup, error)
UpdateStatus(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (*v2beta1.RuleGroup, error)
Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
Get(ctx context.Context, name string, opts v1.GetOptions) (*v2beta1.RuleGroup, error)
List(ctx context.Context, opts v1.ListOptions) (*v2beta1.RuleGroupList, error)
Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.RuleGroup, err error)
RuleGroupExpansion
}
// ruleGroups implements RuleGroupInterface
type ruleGroups struct {
client rest.Interface
ns string
}
// newRuleGroups returns a RuleGroups
func newRuleGroups(c *AlertingV2beta1Client, namespace string) *ruleGroups {
return &ruleGroups{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the ruleGroup, and returns the corresponding ruleGroup object, and an error if there is any.
func (c *ruleGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.RuleGroup, err error) {
result = &v2beta1.RuleGroup{}
err = c.client.Get().
Namespace(c.ns).
Resource("rulegroups").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of RuleGroups that match those selectors.
func (c *ruleGroups) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.RuleGroupList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v2beta1.RuleGroupList{}
err = c.client.Get().
Namespace(c.ns).
Resource("rulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested ruleGroups.
func (c *ruleGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("rulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a ruleGroup and creates it. Returns the server's representation of the ruleGroup, and an error, if there is any.
func (c *ruleGroups) Create(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.CreateOptions) (result *v2beta1.RuleGroup, err error) {
result = &v2beta1.RuleGroup{}
err = c.client.Post().
Namespace(c.ns).
Resource("rulegroups").
VersionedParams(&opts, scheme.ParameterCodec).
Body(ruleGroup).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a ruleGroup and updates it. Returns the server's representation of the ruleGroup, and an error, if there is any.
func (c *ruleGroups) Update(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (result *v2beta1.RuleGroup, err error) {
result = &v2beta1.RuleGroup{}
err = c.client.Put().
Namespace(c.ns).
Resource("rulegroups").
Name(ruleGroup.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(ruleGroup).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *ruleGroups) UpdateStatus(ctx context.Context, ruleGroup *v2beta1.RuleGroup, opts v1.UpdateOptions) (result *v2beta1.RuleGroup, err error) {
result = &v2beta1.RuleGroup{}
err = c.client.Put().
Namespace(c.ns).
Resource("rulegroups").
Name(ruleGroup.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(ruleGroup).
Do(ctx).
Into(result)
return
}
// Delete takes name of the ruleGroup and deletes it. Returns an error if one occurs.
func (c *ruleGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("rulegroups").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *ruleGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("rulegroups").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched ruleGroup.
func (c *ruleGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.RuleGroup, err error) {
result = &v2beta1.RuleGroup{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("rulegroups").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}

View File

@@ -0,0 +1,46 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package alerting
import (
v2beta1 "kubesphere.io/kubesphere/pkg/client/informers/externalversions/alerting/v2beta1"
internalinterfaces "kubesphere.io/kubesphere/pkg/client/informers/externalversions/internalinterfaces"
)
// Interface provides access to each of this group's versions.
type Interface interface {
// V2beta1 provides access to shared informers for resources in V2beta1.
V2beta1() v2beta1.Interface
}
type group struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}
// V2beta1 returns a new v2beta1.Interface.
func (g *group) V2beta1() v2beta1.Interface {
return v2beta1.New(g.factory, g.namespace, g.tweakListOptions)
}

View File

@@ -0,0 +1,89 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v2beta1
import (
"context"
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "k8s.io/client-go/tools/cache"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
versioned "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
internalinterfaces "kubesphere.io/kubesphere/pkg/client/informers/externalversions/internalinterfaces"
v2beta1 "kubesphere.io/kubesphere/pkg/client/listers/alerting/v2beta1"
)
// ClusterRuleGroupInformer provides access to a shared informer and lister for
// ClusterRuleGroups.
type ClusterRuleGroupInformer interface {
Informer() cache.SharedIndexInformer
Lister() v2beta1.ClusterRuleGroupLister
}
type clusterRuleGroupInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// NewClusterRuleGroupInformer constructs a new informer for ClusterRuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewClusterRuleGroupInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredClusterRuleGroupInformer(client, resyncPeriod, indexers, nil)
}
// NewFilteredClusterRuleGroupInformer constructs a new informer for ClusterRuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredClusterRuleGroupInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().ClusterRuleGroups().List(context.TODO(), options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().ClusterRuleGroups().Watch(context.TODO(), options)
},
},
&alertingv2beta1.ClusterRuleGroup{},
resyncPeriod,
indexers,
)
}
func (f *clusterRuleGroupInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredClusterRuleGroupInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *clusterRuleGroupInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&alertingv2beta1.ClusterRuleGroup{}, f.defaultInformer)
}
func (f *clusterRuleGroupInformer) Lister() v2beta1.ClusterRuleGroupLister {
return v2beta1.NewClusterRuleGroupLister(f.Informer().GetIndexer())
}

View File

@@ -0,0 +1,89 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v2beta1
import (
"context"
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "k8s.io/client-go/tools/cache"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
versioned "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
internalinterfaces "kubesphere.io/kubesphere/pkg/client/informers/externalversions/internalinterfaces"
v2beta1 "kubesphere.io/kubesphere/pkg/client/listers/alerting/v2beta1"
)
// GlobalRuleGroupInformer provides access to a shared informer and lister for
// GlobalRuleGroups.
type GlobalRuleGroupInformer interface {
Informer() cache.SharedIndexInformer
Lister() v2beta1.GlobalRuleGroupLister
}
type globalRuleGroupInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// NewGlobalRuleGroupInformer constructs a new informer for GlobalRuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewGlobalRuleGroupInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredGlobalRuleGroupInformer(client, resyncPeriod, indexers, nil)
}
// NewFilteredGlobalRuleGroupInformer constructs a new informer for GlobalRuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredGlobalRuleGroupInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().GlobalRuleGroups().List(context.TODO(), options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().GlobalRuleGroups().Watch(context.TODO(), options)
},
},
&alertingv2beta1.GlobalRuleGroup{},
resyncPeriod,
indexers,
)
}
func (f *globalRuleGroupInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredGlobalRuleGroupInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *globalRuleGroupInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&alertingv2beta1.GlobalRuleGroup{}, f.defaultInformer)
}
func (f *globalRuleGroupInformer) Lister() v2beta1.GlobalRuleGroupLister {
return v2beta1.NewGlobalRuleGroupLister(f.Informer().GetIndexer())
}

View File

@@ -0,0 +1,59 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v2beta1
import (
internalinterfaces "kubesphere.io/kubesphere/pkg/client/informers/externalversions/internalinterfaces"
)
// Interface provides access to all the informers in this group version.
type Interface interface {
// ClusterRuleGroups returns a ClusterRuleGroupInformer.
ClusterRuleGroups() ClusterRuleGroupInformer
// GlobalRuleGroups returns a GlobalRuleGroupInformer.
GlobalRuleGroups() GlobalRuleGroupInformer
// RuleGroups returns a RuleGroupInformer.
RuleGroups() RuleGroupInformer
}
type version struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}
// ClusterRuleGroups returns a ClusterRuleGroupInformer.
func (v *version) ClusterRuleGroups() ClusterRuleGroupInformer {
return &clusterRuleGroupInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
// GlobalRuleGroups returns a GlobalRuleGroupInformer.
func (v *version) GlobalRuleGroups() GlobalRuleGroupInformer {
return &globalRuleGroupInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
// RuleGroups returns a RuleGroupInformer.
func (v *version) RuleGroups() RuleGroupInformer {
return &ruleGroupInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

View File

@@ -0,0 +1,90 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v2beta1
import (
"context"
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "k8s.io/client-go/tools/cache"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
versioned "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
internalinterfaces "kubesphere.io/kubesphere/pkg/client/informers/externalversions/internalinterfaces"
v2beta1 "kubesphere.io/kubesphere/pkg/client/listers/alerting/v2beta1"
)
// RuleGroupInformer provides access to a shared informer and lister for
// RuleGroups.
type RuleGroupInformer interface {
Informer() cache.SharedIndexInformer
Lister() v2beta1.RuleGroupLister
}
type ruleGroupInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
namespace string
}
// NewRuleGroupInformer constructs a new informer for RuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewRuleGroupInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredRuleGroupInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredRuleGroupInformer constructs a new informer for RuleGroup type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredRuleGroupInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().RuleGroups(namespace).List(context.TODO(), options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AlertingV2beta1().RuleGroups(namespace).Watch(context.TODO(), options)
},
},
&alertingv2beta1.RuleGroup{},
resyncPeriod,
indexers,
)
}
func (f *ruleGroupInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredRuleGroupInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *ruleGroupInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&alertingv2beta1.RuleGroup{}, f.defaultInformer)
}
func (f *ruleGroupInformer) Lister() v2beta1.RuleGroupLister {
return v2beta1.NewRuleGroupLister(f.Informer().GetIndexer())
}

View File

@@ -28,6 +28,7 @@ import (
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
versioned "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
alerting "kubesphere.io/kubesphere/pkg/client/informers/externalversions/alerting"
application "kubesphere.io/kubesphere/pkg/client/informers/externalversions/application"
auditing "kubesphere.io/kubesphere/pkg/client/informers/externalversions/auditing"
cluster "kubesphere.io/kubesphere/pkg/client/informers/externalversions/cluster"
@@ -183,6 +184,7 @@ type SharedInformerFactory interface {
ForResource(resource schema.GroupVersionResource) (GenericInformer, error)
WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool
Alerting() alerting.Interface
Application() application.Interface
Auditing() auditing.Interface
Cluster() cluster.Interface
@@ -197,6 +199,10 @@ type SharedInformerFactory interface {
Types() types.Interface
}
func (f *sharedInformerFactory) Alerting() alerting.Interface {
return alerting.New(f, f.namespace, f.tweakListOptions)
}
func (f *sharedInformerFactory) Application() application.Interface {
return application.New(f, f.namespace, f.tweakListOptions)
}

View File

@@ -23,6 +23,7 @@ import (
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
v1alpha1 "kubesphere.io/api/application/v1alpha1"
auditingv1alpha1 "kubesphere.io/api/auditing/v1alpha1"
clusterv1alpha1 "kubesphere.io/api/cluster/v1alpha1"
@@ -30,7 +31,7 @@ import (
v1alpha3 "kubesphere.io/api/devops/v1alpha3"
v1alpha2 "kubesphere.io/api/iam/v1alpha2"
networkv1alpha1 "kubesphere.io/api/network/v1alpha1"
v2beta1 "kubesphere.io/api/notification/v2beta1"
notificationv2beta1 "kubesphere.io/api/notification/v2beta1"
v2beta2 "kubesphere.io/api/notification/v2beta2"
quotav1alpha2 "kubesphere.io/api/quota/v1alpha2"
servicemeshv1alpha2 "kubesphere.io/api/servicemesh/v1alpha2"
@@ -67,7 +68,15 @@ func (f *genericInformer) Lister() cache.GenericLister {
// TODO extend this to unknown resources with a client pool
func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {
switch resource {
// Group=application.kubesphere.io, Version=v1alpha1
// Group=alerting.kubesphere.io, Version=v2beta1
case v2beta1.SchemeGroupVersion.WithResource("clusterrulegroups"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Alerting().V2beta1().ClusterRuleGroups().Informer()}, nil
case v2beta1.SchemeGroupVersion.WithResource("globalrulegroups"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Alerting().V2beta1().GlobalRuleGroups().Informer()}, nil
case v2beta1.SchemeGroupVersion.WithResource("rulegroups"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Alerting().V2beta1().RuleGroups().Informer()}, nil
// Group=application.kubesphere.io, Version=v1alpha1
case v1alpha1.SchemeGroupVersion.WithResource("helmapplications"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Application().V1alpha1().HelmApplications().Informer()}, nil
case v1alpha1.SchemeGroupVersion.WithResource("helmapplicationversions"):
@@ -136,9 +145,9 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource
return &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1alpha1().NamespaceNetworkPolicies().Informer()}, nil
// Group=notification.kubesphere.io, Version=v2beta1
case v2beta1.SchemeGroupVersion.WithResource("configs"):
case notificationv2beta1.SchemeGroupVersion.WithResource("configs"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Notification().V2beta1().Configs().Informer()}, nil
case v2beta1.SchemeGroupVersion.WithResource("receivers"):
case notificationv2beta1.SchemeGroupVersion.WithResource("receivers"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Notification().V2beta1().Receivers().Informer()}, nil
// Group=notification.kubesphere.io, Version=v2beta2

View File

@@ -0,0 +1,68 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v2beta1
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// ClusterRuleGroupLister helps list ClusterRuleGroups.
// All objects returned here must be treated as read-only.
type ClusterRuleGroupLister interface {
// List lists all ClusterRuleGroups in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v2beta1.ClusterRuleGroup, err error)
// Get retrieves the ClusterRuleGroup from the index for a given name.
// Objects returned here must be treated as read-only.
Get(name string) (*v2beta1.ClusterRuleGroup, error)
ClusterRuleGroupListerExpansion
}
// clusterRuleGroupLister implements the ClusterRuleGroupLister interface.
type clusterRuleGroupLister struct {
indexer cache.Indexer
}
// NewClusterRuleGroupLister returns a new ClusterRuleGroupLister.
func NewClusterRuleGroupLister(indexer cache.Indexer) ClusterRuleGroupLister {
return &clusterRuleGroupLister{indexer: indexer}
}
// List lists all ClusterRuleGroups in the indexer.
func (s *clusterRuleGroupLister) List(selector labels.Selector) (ret []*v2beta1.ClusterRuleGroup, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v2beta1.ClusterRuleGroup))
})
return ret, err
}
// Get retrieves the ClusterRuleGroup from the index for a given name.
func (s *clusterRuleGroupLister) Get(name string) (*v2beta1.ClusterRuleGroup, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v2beta1.Resource("clusterrulegroup"), name)
}
return obj.(*v2beta1.ClusterRuleGroup), nil
}

View File

@@ -0,0 +1,35 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v2beta1
// ClusterRuleGroupListerExpansion allows custom methods to be added to
// ClusterRuleGroupLister.
type ClusterRuleGroupListerExpansion interface{}
// GlobalRuleGroupListerExpansion allows custom methods to be added to
// GlobalRuleGroupLister.
type GlobalRuleGroupListerExpansion interface{}
// RuleGroupListerExpansion allows custom methods to be added to
// RuleGroupLister.
type RuleGroupListerExpansion interface{}
// RuleGroupNamespaceListerExpansion allows custom methods to be added to
// RuleGroupNamespaceLister.
type RuleGroupNamespaceListerExpansion interface{}

View File

@@ -0,0 +1,68 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v2beta1
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// GlobalRuleGroupLister helps list GlobalRuleGroups.
// All objects returned here must be treated as read-only.
type GlobalRuleGroupLister interface {
// List lists all GlobalRuleGroups in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v2beta1.GlobalRuleGroup, err error)
// Get retrieves the GlobalRuleGroup from the index for a given name.
// Objects returned here must be treated as read-only.
Get(name string) (*v2beta1.GlobalRuleGroup, error)
GlobalRuleGroupListerExpansion
}
// globalRuleGroupLister implements the GlobalRuleGroupLister interface.
type globalRuleGroupLister struct {
indexer cache.Indexer
}
// NewGlobalRuleGroupLister returns a new GlobalRuleGroupLister.
func NewGlobalRuleGroupLister(indexer cache.Indexer) GlobalRuleGroupLister {
return &globalRuleGroupLister{indexer: indexer}
}
// List lists all GlobalRuleGroups in the indexer.
func (s *globalRuleGroupLister) List(selector labels.Selector) (ret []*v2beta1.GlobalRuleGroup, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v2beta1.GlobalRuleGroup))
})
return ret, err
}
// Get retrieves the GlobalRuleGroup from the index for a given name.
func (s *globalRuleGroupLister) Get(name string) (*v2beta1.GlobalRuleGroup, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v2beta1.Resource("globalrulegroup"), name)
}
return obj.(*v2beta1.GlobalRuleGroup), nil
}

View File

@@ -0,0 +1,99 @@
/*
Copyright 2020 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v2beta1
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
v2beta1 "kubesphere.io/api/alerting/v2beta1"
)
// RuleGroupLister helps list RuleGroups.
// All objects returned here must be treated as read-only.
type RuleGroupLister interface {
// List lists all RuleGroups in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v2beta1.RuleGroup, err error)
// RuleGroups returns an object that can list and get RuleGroups.
RuleGroups(namespace string) RuleGroupNamespaceLister
RuleGroupListerExpansion
}
// ruleGroupLister implements the RuleGroupLister interface.
type ruleGroupLister struct {
indexer cache.Indexer
}
// NewRuleGroupLister returns a new RuleGroupLister.
func NewRuleGroupLister(indexer cache.Indexer) RuleGroupLister {
return &ruleGroupLister{indexer: indexer}
}
// List lists all RuleGroups in the indexer.
func (s *ruleGroupLister) List(selector labels.Selector) (ret []*v2beta1.RuleGroup, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v2beta1.RuleGroup))
})
return ret, err
}
// RuleGroups returns an object that can list and get RuleGroups.
func (s *ruleGroupLister) RuleGroups(namespace string) RuleGroupNamespaceLister {
return ruleGroupNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// RuleGroupNamespaceLister helps list and get RuleGroups.
// All objects returned here must be treated as read-only.
type RuleGroupNamespaceLister interface {
// List lists all RuleGroups in the indexer for a given namespace.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v2beta1.RuleGroup, err error)
// Get retrieves the RuleGroup from the indexer for a given namespace and name.
// Objects returned here must be treated as read-only.
Get(name string) (*v2beta1.RuleGroup, error)
RuleGroupNamespaceListerExpansion
}
// ruleGroupNamespaceLister implements the RuleGroupNamespaceLister
// interface.
type ruleGroupNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all RuleGroups in the indexer for a given namespace.
func (s ruleGroupNamespaceLister) List(selector labels.Selector) (ret []*v2beta1.RuleGroup, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v2beta1.RuleGroup))
})
return ret, err
}
// Get retrieves the RuleGroup from the indexer for a given namespace and name.
func (s ruleGroupNamespaceLister) Get(name string) (*v2beta1.RuleGroup, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v2beta1.Resource("rulegroup"), name)
}
return obj.(*v2beta1.RuleGroup), nil
}

View File

@@ -0,0 +1,149 @@
/*
Copyright 2020 KubeSphere Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v2beta1
import (
"github.com/emicklei/go-restful"
"k8s.io/klog"
kapi "kubesphere.io/kubesphere/pkg/api"
"kubesphere.io/kubesphere/pkg/apiserver/query"
kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
alertingmodels "kubesphere.io/kubesphere/pkg/models/alerting"
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
)
type handler struct {
operator alertingmodels.RuleGroupOperator
}
func newHandler(ksclient kubesphere.Interface, ruleClient alerting.RuleClient) *handler {
return &handler{
operator: alertingmodels.NewRuleGroupOperator(ksclient, ruleClient),
}
}
func (h *handler) handleListRuleGroups(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace")
query := query.ParseQueryParameter(req)
result, err := h.operator.ListRuleGroups(req.Request.Context(), namespace, query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleGetRuleGroup(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace")
name := req.PathParameter("name")
result, err := h.operator.GetRuleGroup(req.Request.Context(), namespace, name)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleListAlerts(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace")
query := query.ParseQueryParameter(req)
result, err := h.operator.ListAlerts(req.Request.Context(), namespace, query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleListClusterRuleGroups(req *restful.Request, resp *restful.Response) {
query := query.ParseQueryParameter(req)
result, err := h.operator.ListClusterRuleGroups(req.Request.Context(), query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleGetClusterRuleGroup(req *restful.Request, resp *restful.Response) {
name := req.PathParameter("name")
result, err := h.operator.GetClusterRuleGroup(req.Request.Context(), name)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleListClusterAlerts(req *restful.Request, resp *restful.Response) {
query := query.ParseQueryParameter(req)
result, err := h.operator.ListClusterAlerts(req.Request.Context(), query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleListGlobalRuleGroups(req *restful.Request, resp *restful.Response) {
query := query.ParseQueryParameter(req)
result, err := h.operator.ListGlobalRuleGroups(req.Request.Context(), query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleGetGlobalRuleGroup(req *restful.Request, resp *restful.Response) {
name := req.PathParameter("name")
result, err := h.operator.GetGlobalRuleGroup(req.Request.Context(), name)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}
func (h *handler) handleListGlobalAlerts(req *restful.Request, resp *restful.Response) {
query := query.ParseQueryParameter(req)
result, err := h.operator.ListGlobalAlerts(req.Request.Context(), query)
if err != nil {
klog.Error(err)
kapi.HandleError(resp, req, err)
return
}
resp.WriteEntity(result)
}

View File

@@ -0,0 +1,135 @@
/*
Copyright 2020 KubeSphere Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v2beta1
import (
"net/http"
"github.com/emicklei/go-restful"
restfulspec "github.com/emicklei/go-restful-openapi"
alertingv2beta1 "kubesphere.io/api/alerting/v2beta1"
kapi "kubesphere.io/kubesphere/pkg/api"
kapialertingv2beta1 "kubesphere.io/kubesphere/pkg/api/alerting/v2beta1"
"kubesphere.io/kubesphere/pkg/apiserver/query"
"kubesphere.io/kubesphere/pkg/apiserver/runtime"
kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
)
func AddToContainer(container *restful.Container, ksclient kubesphere.Interface, ruleClient alerting.RuleClient) error {
ws := runtime.NewWebService(alertingv2beta1.SchemeGroupVersion)
handler := newHandler(ksclient, ruleClient)
ws.Route(ws.GET("/namespaces/{namespace}/rulegroups").
To(handler.handleListRuleGroups).
Doc("list the rulegroups in the specified namespace").
Param(ws.QueryParameter(query.ParameterName, "name used to do filtering").Required(false)).
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, e.g. orderBy=createTime")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state of a rulegroup, one of `firing`, `pending`, `inactive` depending on its rules")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/namespaces/{namespace}/rulegroups/{name}").
To(handler.handleGetRuleGroup).
Doc("get the rulegroup with the specified name in the specified namespace").
Returns(http.StatusOK, kapi.StatusOK, kapialertingv2beta1.RuleGroup{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/namespaces/{namespace}/alerts").
To(handler.handleListAlerts).
Doc("list the alerts in the specified namespace").
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, one of `activeAt`. e.g. orderBy=activeAt")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state, one of `firing`, `pending`")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldAlertLabelFilters, "label filters, concatenating multiple filters with commas, equal symbol for exact query, wave symbol for fuzzy query e.g. name~a").DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/clusterrulegroups").
To(handler.handleListClusterRuleGroups).
Doc("list the clusterrulegroups").
Param(ws.QueryParameter(query.ParameterName, "name used to do filtering").Required(false)).
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, e.g. orderBy=createTime")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state of a rulegroup, one of `firing`, `pending`, `inactive` depending on its rules")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/clusterrulegroups/{name}").
To(handler.handleGetClusterRuleGroup).
Doc("get the clusterrulegroup with the specified name").
Returns(http.StatusOK, kapi.StatusOK, kapialertingv2beta1.RuleGroup{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/clusteralerts").
To(handler.handleListClusterAlerts).
Doc("list the alerts of clusterrulegroups in the cluster").
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, one of `activeAt`. e.g. orderBy=activeAt")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state, one of `firing`, `pending`")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldAlertLabelFilters, "label filters, concatenating multiple filters with commas, equal symbol for exact query, wave symbol for fuzzy query e.g. name~a").DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/globalrulegroups").
To(handler.handleListGlobalRuleGroups).
Doc("list the globalrulegroups").
Param(ws.QueryParameter(query.ParameterName, "name used to do filtering").Required(false)).
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, e.g. orderBy=createTime")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state of a rulegroup, one of `firing`, `pending`, `inactive` depending on its rules")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/globalrulegroups/{name}").
To(handler.handleGetGlobalRuleGroup).
Doc("get the globalrulegroup with the specified name").
Returns(http.StatusOK, kapi.StatusOK, kapialertingv2beta1.RuleGroup{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/globalalerts").
To(handler.handleListGlobalAlerts).
Doc("list the alerts of globalrulegroups in the cluster").
Param(ws.QueryParameter(query.ParameterPage, "page").Required(false).DataFormat("page=%d").DefaultValue("page=1")).
Param(ws.QueryParameter(query.ParameterLimit, "limit").Required(false)).
Param(ws.QueryParameter(query.ParameterAscending, "sort parameters, e.g. reverse=true").Required(false).DefaultValue("ascending=false")).
Param(ws.QueryParameter(query.ParameterOrderBy, "sort parameters, one of `activeAt`. e.g. orderBy=activeAt")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldState, "state, one of `firing`, `pending`")).
Param(ws.QueryParameter(kapialertingv2beta1.FieldAlertLabelFilters, "label filters, concatenating multiple filters with commas, equal symbol for exact query, wave symbol for fuzzy query e.g. name~a").DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, kapi.StatusOK, kapi.ListResult{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
container.Add(ws)
return nil
}

View File

@@ -0,0 +1,620 @@
// Copyright 2022 The KubeSphere Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package alerting
import (
"context"
promlabels "github.com/prometheus/prometheus/pkg/labels"
promrules "github.com/prometheus/prometheus/rules"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"kubesphere.io/kubesphere/pkg/api"
kapialertingv2beta1 "kubesphere.io/kubesphere/pkg/api/alerting/v2beta1"
"kubesphere.io/kubesphere/pkg/apiserver/query"
kubesphere "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
controller "kubesphere.io/kubesphere/pkg/controller/alerting"
resources "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
)
type RuleGroupOperator interface {
ListRuleGroups(ctx context.Context, namespace string, queryParam *query.Query) (*api.ListResult, error)
GetRuleGroup(ctx context.Context, namespace, name string) (*kapialertingv2beta1.RuleGroup, error)
ListAlerts(ctx context.Context, namespace string, queryParam *query.Query) (*api.ListResult, error)
ListGlobalRuleGroups(ctx context.Context, queryParam *query.Query) (*api.ListResult, error)
GetGlobalRuleGroup(ctx context.Context, name string) (*kapialertingv2beta1.GlobalRuleGroup, error)
ListGlobalAlerts(ctx context.Context, queryParam *query.Query) (*api.ListResult, error)
ListClusterRuleGroups(ctx context.Context, queryParam *query.Query) (*api.ListResult, error)
GetClusterRuleGroup(ctx context.Context, name string) (*kapialertingv2beta1.ClusterRuleGroup, error)
ListClusterAlerts(ctx context.Context, queryParam *query.Query) (*api.ListResult, error)
}
func NewRuleGroupOperator(ksclient kubesphere.Interface, ruleClient alerting.RuleClient) RuleGroupOperator {
return &ruleGroupOperator{
ksclient: ksclient,
ruleClient: ruleClient,
}
}
type ruleGroupOperator struct {
ruleClient alerting.RuleClient
ksclient kubesphere.Interface
}
func (o *ruleGroupOperator) listRuleGroups(ctx context.Context, namespace string, selector labels.Selector) ([]runtime.Object, error) {
resourceRuleGroups, err := o.ksclient.AlertingV2beta1().RuleGroups(namespace).List(ctx,
metav1.ListOptions{
LabelSelector: selector.String(),
})
if err != nil {
return nil, err
}
// get rules matching '{rule_level="namespace",namespace="<namespace>"}' from thanos ruler
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelNamesapce),
}, {
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyNamespace,
Value: namespace,
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
var statusRuleGroupMap = make(map[string]*alerting.RuleGroup)
for i := range statusRuleGroups {
g := statusRuleGroups[i]
// the matchers only filter rules and all groups still return,
// and some of them may be with empty rules, so here check them and skip some.
if len(g.Rules) == 0 {
continue
}
if _, ok := statusRuleGroupMap[g.Name]; !ok {
statusRuleGroupMap[g.Name] = g
}
}
// copy status info of statusRuleGroups to matched rulegroups
var groups = make([]runtime.Object, len(resourceRuleGroups.Items))
for i := range resourceRuleGroups.Items {
g := &kapialertingv2beta1.RuleGroup{
RuleGroup: resourceRuleGroups.Items[i],
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
statusg, ok := statusRuleGroupMap[g.Name]
if ok && len(statusg.Rules) == len(g.Spec.Rules) { // assure that they are the same rulegroups
copyRuleGroupStatus(statusg, &g.Status)
}
groups[i] = g
}
return groups, nil
}
func (o *ruleGroupOperator) ListRuleGroups(ctx context.Context, namespace string,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listRuleGroups(ctx, namespace, queryParam.Selector())
if err != nil {
return nil, err
}
return resources.DefaultList(groups, queryParam, func(left, right runtime.Object, field query.Field) bool {
hit, great := o.compareRuleGroupStatus(
&(left.(*kapialertingv2beta1.RuleGroup).Status), &(right.(*kapialertingv2beta1.RuleGroup).Status), field)
if hit {
return great
}
return resources.DefaultObjectMetaCompare(
left.(*kapialertingv2beta1.RuleGroup).ObjectMeta, right.(*kapialertingv2beta1.RuleGroup).ObjectMeta, field)
}, func(obj runtime.Object, filter query.Filter) bool {
hit, selected := o.filterRuleGroupStatus(&obj.(*kapialertingv2beta1.RuleGroup).Status, filter)
if hit {
return selected
}
return resources.DefaultObjectMetaFilter(obj.(*kapialertingv2beta1.RuleGroup).ObjectMeta, filter)
}), nil
}
// compareRuleGroupStatus compare rulegroup status.
// if field in status, return hit(true) and great(true if left great than right, else false).
// if filed not in status, return hit(false) and great(false, should be unuseful).
func (d *ruleGroupOperator) compareRuleGroupStatus(left, right *kapialertingv2beta1.RuleGroupStatus, field query.Field) (hit, great bool) {
switch field {
case kapialertingv2beta1.FieldRuleGroupEvaluationTime:
hit = true
if left.EvaluationTime == nil {
great = false
} else if right.EvaluationTime == nil {
great = true
} else {
great = *left.EvaluationTime > *right.EvaluationTime
}
case kapialertingv2beta1.FieldRuleGroupLastEvaluation:
hit = true
if left.LastEvaluation == nil {
great = false
} else if right.LastEvaluation == nil {
great = true
} else {
great = left.LastEvaluation.After(*right.LastEvaluation)
}
}
return
}
// filterRuleGroupStatus filters by rulegroup status.
// if field in status, return hit(true) and selected(true if match the filter, else false).
// if filed not in status, return hit(false) and selected(false, should be unuseful).
func (d *ruleGroupOperator) filterRuleGroupStatus(status *kapialertingv2beta1.RuleGroupStatus, filter query.Filter) (hit, selected bool) {
switch filter.Field {
case kapialertingv2beta1.FieldState:
hit = true
selected = status.State == string(filter.Value)
}
return
}
func (o *ruleGroupOperator) ListAlerts(ctx context.Context, namespace string,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listRuleGroups(ctx, namespace, labels.Everything())
if err != nil {
return nil, err
}
// encapsulated as runtime.Object for easy comparison and filtering.
var alerts []runtime.Object
for i := range groups {
g := groups[i].(*kapialertingv2beta1.RuleGroup)
for j := range g.Status.RulesStatus {
ruleStatus := g.Status.RulesStatus[j]
for k := range ruleStatus.Alerts {
alerts = append(alerts, &wrapAlert{Alert: *ruleStatus.Alerts[k]})
}
}
}
filterAlert := o.createFilterAlertFunc(queryParam)
listResult := resources.DefaultList(alerts, queryParam, func(left, right runtime.Object, field query.Field) bool {
return o.compareAlert(&left.(*wrapAlert).Alert, &right.(*wrapAlert).Alert, field)
}, func(obj runtime.Object, filter query.Filter) bool {
return filterAlert(&obj.(*wrapAlert).Alert, filter)
})
for i := range listResult.Items {
listResult.Items[i] = &listResult.Items[i].(*wrapAlert).Alert
}
return listResult, nil
}
func (d *ruleGroupOperator) compareAlert(left, right *kapialertingv2beta1.Alert, field query.Field) bool {
switch field {
case kapialertingv2beta1.FieldAlertActiveAt:
if left.ActiveAt == nil {
return false
}
if right.ActiveAt == nil {
return true
}
return left.ActiveAt.After(*right.ActiveAt)
}
return false
}
func (d *ruleGroupOperator) createFilterAlertFunc(queryParam *query.Query) func(alert *kapialertingv2beta1.Alert, filter query.Filter) bool {
var labelFilters kapialertingv2beta1.LabelFilters
if len(queryParam.Filters) > 0 {
if filters, ok := queryParam.Filters[kapialertingv2beta1.FieldAlertLabelFilters]; ok {
labelFilters = kapialertingv2beta1.ParseLabelFilters(string(filters))
}
}
return func(alert *kapialertingv2beta1.Alert, filter query.Filter) bool {
switch filter.Field {
case kapialertingv2beta1.FieldAlertLabelFilters:
if labelFilters == nil {
return true
}
return labelFilters.Matches(alert.Labels)
case kapialertingv2beta1.FieldState:
return alert.State == string(filter.Value)
}
return false
}
}
func (o *ruleGroupOperator) GetRuleGroup(ctx context.Context, namespace, name string) (*kapialertingv2beta1.RuleGroup, error) {
resourceRuleGroup, err := o.ksclient.AlertingV2beta1().RuleGroups(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
ret := &kapialertingv2beta1.RuleGroup{
RuleGroup: *resourceRuleGroup,
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelNamesapce),
}, {
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyNamespace,
Value: namespace,
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
for _, g := range statusRuleGroups {
if g.Name == resourceRuleGroup.Name && len(g.Rules) == len(resourceRuleGroup.Spec.Rules) {
copyRuleGroupStatus(g, &ret.Status)
break
}
}
return ret, nil
}
func (o *ruleGroupOperator) listClusterRuleGroups(ctx context.Context, selector labels.Selector) ([]runtime.Object, error) {
resourceRuleGroups, err := o.ksclient.AlertingV2beta1().ClusterRuleGroups().List(ctx, metav1.ListOptions{
LabelSelector: selector.String(),
})
if err != nil {
return nil, err
}
// get rules matching '{rule_level="cluster"}' from thanos ruler
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelCluster),
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
var statusRuleGroupMap = make(map[string]*alerting.RuleGroup)
for i := range statusRuleGroups {
g := statusRuleGroups[i]
// the matchers only filter rules and all groups still return,
// and some of them may be with empty rules, so here check them and skip some.
if len(g.Rules) == 0 {
continue
}
if _, ok := statusRuleGroupMap[g.Name]; !ok {
statusRuleGroupMap[g.Name] = g
}
}
// copy status info of statusRuleGroups to matched rulegroups
var groups = make([]runtime.Object, len(resourceRuleGroups.Items))
for i := range resourceRuleGroups.Items {
g := &kapialertingv2beta1.ClusterRuleGroup{
ClusterRuleGroup: resourceRuleGroups.Items[i],
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
statusg, ok := statusRuleGroupMap[g.Name]
if ok && len(statusg.Rules) == len(g.Spec.Rules) {
copyRuleGroupStatus(statusg, &g.Status)
}
groups[i] = g
}
return groups, nil
}
func (o *ruleGroupOperator) ListClusterRuleGroups(ctx context.Context,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listClusterRuleGroups(ctx, queryParam.Selector())
if err != nil {
return nil, err
}
return resources.DefaultList(groups, queryParam, func(left, right runtime.Object, field query.Field) bool {
hit, great := o.compareRuleGroupStatus(
&(left.(*kapialertingv2beta1.ClusterRuleGroup).Status), &(right.(*kapialertingv2beta1.ClusterRuleGroup).Status), field)
if hit {
return great
}
return resources.DefaultObjectMetaCompare(
left.(*kapialertingv2beta1.ClusterRuleGroup).ObjectMeta, right.(*kapialertingv2beta1.ClusterRuleGroup).ObjectMeta, field)
}, func(obj runtime.Object, filter query.Filter) bool {
hit, selected := o.filterRuleGroupStatus(&obj.(*kapialertingv2beta1.ClusterRuleGroup).Status, filter)
if hit {
return selected
}
return resources.DefaultObjectMetaFilter(obj.(*kapialertingv2beta1.ClusterRuleGroup).ObjectMeta, filter)
}), nil
}
func (o *ruleGroupOperator) ListClusterAlerts(ctx context.Context,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listClusterRuleGroups(ctx, labels.Everything())
if err != nil {
return nil, err
}
// encapsulated as runtime.Object for easy comparison and filtering.
var alerts []runtime.Object
for i := range groups {
g := groups[i].(*kapialertingv2beta1.ClusterRuleGroup)
for j := range g.Status.RulesStatus {
ruleStatus := g.Status.RulesStatus[j]
for k := range ruleStatus.Alerts {
alerts = append(alerts, &wrapAlert{Alert: *ruleStatus.Alerts[k]})
}
}
}
filterAlert := o.createFilterAlertFunc(queryParam)
listResult := resources.DefaultList(alerts, queryParam, func(left, right runtime.Object, field query.Field) bool {
return o.compareAlert(&left.(*wrapAlert).Alert, &right.(*wrapAlert).Alert, field)
}, func(obj runtime.Object, filter query.Filter) bool {
return filterAlert(&obj.(*wrapAlert).Alert, filter)
})
for i := range listResult.Items {
listResult.Items[i] = &listResult.Items[i].(*wrapAlert).Alert
}
return listResult, nil
}
func (o *ruleGroupOperator) GetClusterRuleGroup(ctx context.Context, name string) (*kapialertingv2beta1.ClusterRuleGroup, error) {
resourceRuleGroup, err := o.ksclient.AlertingV2beta1().ClusterRuleGroups().Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
ret := &kapialertingv2beta1.ClusterRuleGroup{
ClusterRuleGroup: *resourceRuleGroup,
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelCluster),
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
for _, g := range statusRuleGroups {
if g.Name == resourceRuleGroup.Name && len(g.Rules) == len(resourceRuleGroup.Spec.Rules) {
copyRuleGroupStatus(g, &ret.Status)
break
}
}
return ret, nil
}
func (o *ruleGroupOperator) listGlobalRuleGroups(ctx context.Context, selector labels.Selector) ([]runtime.Object, error) {
resourceRuleGroups, err := o.ksclient.AlertingV2beta1().GlobalRuleGroups().List(ctx,
metav1.ListOptions{
LabelSelector: selector.String(),
})
if err != nil {
return nil, err
}
// get rules matching '{rule_level="global"}' from thanos ruler
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelGlobal),
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
var statusRuleGroupMap = make(map[string]*alerting.RuleGroup)
for i := range statusRuleGroups {
g := statusRuleGroups[i]
// the matchers only filter rules and all groups still return,
// and some of them may be with empty rules, so here check them and skip some.
if len(g.Rules) == 0 {
continue
}
if _, ok := statusRuleGroupMap[g.Name]; !ok {
statusRuleGroupMap[g.Name] = g
}
}
// copy status info of statusRuleGroups to matched rulegroups
var groups = make([]runtime.Object, len(resourceRuleGroups.Items))
for i := range resourceRuleGroups.Items {
g := &kapialertingv2beta1.GlobalRuleGroup{
GlobalRuleGroup: resourceRuleGroups.Items[i],
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
statusg, ok := statusRuleGroupMap[g.Name]
if ok && len(statusg.Rules) == len(g.Spec.Rules) {
copyRuleGroupStatus(statusg, &g.Status)
}
groups[i] = g
}
return groups, nil
}
func (o *ruleGroupOperator) ListGlobalRuleGroups(ctx context.Context,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listGlobalRuleGroups(ctx, queryParam.Selector())
if err != nil {
return nil, err
}
return resources.DefaultList(groups, queryParam, func(left, right runtime.Object, field query.Field) bool {
hit, great := o.compareRuleGroupStatus(
&(left.(*kapialertingv2beta1.GlobalRuleGroup).Status), &(right.(*kapialertingv2beta1.GlobalRuleGroup).Status), field)
if hit {
return great
}
return resources.DefaultObjectMetaCompare(
left.(*kapialertingv2beta1.GlobalRuleGroup).ObjectMeta, right.(*kapialertingv2beta1.GlobalRuleGroup).ObjectMeta, field)
}, func(obj runtime.Object, filter query.Filter) bool {
hit, selected := o.filterRuleGroupStatus(&obj.(*kapialertingv2beta1.GlobalRuleGroup).Status, filter)
if hit {
return selected
}
return resources.DefaultObjectMetaFilter(obj.(*kapialertingv2beta1.GlobalRuleGroup).ObjectMeta, filter)
}), nil
}
func (o *ruleGroupOperator) ListGlobalAlerts(ctx context.Context,
queryParam *query.Query) (*api.ListResult, error) {
groups, err := o.listGlobalRuleGroups(ctx, labels.Everything())
if err != nil {
return nil, err
}
// encapsulated as runtime.Object for easy comparison and filtering.
var alerts []runtime.Object
for i := range groups {
wrapg := groups[i].(*kapialertingv2beta1.GlobalRuleGroup)
for j := range wrapg.Status.RulesStatus {
ruleStatus := wrapg.Status.RulesStatus[j]
for k := range ruleStatus.Alerts {
alerts = append(alerts, &wrapAlert{Alert: *ruleStatus.Alerts[k]})
}
}
}
filterAlert := o.createFilterAlertFunc(queryParam)
listResult := resources.DefaultList(alerts, queryParam, func(left, right runtime.Object, field query.Field) bool {
return o.compareAlert(&left.(*wrapAlert).Alert, &right.(*wrapAlert).Alert, field)
}, func(obj runtime.Object, filter query.Filter) bool {
return filterAlert(&obj.(*wrapAlert).Alert, filter)
})
for i := range listResult.Items {
listResult.Items[i] = &listResult.Items[i].(*wrapAlert).Alert
}
return listResult, nil
}
func (o *ruleGroupOperator) GetGlobalRuleGroup(ctx context.Context, name string) (*kapialertingv2beta1.GlobalRuleGroup, error) {
resourceRuleGroup, err := o.ksclient.AlertingV2beta1().GlobalRuleGroups().Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
ret := &kapialertingv2beta1.GlobalRuleGroup{
GlobalRuleGroup: *resourceRuleGroup,
Status: kapialertingv2beta1.RuleGroupStatus{
State: promrules.StateInactive.String(),
},
}
matchers := []*promlabels.Matcher{{
Type: promlabels.MatchEqual,
Name: controller.RuleLabelKeyRuleLevel,
Value: string(controller.RuleLevelGlobal),
}}
statusRuleGroups, err := o.ruleClient.ThanosRules(ctx, matchers)
if err != nil {
return nil, err
}
for _, g := range statusRuleGroups {
if g.Name == resourceRuleGroup.Name && len(g.Rules) == len(resourceRuleGroup.Spec.Rules) {
copyRuleGroupStatus(g, &ret.Status)
break
}
}
return ret, nil
}
// copyRuleGroupStatus copies group/rule status and alerts from source to target
func copyRuleGroupStatus(source *alerting.RuleGroup, target *kapialertingv2beta1.RuleGroupStatus) {
target.LastEvaluation = source.LastEvaluation
if source.EvaluationTime > 0 {
target.EvaluationTime = &source.EvaluationTime
}
groupState := promrules.StateInactive
for i := range source.Rules {
rule := source.Rules[i]
// the group state takes the max state of its rules
if ruleState := parseAlertState(rule.State); ruleState > groupState {
groupState = ruleState
}
alerts := []*kapialertingv2beta1.Alert{}
for _, alert := range rule.Alerts {
alerts = append(alerts, &kapialertingv2beta1.Alert{
ActiveAt: alert.ActiveAt,
Annotations: alert.Annotations,
Labels: alert.Labels,
State: alert.State,
Value: alert.Value,
})
}
target.RulesStatus = append(target.RulesStatus, kapialertingv2beta1.RuleStatus{
State: rule.State,
Health: rule.Health,
LastError: rule.LastError,
EvaluationTime: rule.EvaluationTime,
LastEvaluation: rule.LastEvaluation,
Alerts: alerts,
})
}
target.State = groupState.String()
}
var (
statePendingString = promrules.StatePending.String()
stateFiringString = promrules.StateFiring.String()
stateInactiveString = promrules.StateInactive.String()
)
// parseAlertState parses state string to the AlertState type
func parseAlertState(state string) promrules.AlertState {
switch state {
case statePendingString:
return promrules.StatePending
case stateFiringString:
return promrules.StateFiring
case stateInactiveString:
fallthrough
default:
return promrules.StateInactive
}
}
type wrapAlert struct {
kapialertingv2beta1.Alert
runtime.Object
}

View File

@@ -298,7 +298,9 @@ func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *alerting.AlertingR
}
rule.LastError = epRule.LastError
rule.LastEvaluation = epRule.LastEvaluation
rule.EvaluationDurationSeconds = epRule.EvaluationTime
if epRule.EvaluationTime != nil {
rule.EvaluationDurationSeconds = *epRule.EvaluationTime
}
rState := strings.ToLower(epRule.State)
cliRuleStateEmpty := rState == ""
@@ -349,11 +351,13 @@ func ParseAlertingRules(epRuleGroups []*alerting.RuleGroup, custom bool, level v
Labels: r.Labels,
Annotations: r.Annotations,
},
State: r.State,
Health: string(r.Health),
LastError: r.LastError,
LastEvaluation: r.LastEvaluation,
EvaluationDurationSeconds: r.EvaluationTime,
State: r.State,
Health: string(r.Health),
LastError: r.LastError,
LastEvaluation: r.LastEvaluation,
}
if r.EvaluationTime != nil {
rule.EvaluationDurationSeconds = *r.EvaluationTime
}
if rule.Health != "" {
rule.Health = string(rules.HealthUnknown)

View File

@@ -8,6 +8,8 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/client_golang/api"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql/parser"
)
const (
@@ -48,7 +50,7 @@ type response struct {
type RuleClient interface {
PrometheusRules(ctx context.Context) ([]*RuleGroup, error)
ThanosRules(ctx context.Context) ([]*RuleGroup, error)
ThanosRules(ctx context.Context, matchers ...[]*labels.Matcher) ([]*RuleGroup, error)
}
type ruleClient struct {
@@ -63,17 +65,25 @@ func (c *ruleClient) PrometheusRules(ctx context.Context) ([]*RuleGroup, error)
return nil, nil
}
func (c *ruleClient) ThanosRules(ctx context.Context) ([]*RuleGroup, error) {
func (c *ruleClient) ThanosRules(ctx context.Context, matchers ...[]*labels.Matcher) ([]*RuleGroup, error) {
if c.thanosruler != nil {
return c.rules(c.thanosruler, ctx)
return c.rules(c.thanosruler, ctx, matchers...)
}
return nil, nil
}
func (c *ruleClient) rules(client api.Client, ctx context.Context) ([]*RuleGroup, error) {
func (c *ruleClient) rules(client api.Client, ctx context.Context, matchers ...[]*labels.Matcher) ([]*RuleGroup, error) {
u := client.URL(epRules, nil)
q := u.Query()
q.Add("type", "alert")
for _, ms := range matchers {
vs := parser.VectorSelector{
LabelMatchers: ms,
}
q.Add("match[]", vs.String())
}
u.RawQuery = q.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)

View File

@@ -25,7 +25,7 @@ type AlertingRule struct {
// Health can be "ok", "err", "unknown".
Health string `json:"health"`
LastError string `json:"lastError,omitempty"`
EvaluationTime float64 `json:"evaluationTime"`
EvaluationTime *float64 `json:"evaluationTime"`
LastEvaluation *time.Time `json:"lastEvaluation"`
// Type of an alertingRule is always "alerting".
Type string `json:"type"`