From 514fec7eb41679b06bfc522583023b1b4313876e Mon Sep 17 00:00:00 2001 From: junotx Date: Tue, 12 Jan 2021 16:43:13 +0800 Subject: [PATCH] custom alerting use the same API group and flagset to alerting Signed-off-by: junotx --- cmd/ks-apiserver/app/options/options.go | 12 +- cmd/ks-apiserver/app/options/validation.go | 2 +- .../v1alpha1 => alerting/v2alpha1}/types.go | 2 +- pkg/apiserver/apiserver.go | 10 +- pkg/apiserver/config/config.go | 6 +- pkg/apiserver/config/config_test.go | 10 +- pkg/constants/constants.go | 2 +- .../v1alpha1 => alerting/v2alpha1}/handler.go | 56 +++--- .../v2alpha1}/register.go | 82 ++++----- .../alerting.go} | 162 +++++++++--------- .../rules/cache.go | 4 +- .../rules/rule.go | 6 +- .../rules/ruler.go | 6 +- .../rules/utils.go | 50 +++--- .../rules/utils_test.go | 18 +- pkg/simple/client/alerting/options.go | 51 +++++- .../rule_client.go | 2 +- .../rule_client_test.go | 2 +- .../{customalerting => alerting}/types.go | 2 +- pkg/simple/client/customalerting/options.go | 66 ------- tools/cmd/doc-gen/main.go | 4 +- 21 files changed, 261 insertions(+), 294 deletions(-) rename pkg/api/{customalerting/v1alpha1 => alerting/v2alpha1}/types.go (99%) rename pkg/kapis/{customalerting/v1alpha1 => alerting/v2alpha1}/handler.go (82%) rename pkg/kapis/{customalerting/v1alpha1 => alerting/v2alpha1}/register.go (74%) rename pkg/models/{customalerting/customalerting.go => alerting/alerting.go} (80%) rename pkg/models/{customalerting => alerting}/rules/cache.go (97%) rename pkg/models/{customalerting => alerting}/rules/rule.go (82%) rename pkg/models/{customalerting => alerting}/rules/ruler.go (99%) rename pkg/models/{customalerting => alerting}/rules/utils.go (86%) rename pkg/models/{customalerting => alerting}/rules/utils_test.go (85%) rename pkg/simple/client/{customalerting => alerting}/rule_client.go (99%) rename pkg/simple/client/{customalerting => alerting}/rule_client_test.go (99%) rename pkg/simple/client/{customalerting => alerting}/types.go (98%) delete mode 100644 pkg/simple/client/customalerting/options.go diff --git a/cmd/ks-apiserver/app/options/options.go b/cmd/ks-apiserver/app/options/options.go index 3b45db4f..f60b2a88 100644 --- a/cmd/ks-apiserver/app/options/options.go +++ b/cmd/ks-apiserver/app/options/options.go @@ -28,11 +28,11 @@ import ( "kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme" "kubesphere.io/kubesphere/pkg/informers" genericoptions "kubesphere.io/kubesphere/pkg/server/options" + "kubesphere.io/kubesphere/pkg/simple/client/alerting" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/cache" runtimecache "sigs.k8s.io/controller-runtime/pkg/cache" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/k8s" @@ -83,7 +83,7 @@ func (s *ServerRunOptions) Flags() (fss cliflag.NamedFlagSets) { s.MultiClusterOptions.AddFlags(fss.FlagSet("multicluster"), s.MultiClusterOptions) s.EventsOptions.AddFlags(fss.FlagSet("events"), s.EventsOptions) s.AuditingOptions.AddFlags(fss.FlagSet("auditing"), s.AuditingOptions) - s.CustomAlertingOptions.AddFlags(fss.FlagSet("customalerting"), s.CustomAlertingOptions) + s.AlertingOptions.AddFlags(fss.FlagSet("alerting"), s.AlertingOptions) fs = fss.FlagSet("klog") local := flag.NewFlagSet("klog", flag.ExitOnError) @@ -201,12 +201,12 @@ func (s *ServerRunOptions) NewAPIServer(stopCh <-chan struct{}) (*apiserver.APIS apiServer.OpenpitrixClient = opClient } - if s.CustomAlertingOptions != nil { - customAlertingClient, err := customalerting.NewRuleClient(s.CustomAlertingOptions) + if s.AlertingOptions != nil && (s.AlertingOptions.PrometheusEndpoint != "" || s.AlertingOptions.ThanosRulerEndpoint != "") { + alertingClient, err := alerting.NewRuleClient(s.AlertingOptions) if err != nil { - return nil, fmt.Errorf("failed to init custom alerting client") + return nil, fmt.Errorf("failed to init alerting client: %v", err) } - apiServer.CustomAlertingClient = customAlertingClient + apiServer.AlertingClient = alertingClient } server := &http.Server{ diff --git a/cmd/ks-apiserver/app/options/validation.go b/cmd/ks-apiserver/app/options/validation.go index 96a14186..3d18551a 100644 --- a/cmd/ks-apiserver/app/options/validation.go +++ b/cmd/ks-apiserver/app/options/validation.go @@ -34,7 +34,7 @@ func (s *ServerRunOptions) Validate() []error { errors = append(errors, s.AuthorizationOptions.Validate()...) errors = append(errors, s.EventsOptions.Validate()...) errors = append(errors, s.AuditingOptions.Validate()...) - errors = append(errors, s.CustomAlertingOptions.Validate()...) + errors = append(errors, s.AlertingOptions.Validate()...) return errors } diff --git a/pkg/api/customalerting/v1alpha1/types.go b/pkg/api/alerting/v2alpha1/types.go similarity index 99% rename from pkg/api/customalerting/v1alpha1/types.go rename to pkg/api/alerting/v2alpha1/types.go index c445d884..b2a89570 100644 --- a/pkg/api/customalerting/v1alpha1/types.go +++ b/pkg/api/alerting/v2alpha1/types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v2alpha1 import ( "regexp" diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index 289de2fd..aa96f120 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -49,9 +49,9 @@ import ( "kubesphere.io/kubesphere/pkg/apiserver/request" "kubesphere.io/kubesphere/pkg/informers" alertingv1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v1" + alertingv2alpha1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2alpha1" clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1" configv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/config/v1alpha2" - customalertingv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/customalerting/v1alpha1" devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2" devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3" iamapi "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2" @@ -73,9 +73,9 @@ import ( "kubesphere.io/kubesphere/pkg/models/iam/im" "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/loginrecord" "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/user" + "kubesphere.io/kubesphere/pkg/simple/client/alerting" "kubesphere.io/kubesphere/pkg/simple/client/auditing" "kubesphere.io/kubesphere/pkg/simple/client/cache" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/devops" "kubesphere.io/kubesphere/pkg/simple/client/events" "kubesphere.io/kubesphere/pkg/simple/client/k8s" @@ -146,7 +146,7 @@ type APIServer struct { AuditingClient auditing.Client - CustomAlertingClient customalerting.RuleClient + AlertingClient alerting.RuleClient // controller-runtime cache RuntimeCache runtimecache.Cache @@ -239,9 +239,9 @@ func (s *APIServer) installKubeSphereAPIs() { s.InformerFactory.KubernetesSharedInformerFactory())) urlruntime.Must(notificationv1.AddToContainer(s.container, s.Config.NotificationOptions.Endpoint)) 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(version.AddToContainer(s.container, s.KubernetesClient.Discovery())) - urlruntime.Must(customalertingv1alpha1.AddToContainer(s.container, s.InformerFactory, - s.KubernetesClient.Prometheus(), s.CustomAlertingClient, s.Config.CustomAlertingOptions)) } func (s *APIServer) Run(stopCh <-chan struct{}) (err error) { diff --git a/pkg/apiserver/config/config.go b/pkg/apiserver/config/config.go index 5a3542c6..9cf1a7a5 100644 --- a/pkg/apiserver/config/config.go +++ b/pkg/apiserver/config/config.go @@ -25,7 +25,6 @@ import ( "kubesphere.io/kubesphere/pkg/simple/client/alerting" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/cache" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/k8s" @@ -98,7 +97,6 @@ type Config struct { AuditingOptions *auditingclient.Options `json:"auditing,omitempty" yaml:"auditing,omitempty" mapstructure:"auditing"` AlertingOptions *alerting.Options `json:"alerting,omitempty" yaml:"alerting,omitempty" mapstructure:"alerting"` NotificationOptions *notification.Options `json:"notification,omitempty" yaml:"notification,omitempty" mapstructure:"notification"` - CustomAlertingOptions *customalerting.Options `json:"customalerting,omitempty" yaml:"customalerting,omitempty" mapstructure:"customalerting"` } // newConfig creates a default non-empty Config @@ -122,7 +120,6 @@ func New() *Config { MultiClusterOptions: multicluster.NewOptions(), EventsOptions: eventsclient.NewElasticSearchOptions(), AuditingOptions: auditingclient.NewElasticSearchOptions(), - CustomAlertingOptions: customalerting.NewOptions(), } } @@ -250,7 +247,8 @@ func (conf *Config) stripEmptyOptions() { conf.S3Options = nil } - if conf.AlertingOptions != nil && conf.AlertingOptions.Endpoint == "" { + if conf.AlertingOptions != nil && conf.AlertingOptions.Endpoint == "" && + conf.AlertingOptions.PrometheusEndpoint == "" && conf.AlertingOptions.ThanosRulerEndpoint == "" { conf.AlertingOptions = nil } diff --git a/pkg/apiserver/config/config_test.go b/pkg/apiserver/config/config_test.go index 4ece45df..93f77b5a 100644 --- a/pkg/apiserver/config/config_test.go +++ b/pkg/apiserver/config/config_test.go @@ -28,7 +28,6 @@ import ( "kubesphere.io/kubesphere/pkg/simple/client/alerting" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/cache" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" "kubesphere.io/kubesphere/pkg/simple/client/k8s" @@ -120,6 +119,10 @@ func newTestConfig() (*Config, error) { }, AlertingOptions: &alerting.Options{ Endpoint: "http://alerting-client-server.kubesphere-alerting-system.svc:9200/api", + + PrometheusEndpoint: "http://prometheus-operated.kubesphere-monitoring-system.svc", + ThanosRulerEndpoint: "http://thanos-ruler-operated.kubesphere-monitoring-system.svc", + ThanosRuleResourceLabels: "thanosruler=thanos-ruler,role=thanos-alerting-rules", }, NotificationOptions: ¬ification.Options{ Endpoint: "http://notification.kubesphere-alerting-system.svc:9200", @@ -157,11 +160,6 @@ func newTestConfig() (*Config, error) { IndexPrefix: "ks-logstash-auditing", Version: "6", }, - CustomAlertingOptions: &customalerting.Options{ - PrometheusEndpoint: "http://prometheus-operated.kubesphere-monitoring-system.svc", - ThanosRulerEndpoint: "http://thanos-ruler-operated.kubesphere-monitoring-system.svc", - ThanosRuleResourceLabels: "thanosruler=thanos-ruler,role=thanos-alerting-rules", - }, } return conf, nil } diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index 195c3049..e759ee98 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -105,7 +105,7 @@ const ( EventsQueryTag = "Events Query" AuditingQueryTag = "Auditing Query" - CustomAlertingTag = "Custom Alerting" + AlertingTag = "Alerting" ) var ( diff --git a/pkg/kapis/customalerting/v1alpha1/handler.go b/pkg/kapis/alerting/v2alpha1/handler.go similarity index 82% rename from pkg/kapis/customalerting/v1alpha1/handler.go rename to pkg/kapis/alerting/v2alpha1/handler.go index b8bdef96..94df298c 100644 --- a/pkg/kapis/customalerting/v1alpha1/handler.go +++ b/pkg/kapis/alerting/v2alpha1/handler.go @@ -14,35 +14,35 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v2alpha1 import ( "github.com/emicklei/go-restful" promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" "k8s.io/klog" ksapi "kubesphere.io/kubesphere/pkg/api" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" "kubesphere.io/kubesphere/pkg/informers" - customalertingmodels "kubesphere.io/kubesphere/pkg/models/customalerting" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" + alertingmodels "kubesphere.io/kubesphere/pkg/models/alerting" + "kubesphere.io/kubesphere/pkg/simple/client/alerting" ) type handler struct { - operator customalertingmodels.Operator + operator alertingmodels.Operator } func newHandler(informers informers.InformerFactory, - promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, - option *customalerting.Options) *handler { + promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient, + option *alerting.Options) *handler { return &handler{ - operator: customalertingmodels.NewOperator( + operator: alertingmodels.NewOperator( informers, promResourceClient, ruleClient, option), } } func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *restful.Response) { namespace := req.PathParameter("namespace") - query, err := v1alpha1.ParseAlertingRuleQueryParams(req) + query, err := v2alpha1.ParseAlertingRuleQueryParams(req) if err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -53,7 +53,7 @@ func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *rest if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -65,7 +65,7 @@ func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *rest func (h *handler) handleListCustomRulesAlerts(req *restful.Request, resp *restful.Response) { namespace := req.PathParameter("namespace") - query, err := v1alpha1.ParseAlertQueryParams(req) + query, err := v2alpha1.ParseAlertQueryParams(req) if err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -76,7 +76,7 @@ func (h *handler) handleListCustomRulesAlerts(req *restful.Request, resp *restfu if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -94,9 +94,9 @@ func (h *handler) handleGetCustomAlertingRule(req *restful.Request, resp *restfu if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -118,9 +118,9 @@ func (h *handler) handleListCustomRuleAlerts(req *restful.Request, resp *restful if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -133,7 +133,7 @@ func (h *handler) handleListCustomRuleAlerts(req *restful.Request, resp *restful func (h *handler) handleCreateCustomAlertingRule(req *restful.Request, resp *restful.Response) { namespace := req.PathParameter("namespace") - var rule v1alpha1.PostableAlertingRule + var rule v2alpha1.PostableAlertingRule if err := req.ReadEntity(&rule); err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -149,9 +149,9 @@ func (h *handler) handleCreateCustomAlertingRule(req *restful.Request, resp *res if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) - case err == v1alpha1.ErrAlertingRuleAlreadyExists: + case err == v2alpha1.ErrAlertingRuleAlreadyExists: ksapi.HandleConflict(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -164,7 +164,7 @@ func (h *handler) handleUpdateCustomAlertingRule(req *restful.Request, resp *res namespace := req.PathParameter("namespace") ruleName := req.PathParameter("rule_name") - var rule v1alpha1.PostableAlertingRule + var rule v2alpha1.PostableAlertingRule if err := req.ReadEntity(&rule); err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -180,9 +180,9 @@ func (h *handler) handleUpdateCustomAlertingRule(req *restful.Request, resp *res if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -199,9 +199,9 @@ func (h *handler) handleDeleteCustomAlertingRule(req *restful.Request, resp *res if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrThanosRulerNotEnabled: + case err == v2alpha1.ErrThanosRulerNotEnabled: ksapi.HandleBadRequest(resp, nil, err) - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -211,7 +211,7 @@ func (h *handler) handleDeleteCustomAlertingRule(req *restful.Request, resp *res } func (h *handler) handleListBuiltinAlertingRules(req *restful.Request, resp *restful.Response) { - query, err := v1alpha1.ParseAlertingRuleQueryParams(req) + query, err := v2alpha1.ParseAlertingRuleQueryParams(req) if err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -228,7 +228,7 @@ func (h *handler) handleListBuiltinAlertingRules(req *restful.Request, resp *res } func (h *handler) handleListBuiltinRulesAlerts(req *restful.Request, resp *restful.Response) { - query, err := v1alpha1.ParseAlertQueryParams(req) + query, err := v2alpha1.ParseAlertQueryParams(req) if err != nil { klog.Error(err) ksapi.HandleBadRequest(resp, nil, err) @@ -251,7 +251,7 @@ func (h *handler) handleGetBuiltinAlertingRule(req *restful.Request, resp *restf if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) @@ -273,7 +273,7 @@ func (h *handler) handleListBuiltinRuleAlerts(req *restful.Request, resp *restfu if err != nil { klog.Error(err) switch { - case err == v1alpha1.ErrAlertingRuleNotFound: + case err == v2alpha1.ErrAlertingRuleNotFound: ksapi.HandleNotFound(resp, nil, err) default: ksapi.HandleInternalError(resp, nil, err) diff --git a/pkg/kapis/customalerting/v1alpha1/register.go b/pkg/kapis/alerting/v2alpha1/register.go similarity index 74% rename from pkg/kapis/customalerting/v1alpha1/register.go rename to pkg/kapis/alerting/v2alpha1/register.go index 11facb2b..1e32d3fb 100644 --- a/pkg/kapis/customalerting/v1alpha1/register.go +++ b/pkg/kapis/alerting/v2alpha1/register.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v2alpha1 import ( "net/http" @@ -24,22 +24,22 @@ import ( promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" "k8s.io/apimachinery/pkg/runtime/schema" ksapi "kubesphere.io/kubesphere/pkg/api" - customalertingv1alpha1 "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + alertingv2alpha1 "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" "kubesphere.io/kubesphere/pkg/apiserver/runtime" "kubesphere.io/kubesphere/pkg/constants" "kubesphere.io/kubesphere/pkg/informers" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" + "kubesphere.io/kubesphere/pkg/simple/client/alerting" ) const ( - groupName = "custom.alerting.kubesphere.io" + groupName = "alerting.kubesphere.io" ) -var GroupVersion = schema.GroupVersion{Group: groupName, Version: "v1alpha1"} +var GroupVersion = schema.GroupVersion{Group: groupName, Version: "v2alpha1"} func AddToContainer(container *restful.Container, informers informers.InformerFactory, - promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, - option *customalerting.Options) error { + promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient, + option *alerting.Options) error { handler := newHandler(informers, promResourceClient, ruleClient, option) @@ -56,8 +56,8 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("sort_type", "sort type, one of `asc`, `desc`")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/alerts"). To(handler.handleListCustomRulesAlerts). @@ -66,40 +66,40 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("label_filters", "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")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/rules/{rule_name}"). To(handler.handleGetCustomAlertingRule). Doc("get the cluster-level custom alerting rule with the specified name"). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/rules/{rule_name}/alerts"). To(handler.handleListCustomRuleAlerts). Doc("list the alerts of the cluster-level custom alerting rule with the specified name"). - Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.POST("/rules"). To(handler.handleCreateCustomAlertingRule). Doc("create a cluster-level custom alerting rule"). - Reads(customalertingv1alpha1.PostableAlertingRule{}). + Reads(alertingv2alpha1.PostableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, nil). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.PUT("/rules/{rule_name}"). To(handler.handleUpdateCustomAlertingRule). Doc("update the cluster-level custom alerting rule with the specified name"). - Reads(customalertingv1alpha1.PostableAlertingRule{}). + Reads(alertingv2alpha1.PostableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, nil). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.DELETE("/rules/{rule_name}"). To(handler.handleDeleteCustomAlertingRule). Doc("delete the cluster-level custom alerting rule with the specified name"). Returns(http.StatusOK, ksapi.StatusOK, nil). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/namespaces/{namespace}/rules"). To(handler.handleListCustomAlertingRules). @@ -112,8 +112,8 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("sort_type", "sort type, one of `asc`, `desc`")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/namespaces/{namespace}/alerts"). To(handler.handleListCustomRulesAlerts). @@ -122,40 +122,40 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("label_filters", "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")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}"). To(handler.handleGetCustomAlertingRule). Doc("get the custom alerting rule with the specified name in the specified namespace"). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}/alerts"). To(handler.handleListCustomRuleAlerts). Doc("get the alerts of the custom alerting rule with the specified name in the specified namespace"). - Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.POST("/namespaces/{namespace}/rules"). To(handler.handleCreateCustomAlertingRule). Doc("create a custom alerting rule in the specified namespace"). - Reads(customalertingv1alpha1.PostableAlertingRule{}). + Reads(alertingv2alpha1.PostableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, ""). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.PUT("/namespaces/{namespace}/rules/{rule_name}"). To(handler.handleUpdateCustomAlertingRule). Doc("update the custom alerting rule with the specified name in the specified namespace"). - Reads(customalertingv1alpha1.PostableAlertingRule{}). + Reads(alertingv2alpha1.PostableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, ""). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.DELETE("/namespaces/{namespace}/rules/{rule_name}"). To(handler.handleDeleteCustomAlertingRule). Doc("delete the custom alerting rule with the specified rule name in the specified namespace"). Returns(http.StatusOK, ksapi.StatusOK, nil). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/builtin/rules"). To(handler.handleListBuiltinAlertingRules). @@ -168,8 +168,8 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("sort_type", "sort type, one of `asc`, `desc`")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/builtin/alerts"). To(handler.handleListBuiltinRulesAlerts). @@ -178,20 +178,20 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa Param(ws.QueryParameter("label_filters", "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")). Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/builtin/rules/{rule_id}"). To(handler.handleGetBuiltinAlertingRule). Doc("get the builtin(non-custom) alerting rule with specified id"). - Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) ws.Route(ws.GET("/builtin/rules/{rule_id}/alerts"). To(handler.handleListBuiltinRuleAlerts). Doc("list the alerts of the builtin(non-custom) alerting rule with the specified id"). - Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). - Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) + Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}). + Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag})) container.Add(ws) diff --git a/pkg/models/customalerting/customalerting.go b/pkg/models/alerting/alerting.go similarity index 80% rename from pkg/models/customalerting/customalerting.go rename to pkg/models/alerting/alerting.go index 1c21cc88..3c40ed01 100644 --- a/pkg/models/customalerting/customalerting.go +++ b/pkg/models/alerting/alerting.go @@ -1,4 +1,4 @@ -package customalerting +package alerting import ( "context" @@ -13,11 +13,11 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/util/intstr" coreinformersv1 "k8s.io/client-go/informers/core/v1" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" "kubesphere.io/kubesphere/pkg/constants" "kubesphere.io/kubesphere/pkg/informers" - "kubesphere.io/kubesphere/pkg/models/customalerting/rules" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" + "kubesphere.io/kubesphere/pkg/models/alerting/rules" + "kubesphere.io/kubesphere/pkg/simple/client/alerting" ) const ( @@ -41,36 +41,36 @@ var ( type Operator interface { // ListCustomAlertingRules lists the custom alerting rules. ListCustomAlertingRules(ctx context.Context, namespace string, - queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) + queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) // ListCustomRulesAlerts lists the alerts of the custom alerting rules. ListCustomRulesAlerts(ctx context.Context, namespace string, - queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) + queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) // GetCustomAlertingRule gets the custom alerting rule with the given name. - GetCustomAlertingRule(ctx context.Context, namespace, ruleName string) (*v1alpha1.GettableAlertingRule, error) + GetCustomAlertingRule(ctx context.Context, namespace, ruleName string) (*v2alpha1.GettableAlertingRule, error) // ListCustomRuleAlerts lists the alerts of the custom alerting rule with the given name. - ListCustomRuleAlerts(ctx context.Context, namespace, ruleName string) ([]*v1alpha1.Alert, error) + ListCustomRuleAlerts(ctx context.Context, namespace, ruleName string) ([]*v2alpha1.Alert, error) // CreateCustomAlertingRule creates a custom alerting rule. - CreateCustomAlertingRule(ctx context.Context, namespace string, rule *v1alpha1.PostableAlertingRule) error + CreateCustomAlertingRule(ctx context.Context, namespace string, rule *v2alpha1.PostableAlertingRule) error // UpdateCustomAlertingRule updates the custom alerting rule with the given name. - UpdateCustomAlertingRule(ctx context.Context, namespace, ruleName string, rule *v1alpha1.PostableAlertingRule) error + UpdateCustomAlertingRule(ctx context.Context, namespace, ruleName string, rule *v2alpha1.PostableAlertingRule) error // DeleteCustomAlertingRule deletes the custom alerting rule with the given name. DeleteCustomAlertingRule(ctx context.Context, namespace, ruleName string) error // ListBuiltinAlertingRules lists the builtin(non-custom) alerting rules ListBuiltinAlertingRules(ctx context.Context, - queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) + queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) // ListBuiltinRulesAlerts lists the alerts of the builtin(non-custom) alerting rules ListBuiltinRulesAlerts(ctx context.Context, - queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) + queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) // GetBuiltinAlertingRule gets the builtin(non-custom) alerting rule with the given id - GetBuiltinAlertingRule(ctx context.Context, ruleId string) (*v1alpha1.GettableAlertingRule, error) + GetBuiltinAlertingRule(ctx context.Context, ruleId string) (*v2alpha1.GettableAlertingRule, error) // ListBuiltinRuleAlerts lists the alerts of the builtin(non-custom) alerting rule with the given id - ListBuiltinRuleAlerts(ctx context.Context, ruleId string) ([]*v1alpha1.Alert, error) + ListBuiltinRuleAlerts(ctx context.Context, ruleId string) ([]*v2alpha1.Alert, error) } func NewOperator(informers informers.InformerFactory, - promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, - option *customalerting.Options) Operator { + promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient, + option *alerting.Options) Operator { o := operator{ namespaceInformer: informers.KubernetesSharedInformerFactory().Core().V1().Namespaces(), @@ -101,7 +101,7 @@ func NewOperator(informers informers.InformerFactory, } type operator struct { - ruleClient customalerting.RuleClient + ruleClient alerting.RuleClient promResourceClient promresourcesclient.Interface @@ -117,14 +117,14 @@ type operator struct { } func (o *operator) ListCustomAlertingRules(ctx context.Context, namespace string, - queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) { + queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) { - var level v1alpha1.RuleLevel + var level v2alpha1.RuleLevel if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace } ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -141,14 +141,14 @@ func (o *operator) ListCustomAlertingRules(ctx context.Context, namespace string } func (o *operator) ListCustomRulesAlerts(ctx context.Context, namespace string, - queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) { + queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) { - var level v1alpha1.RuleLevel + var level v2alpha1.RuleLevel if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace } ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -165,14 +165,14 @@ func (o *operator) ListCustomRulesAlerts(ctx context.Context, namespace string, } func (o *operator) GetCustomAlertingRule(ctx context.Context, namespace, ruleName string) ( - *v1alpha1.GettableAlertingRule, error) { + *v2alpha1.GettableAlertingRule, error) { - var level v1alpha1.RuleLevel + var level v2alpha1.RuleLevel if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace } ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -184,20 +184,20 @@ func (o *operator) GetCustomAlertingRule(ctx context.Context, namespace, ruleNam } func (o *operator) ListCustomRuleAlerts(ctx context.Context, namespace, ruleName string) ( - []*v1alpha1.Alert, error) { + []*v2alpha1.Alert, error) { rule, err := o.GetCustomAlertingRule(ctx, namespace, ruleName) if err != nil { return nil, err } if rule == nil { - return nil, v1alpha1.ErrAlertingRuleNotFound + return nil, v2alpha1.ErrAlertingRuleNotFound } return rule.Alerts, nil } func (o *operator) ListBuiltinAlertingRules(ctx context.Context, - queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) { + queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) { alertingRules, err := o.listBuiltinAlertingRules(ctx) if err != nil { @@ -208,7 +208,7 @@ func (o *operator) ListBuiltinAlertingRules(ctx context.Context, } func (o *operator) ListBuiltinRulesAlerts(ctx context.Context, - queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) { + queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) { alertingRules, err := o.listBuiltinAlertingRules(ctx) if err != nil { return nil, err @@ -218,24 +218,24 @@ func (o *operator) ListBuiltinRulesAlerts(ctx context.Context, } func (o *operator) GetBuiltinAlertingRule(ctx context.Context, ruleId string) ( - *v1alpha1.GettableAlertingRule, error) { + *v2alpha1.GettableAlertingRule, error) { return o.getBuiltinAlertingRule(ctx, ruleId) } -func (o *operator) ListBuiltinRuleAlerts(ctx context.Context, ruleId string) ([]*v1alpha1.Alert, error) { +func (o *operator) ListBuiltinRuleAlerts(ctx context.Context, ruleId string) ([]*v2alpha1.Alert, error) { rule, err := o.getBuiltinAlertingRule(ctx, ruleId) if err != nil { return nil, err } if rule == nil { - return nil, v1alpha1.ErrAlertingRuleNotFound + return nil, v2alpha1.ErrAlertingRuleNotFound } return rule.Alerts, nil } func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag string, - queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) { + queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) { namespace := rulerNamespace ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -243,7 +243,7 @@ func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag stri return nil, err } - alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v1alpha1.RuleLevelCluster) + alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v2alpha1.RuleLevelCluster) if err != nil { return nil, err } @@ -252,7 +252,7 @@ func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag stri } func (o *operator) ListClusterRulesAlerts(ctx context.Context, - queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) { + queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) { namespace := rulerNamespace ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -260,7 +260,7 @@ func (o *operator) ListClusterRulesAlerts(ctx context.Context, return nil, err } - alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v1alpha1.RuleLevelCluster) + alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v2alpha1.RuleLevelCluster) if err != nil { return nil, err } @@ -269,14 +269,14 @@ func (o *operator) ListClusterRulesAlerts(ctx context.Context, } func (o *operator) listCustomAlertingRules(ctx context.Context, ruleNamespace *corev1.Namespace, - level v1alpha1.RuleLevel) ([]*v1alpha1.GettableAlertingRule, error) { + level v2alpha1.RuleLevel) ([]*v2alpha1.GettableAlertingRule, error) { ruler, err := o.getThanosRuler() if err != nil { return nil, err } if ruler == nil { - return nil, v1alpha1.ErrThanosRulerNotEnabled + return nil, v2alpha1.ErrThanosRulerNotEnabled } resourceRulesMap, err := o.resourceRuleCache.ListRules(ruler, ruleNamespace, @@ -298,14 +298,14 @@ func (o *operator) listCustomAlertingRules(ctx context.Context, ruleNamespace *c } func (o *operator) getCustomAlertingRule(ctx context.Context, ruleNamespace *corev1.Namespace, - ruleName string, level v1alpha1.RuleLevel) (*v1alpha1.GettableAlertingRule, error) { + ruleName string, level v2alpha1.RuleLevel) (*v2alpha1.GettableAlertingRule, error) { ruler, err := o.getThanosRuler() if err != nil { return nil, err } if ruler == nil { - return nil, v1alpha1.ErrThanosRulerNotEnabled + return nil, v2alpha1.ErrThanosRulerNotEnabled } resourceRule, err := o.resourceRuleCache.GetRule(ruler, ruleNamespace, @@ -314,7 +314,7 @@ func (o *operator) getCustomAlertingRule(ctx context.Context, ruleNamespace *cor return nil, err } if resourceRule == nil { - return nil, v1alpha1.ErrAlertingRuleNotFound + return nil, v2alpha1.ErrAlertingRuleNotFound } ruleGroups, err := o.ruleClient.ThanosRules(ctx) @@ -330,7 +330,7 @@ func (o *operator) getCustomAlertingRule(ctx context.Context, ruleNamespace *cor } func (o *operator) listBuiltinAlertingRules(ctx context.Context) ( - []*v1alpha1.GettableAlertingRule, error) { + []*v2alpha1.GettableAlertingRule, error) { ruler, err := o.getPrometheusRuler() if err != nil { @@ -344,8 +344,8 @@ func (o *operator) listBuiltinAlertingRules(ctx context.Context) ( if ruler == nil { // for out-cluster prometheus - return rules.ParseAlertingRules(ruleGroups, false, v1alpha1.RuleLevelCluster, - func(group, id string, rule *customalerting.AlertingRule) bool { + return rules.ParseAlertingRules(ruleGroups, false, v2alpha1.RuleLevelCluster, + func(group, id string, rule *alerting.AlertingRule) bool { return true }) } @@ -364,11 +364,11 @@ func (o *operator) listBuiltinAlertingRules(ctx context.Context) ( return rules.GetAlertingRulesStatus(ruleNamespace.Name, &rules.ResourceRuleChunk{ ResourceRulesMap: resourceRulesMap, Custom: false, - Level: v1alpha1.RuleLevelCluster, + Level: v2alpha1.RuleLevelCluster, }, ruleGroups, ruler.ExternalLabels()) } -func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (*v1alpha1.GettableAlertingRule, error) { +func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (*v2alpha1.GettableAlertingRule, error) { ruler, err := o.getPrometheusRuler() if err != nil { @@ -382,18 +382,18 @@ func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (* if ruler == nil { // for out-cluster prometheus - alertingRules, err := rules.ParseAlertingRules(ruleGroups, false, v1alpha1.RuleLevelCluster, - func(group, id string, rule *customalerting.AlertingRule) bool { + alertingRules, err := rules.ParseAlertingRules(ruleGroups, false, v2alpha1.RuleLevelCluster, + func(group, id string, rule *alerting.AlertingRule) bool { return ruleId == id }) if err != nil { return nil, err } if len(alertingRules) == 0 { - return nil, v1alpha1.ErrAlertingRuleNotFound + return nil, v2alpha1.ErrAlertingRuleNotFound } sort.Slice(alertingRules, func(i, j int) bool { - return v1alpha1.AlertingRuleIdCompare(alertingRules[i].Id, alertingRules[j].Id) + return v2alpha1.AlertingRuleIdCompare(alertingRules[i].Id, alertingRules[j].Id) }) return alertingRules[0], nil } @@ -410,28 +410,28 @@ func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (* } if resourceRule == nil { - return nil, v1alpha1.ErrAlertingRuleNotFound + return nil, v2alpha1.ErrAlertingRuleNotFound } return rules.GetAlertingRuleStatus(ruleNamespace.Name, &rules.ResourceRule{ ResourceRuleItem: *resourceRule, Custom: false, - Level: v1alpha1.RuleLevelCluster, + Level: v2alpha1.RuleLevelCluster, }, ruleGroups, ruler.ExternalLabels()) } func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace string, - rule *v1alpha1.PostableAlertingRule) error { + rule *v2alpha1.PostableAlertingRule) error { ruler, err := o.getThanosRuler() if err != nil { return err } if ruler == nil { - return v1alpha1.ErrThanosRulerNotEnabled + return v2alpha1.ErrThanosRulerNotEnabled } var ( - level v1alpha1.RuleLevel + level v2alpha1.RuleLevel ruleResourceLabels = make(map[string]string) ) for k, v := range o.thanosRuleResourceLabels { @@ -439,9 +439,9 @@ func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace strin } if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace) if err != nil { return err @@ -461,7 +461,7 @@ func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace strin return err } if resourceRule != nil { - return v1alpha1.ErrAlertingRuleAlreadyExists + return v2alpha1.ErrAlertingRuleAlreadyExists } return ruler.AddAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, @@ -469,7 +469,7 @@ func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace strin } func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name string, - rule *v1alpha1.PostableAlertingRule) error { + rule *v2alpha1.PostableAlertingRule) error { rule.Name = name @@ -478,11 +478,11 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name return err } if ruler == nil { - return v1alpha1.ErrThanosRulerNotEnabled + return v2alpha1.ErrThanosRulerNotEnabled } var ( - level v1alpha1.RuleLevel + level v2alpha1.RuleLevel ruleResourceLabels = make(map[string]string) ) for k, v := range o.thanosRuleResourceLabels { @@ -490,9 +490,9 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name } if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace) if err != nil { return err @@ -512,7 +512,7 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name return err } if resourceRule == nil { - return v1alpha1.ErrAlertingRuleNotFound + return v2alpha1.ErrAlertingRuleNotFound } return ruler.UpdateAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, @@ -525,17 +525,17 @@ func (o *operator) DeleteCustomAlertingRule(ctx context.Context, namespace, name return err } if ruler == nil { - return v1alpha1.ErrThanosRulerNotEnabled + return v2alpha1.ErrThanosRulerNotEnabled } var ( - level v1alpha1.RuleLevel + level v2alpha1.RuleLevel ) if namespace == "" { namespace = rulerNamespace - level = v1alpha1.RuleLevelCluster + level = v2alpha1.RuleLevelCluster } else { - level = v1alpha1.RuleLevelNamespace + level = v2alpha1.RuleLevelNamespace } ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) @@ -549,7 +549,7 @@ func (o *operator) DeleteCustomAlertingRule(ctx context.Context, namespace, name return err } if resourceRule == nil { - return v1alpha1.ErrAlertingRuleNotFound + return v2alpha1.ErrAlertingRuleNotFound } return ruler.DeleteAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, resourceRule.Group, name) @@ -591,7 +591,7 @@ func (o *operator) getThanosRuler() (rules.Ruler, error) { return rules.NewThanosRuler(thanosrulers[0], o.ruleResourceInformer, o.promResourceClient), nil } -func parseToPrometheusRule(rule *v1alpha1.PostableAlertingRule) *promresourcesv1.Rule { +func parseToPrometheusRule(rule *v2alpha1.PostableAlertingRule) *promresourcesv1.Rule { return &promresourcesv1.Rule{ Alert: rule.Name, Expr: intstr.FromString(rule.Query), @@ -601,28 +601,28 @@ func parseToPrometheusRule(rule *v1alpha1.PostableAlertingRule) *promresourcesv1 } } -func pageAlertingRules(alertingRules []*v1alpha1.GettableAlertingRule, - queryParams *v1alpha1.AlertingRuleQueryParams) *v1alpha1.GettableAlertingRuleList { +func pageAlertingRules(alertingRules []*v2alpha1.GettableAlertingRule, + queryParams *v2alpha1.AlertingRuleQueryParams) *v2alpha1.GettableAlertingRuleList { alertingRules = queryParams.Filter(alertingRules) queryParams.Sort(alertingRules) - return &v1alpha1.GettableAlertingRuleList{ + return &v2alpha1.GettableAlertingRuleList{ Total: len(alertingRules), Items: queryParams.Sub(alertingRules), } } -func pageAlerts(alertingRules []*v1alpha1.GettableAlertingRule, - queryParams *v1alpha1.AlertQueryParams) *v1alpha1.AlertList { +func pageAlerts(alertingRules []*v2alpha1.GettableAlertingRule, + queryParams *v2alpha1.AlertQueryParams) *v2alpha1.AlertList { - var alerts []*v1alpha1.Alert + var alerts []*v2alpha1.Alert for _, rule := range alertingRules { alerts = append(alerts, queryParams.Filter(rule.Alerts)...) } queryParams.Sort(alerts) - return &v1alpha1.AlertList{ + return &v2alpha1.AlertList{ Total: len(alerts), Items: queryParams.Sub(alerts), } diff --git a/pkg/models/customalerting/rules/cache.go b/pkg/models/alerting/rules/cache.go similarity index 97% rename from pkg/models/customalerting/rules/cache.go rename to pkg/models/alerting/rules/cache.go index 556d0b2c..ed94a521 100644 --- a/pkg/models/customalerting/rules/cache.go +++ b/pkg/models/alerting/rules/cache.go @@ -9,7 +9,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" "kubesphere.io/kubesphere/pkg/server/errors" ) @@ -150,7 +150,7 @@ func (c *RuleCache) GetRule(ruler Ruler, ruleNamespace *corev1.Namespace, } else if l > 1 { // guarantees the stability of the get operations. sort.Slice(rules, func(i, j int) bool { - return v1alpha1.AlertingRuleIdCompare(rules[i].Id, rules[j].Id) + return v2alpha1.AlertingRuleIdCompare(rules[i].Id, rules[j].Id) }) } return rules[0], nil diff --git a/pkg/models/customalerting/rules/rule.go b/pkg/models/alerting/rules/rule.go similarity index 82% rename from pkg/models/customalerting/rules/rule.go rename to pkg/models/alerting/rules/rule.go index 7941d305..6524187e 100644 --- a/pkg/models/customalerting/rules/rule.go +++ b/pkg/models/alerting/rules/rule.go @@ -2,7 +2,7 @@ package rules import ( promresourcesv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" ) type ResourceRuleCollection struct { @@ -19,13 +19,13 @@ type ResourceRuleItem struct { } type ResourceRule struct { - Level v1alpha1.RuleLevel + Level v2alpha1.RuleLevel Custom bool ResourceRuleItem } type ResourceRuleChunk struct { - Level v1alpha1.RuleLevel + Level v2alpha1.RuleLevel Custom bool ResourceRulesMap map[string]*ResourceRuleCollection } diff --git a/pkg/models/customalerting/rules/ruler.go b/pkg/models/alerting/rules/ruler.go similarity index 99% rename from pkg/models/customalerting/rules/ruler.go rename to pkg/models/alerting/rules/ruler.go index c85ef4fa..887a6e89 100644 --- a/pkg/models/customalerting/rules/ruler.go +++ b/pkg/models/alerting/rules/ruler.go @@ -13,7 +13,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" ) const ( @@ -438,7 +438,7 @@ func (r *ThanosRuler) UpdateAlertingRule(ctx context.Context, ruleNamespace *cor } if !found { - return v1alpha1.ErrAlertingRuleNotFound + return v2alpha1.ErrAlertingRuleNotFound } if !success { @@ -478,7 +478,7 @@ func (r *ThanosRuler) DeleteAlertingRule(ctx context.Context, ruleNamespace *cor } } if !success { - return v1alpha1.ErrAlertingRuleNotFound + return v2alpha1.ErrAlertingRuleNotFound } return nil } diff --git a/pkg/models/customalerting/rules/utils.go b/pkg/models/alerting/rules/utils.go similarity index 86% rename from pkg/models/customalerting/rules/utils.go rename to pkg/models/alerting/rules/utils.go index b2a266d3..b22f1ca9 100644 --- a/pkg/models/customalerting/rules/utils.go +++ b/pkg/models/alerting/rules/utils.go @@ -1,6 +1,7 @@ package rules import ( + "kubesphere.io/kubesphere/pkg/simple/client/alerting" "path/filepath" "sort" "strings" @@ -14,8 +15,7 @@ import ( "github.com/prometheus/prometheus/promql/parser" "github.com/prometheus/prometheus/rules" "k8s.io/klog" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" ) const ( @@ -92,7 +92,7 @@ func GenResourceRuleIdIgnoreFormat(group string, rule *promresourcesv1.Rule) str return prommodel.Fingerprint(prommodel.LabelsToSignature(lbls)).String() } -func GenEndpointRuleId(group string, epRule *customalerting.AlertingRule, +func GenEndpointRuleId(group string, epRule *alerting.AlertingRule, externalLabels func() map[string]string) (string, error) { query, err := FormatExpr(epRule.Query) if err != nil { @@ -127,13 +127,13 @@ func GenEndpointRuleId(group string, epRule *customalerting.AlertingRule, // GetAlertingRulesStatus mix rules from prometheusrule custom resources and rules from endpoints. // Use rules from prometheusrule custom resources as the main reference. -func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, epRuleGroups []*customalerting.RuleGroup, - extLabels func() map[string]string) ([]*v1alpha1.GettableAlertingRule, error) { +func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, epRuleGroups []*alerting.RuleGroup, + extLabels func() map[string]string) ([]*v2alpha1.GettableAlertingRule, error) { var ( - idEpRules = make(map[string]*customalerting.AlertingRule) + idEpRules = make(map[string]*alerting.AlertingRule) nameIds = make(map[string][]string) - ret []*v1alpha1.GettableAlertingRule + ret []*v2alpha1.GettableAlertingRule ) for _, group := range epRuleGroups { fileShort := strings.TrimSuffix(filepath.Base(group.File), filepath.Ext(group.File)) @@ -169,7 +169,7 @@ func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, if l := len(rrArr); l > 0 { if l > 1 { sort.Slice(rrArr, func(i, j int) bool { - return v1alpha1.AlertingRuleIdCompare(rrArr[i].Id, rrArr[j].Id) + return v2alpha1.AlertingRuleIdCompare(rrArr[i].Id, rrArr[j].Id) }) } resRule := rrArr[0] @@ -181,7 +181,7 @@ func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, } } else { // guarantee the ids of the builtin alerting rules not to be repeated - var m = make(map[string]*v1alpha1.GettableAlertingRule) + var m = make(map[string]*v2alpha1.GettableAlertingRule) for _, resourceRules := range ruleChunk.ResourceRulesMap { for id, rule := range resourceRules.IdRules { if r := getAlertingRuleStatus(rule, idEpRules[id], ruleChunk.Custom, ruleChunk.Level); r != nil { @@ -197,14 +197,14 @@ func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, return ret, nil } -func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroups []*customalerting.RuleGroup, - extLabels func() map[string]string) (*v1alpha1.GettableAlertingRule, error) { +func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroups []*alerting.RuleGroup, + extLabels func() map[string]string) (*v2alpha1.GettableAlertingRule, error) { if rule == nil || rule.Rule == nil { return nil, nil } - var epRules = make(map[string]*customalerting.AlertingRule) + var epRules = make(map[string]*alerting.AlertingRule) for _, group := range epRuleGroups { fileShort := strings.TrimSuffix(filepath.Base(group.File), filepath.Ext(group.File)) if !strings.HasPrefix(fileShort, ruleNamespace+"-") { @@ -224,7 +224,7 @@ func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroup } } } - var epRule *customalerting.AlertingRule + var epRule *alerting.AlertingRule if rule.Custom { // guarantees the stability of the get operations. var ids []string @@ -234,7 +234,7 @@ func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroup if l := len(ids); l > 0 { if l > 1 { sort.Slice(ids, func(i, j int) bool { - return v1alpha1.AlertingRuleIdCompare(ids[i], ids[j]) + return v2alpha1.AlertingRuleIdCompare(ids[i], ids[j]) }) } epRule = epRules[ids[0]] @@ -246,15 +246,15 @@ func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroup return getAlertingRuleStatus(&rule.ResourceRuleItem, epRule, rule.Custom, rule.Level), nil } -func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.AlertingRule, - custom bool, level v1alpha1.RuleLevel) *v1alpha1.GettableAlertingRule { +func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *alerting.AlertingRule, + custom bool, level v2alpha1.RuleLevel) *v2alpha1.GettableAlertingRule { if resRule == nil || resRule.Rule == nil { return nil } - rule := v1alpha1.GettableAlertingRule{ - AlertingRule: v1alpha1.AlertingRule{ + rule := v2alpha1.GettableAlertingRule{ + AlertingRule: v2alpha1.AlertingRule{ Id: resRule.Id, Name: resRule.Rule.Alert, Query: resRule.Rule.Expr.String(), @@ -289,7 +289,7 @@ func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.Ale rule.State = aState } } - rule.Alerts = append(rule.Alerts, &v1alpha1.Alert{ + rule.Alerts = append(rule.Alerts, &v2alpha1.Alert{ ActiveAt: a.ActiveAt, Labels: a.Labels, Annotations: a.Annotations, @@ -304,10 +304,10 @@ func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.Ale return &rule } -func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, level v1alpha1.RuleLevel, - filterFunc func(group, ruleId string, rule *customalerting.AlertingRule) bool) ([]*v1alpha1.GettableAlertingRule, error) { +func ParseAlertingRules(epRuleGroups []*alerting.RuleGroup, custom bool, level v2alpha1.RuleLevel, + filterFunc func(group, ruleId string, rule *alerting.AlertingRule) bool) ([]*v2alpha1.GettableAlertingRule, error) { - var ret []*v1alpha1.GettableAlertingRule + var ret []*v2alpha1.GettableAlertingRule for _, g := range epRuleGroups { for _, r := range g.Rules { id, err := GenEndpointRuleId(g.Name, r, nil) @@ -315,8 +315,8 @@ func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, l return nil, err } if filterFunc(g.Name, id, r) { - rule := &v1alpha1.GettableAlertingRule{ - AlertingRule: v1alpha1.AlertingRule{ + rule := &v2alpha1.GettableAlertingRule{ + AlertingRule: v2alpha1.AlertingRule{ Id: id, Name: r.Name, Query: r.Query, @@ -344,7 +344,7 @@ func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, l rule.State = aState } } - rule.Alerts = append(rule.Alerts, &v1alpha1.Alert{ + rule.Alerts = append(rule.Alerts, &v2alpha1.Alert{ ActiveAt: a.ActiveAt, Labels: a.Labels, Annotations: a.Annotations, diff --git a/pkg/models/customalerting/rules/utils_test.go b/pkg/models/alerting/rules/utils_test.go similarity index 85% rename from pkg/models/customalerting/rules/utils_test.go rename to pkg/models/alerting/rules/utils_test.go index ee64984c..8a188717 100644 --- a/pkg/models/customalerting/rules/utils_test.go +++ b/pkg/models/alerting/rules/utils_test.go @@ -1,14 +1,14 @@ package rules import ( + "kubesphere.io/kubesphere/pkg/simple/client/alerting" "testing" "github.com/google/go-cmp/cmp" promresourcesv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" "github.com/prometheus/prometheus/rules" "k8s.io/apimachinery/pkg/util/intstr" - "kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" - "kubesphere.io/kubesphere/pkg/simple/client/customalerting" + "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1" ) func TestGetAlertingRulesStatus(t *testing.T) { @@ -16,14 +16,14 @@ func TestGetAlertingRulesStatus(t *testing.T) { description string ruleNamespace string resourceRuleChunk *ResourceRuleChunk - ruleGroups []*customalerting.RuleGroup + ruleGroups []*alerting.RuleGroup extLabels func() map[string]string - expected []*v1alpha1.GettableAlertingRule + expected []*v2alpha1.GettableAlertingRule }{{ description: "get alerting rules status", ruleNamespace: "test", resourceRuleChunk: &ResourceRuleChunk{ - Level: v1alpha1.RuleLevelNamespace, + Level: v2alpha1.RuleLevelNamespace, Custom: true, ResourceRulesMap: map[string]*ResourceRuleCollection{ "custom-alerting-rule-jqbgn": &ResourceRuleCollection{ @@ -47,10 +47,10 @@ func TestGetAlertingRulesStatus(t *testing.T) { }, }, }, - ruleGroups: []*customalerting.RuleGroup{{ + ruleGroups: []*alerting.RuleGroup{{ Name: "alerting.custom.defaults", File: "/etc/thanos/rules/thanos-ruler-thanos-ruler-rulefiles-0/test-custom-alerting-rule-jqbgn.yaml", - Rules: []*customalerting.AlertingRule{{ + Rules: []*alerting.AlertingRule{{ Name: "TestCPUUsageHigh", Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`, Duration: 60, @@ -62,8 +62,8 @@ func TestGetAlertingRulesStatus(t *testing.T) { }, }}, }}, - expected: []*v1alpha1.GettableAlertingRule{{ - AlertingRule: v1alpha1.AlertingRule{ + expected: []*v2alpha1.GettableAlertingRule{{ + AlertingRule: v2alpha1.AlertingRule{ Id: "ca7f09e76954e67c", Name: "TestCPUUsageHigh", Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`, diff --git a/pkg/simple/client/alerting/options.go b/pkg/simple/client/alerting/options.go index 2ab11da2..c8a419e9 100644 --- a/pkg/simple/client/alerting/options.go +++ b/pkg/simple/client/alerting/options.go @@ -16,8 +16,21 @@ limitations under the License. package alerting +import ( + "fmt" + "strings" + + "github.com/spf13/pflag" + "kubesphere.io/kubesphere/pkg/utils/reflectutils" +) + type Options struct { Endpoint string `json:"endpoint" yaml:"endpoint"` + + // The following options are for the alerting with v2alpha1 version or higher versions + PrometheusEndpoint string `json:"prometheusEndpoint" yaml:"prometheusEndpoint"` + ThanosRulerEndpoint string `json:"thanosRulerEndpoint" yaml:"thanosRulerEndpoint"` + ThanosRuleResourceLabels string `json:"thanosRuleResourceLabels" yaml:"thanosRuleResourceLabels"` } func NewAlertingOptions() *Options { @@ -26,13 +39,37 @@ func NewAlertingOptions() *Options { } } -func (s *Options) ApplyTo(options *Options) { - if options == nil { - options = s - return - } +func (o *Options) ApplyTo(options *Options) { + reflectutils.Override(options, o) +} - if s.Endpoint != "" { - options.Endpoint = s.Endpoint +func (o *Options) Validate() []error { + errs := []error{} + + if len(o.ThanosRuleResourceLabels) > 0 { + lblStrings := strings.Split(o.ThanosRuleResourceLabels, ",") + for _, lblString := range lblStrings { + if len(lblString) > 0 { + lbl := strings.Split(lblString, "=") + if len(lbl) != 2 { + errs = append(errs, fmt.Errorf("invalid alerting-thanos-rule-resource-labels arg: %s", o.ThanosRuleResourceLabels)) + break + } + } + } } + + return errs +} + +func (o *Options) AddFlags(fs *pflag.FlagSet, c *Options) { + fs.StringVar(&o.Endpoint, "alerting-server-endpoint", c.Endpoint, + "alerting server endpoint for alerting v1.") + + fs.StringVar(&o.PrometheusEndpoint, "alerting-prometheus-endpoint", c.PrometheusEndpoint, + "Prometheus service endpoint from which built-in alerting rules are fetched(alerting v2alpha1 or higher required)") + fs.StringVar(&o.ThanosRulerEndpoint, "alerting-thanos-ruler-endpoint", c.ThanosRulerEndpoint, + "Thanos ruler service endpoint from which custom alerting rules are fetched(alerting v2alpha1 or higher required)") + fs.StringVar(&o.ThanosRuleResourceLabels, "alerting-thanos-rule-resource-labels", c.ThanosRuleResourceLabels, + "Labels used by Thanos Ruler to select PrometheusRule custom resources. eg: thanosruler=thanos-ruler,role=custom-alerting-rules (alerting v2alpha1 or higher required)") } diff --git a/pkg/simple/client/customalerting/rule_client.go b/pkg/simple/client/alerting/rule_client.go similarity index 99% rename from pkg/simple/client/customalerting/rule_client.go rename to pkg/simple/client/alerting/rule_client.go index db1385fa..e0d82b1b 100644 --- a/pkg/simple/client/customalerting/rule_client.go +++ b/pkg/simple/client/alerting/rule_client.go @@ -1,4 +1,4 @@ -package customalerting +package alerting import ( "context" diff --git a/pkg/simple/client/customalerting/rule_client_test.go b/pkg/simple/client/alerting/rule_client_test.go similarity index 99% rename from pkg/simple/client/customalerting/rule_client_test.go rename to pkg/simple/client/alerting/rule_client_test.go index 420290d6..5d3f800e 100644 --- a/pkg/simple/client/customalerting/rule_client_test.go +++ b/pkg/simple/client/alerting/rule_client_test.go @@ -1,4 +1,4 @@ -package customalerting +package alerting import ( "context" diff --git a/pkg/simple/client/customalerting/types.go b/pkg/simple/client/alerting/types.go similarity index 98% rename from pkg/simple/client/customalerting/types.go rename to pkg/simple/client/alerting/types.go index 53b5de7d..d45d1a87 100644 --- a/pkg/simple/client/customalerting/types.go +++ b/pkg/simple/client/alerting/types.go @@ -1,4 +1,4 @@ -package customalerting +package alerting import ( "time" diff --git a/pkg/simple/client/customalerting/options.go b/pkg/simple/client/customalerting/options.go deleted file mode 100644 index e5b4671a..00000000 --- a/pkg/simple/client/customalerting/options.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -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 customalerting - -import ( - "fmt" - "strings" - - "github.com/spf13/pflag" - "kubesphere.io/kubesphere/pkg/utils/reflectutils" -) - -type Options struct { - PrometheusEndpoint string `json:"prometheusEndpoint" yaml:"prometheusEndpoint"` - ThanosRulerEndpoint string `json:"thanosRulerEndpoint" yaml:"thanosRulerEndpoint"` - ThanosRuleResourceLabels string `json:"thanosRuleResourceLabels" yaml:"thanosRuleResourceLabels"` -} - -func NewOptions() *Options { - return &Options{} -} - -func (o *Options) ApplyTo(options *Options) { - reflectutils.Override(options, o) -} - -func (o *Options) Validate() []error { - errs := []error{} - - if len(o.ThanosRuleResourceLabels) > 0 { - lblStrings := strings.Split(o.ThanosRuleResourceLabels, ",") - for _, lblString := range lblStrings { - if len(lblString) > 0 { - lbl := strings.Split(lblString, "=") - if len(lbl) != 2 { - errs = append(errs, fmt.Errorf("invalid thanos-rule-resource-labels arg: %s", o.ThanosRuleResourceLabels)) - } - } - } - } - - return errs -} - -func (o *Options) AddFlags(fs *pflag.FlagSet, c *Options) { - fs.StringVar(&o.PrometheusEndpoint, "prometheus-endpoint", c.PrometheusEndpoint, - "Prometheus service endpoint from which built-in alerting rules are gotten.") - fs.StringVar(&o.ThanosRulerEndpoint, "thanos-ruler-endpoint", c.ThanosRulerEndpoint, - "Thanos ruler service endpoint from which custom alerting rules are gotten.") - fs.StringVar(&o.ThanosRuleResourceLabels, "thanos-rule-resource-labels", c.ThanosRuleResourceLabels, - "The labels will be added to prometheusrule custom resources to be selected by thanos ruler. eg: thanosruler=thanos-ruler,role=custom-alerting-rules") -} diff --git a/tools/cmd/doc-gen/main.go b/tools/cmd/doc-gen/main.go index d2b8ec0a..78e4e5cd 100644 --- a/tools/cmd/doc-gen/main.go +++ b/tools/cmd/doc-gen/main.go @@ -37,8 +37,8 @@ import ( "kubesphere.io/kubesphere/pkg/apiserver/runtime" "kubesphere.io/kubesphere/pkg/constants" "kubesphere.io/kubesphere/pkg/informers" + alertingv2alpha1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2alpha1" clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1" - customalertingv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/customalerting/v1alpha1" devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2" devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3" iamv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2" @@ -129,7 +129,7 @@ func generateSwaggerJson() []byte { urlruntime.Must(terminalv1alpha2.AddToContainer(container, clientsets.Kubernetes(), nil)) urlruntime.Must(metricsv1alpha2.AddToContainer(container)) urlruntime.Must(networkv1alpha2.AddToContainer(container, "")) - urlruntime.Must(customalertingv1alpha1.AddToContainer(container, informerFactory, nil, nil, nil)) + urlruntime.Must(alertingv2alpha1.AddToContainer(container, informerFactory, nil, nil, nil)) config := restfulspec.Config{ WebServices: container.RegisteredWebServices(), -- GitLab