custom alerting use the same API group and flagset to alerting

Signed-off-by: junotx <junotx@126.com>
This commit is contained in:
junotx
2021-01-12 16:43:13 +08:00
parent 6f9d306368
commit 514fec7eb4
21 changed files with 261 additions and 294 deletions

View File

@@ -28,11 +28,11 @@ import (
"kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme" "kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
"kubesphere.io/kubesphere/pkg/informers" "kubesphere.io/kubesphere/pkg/informers"
genericoptions "kubesphere.io/kubesphere/pkg/server/options" genericoptions "kubesphere.io/kubesphere/pkg/server/options"
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/cache" "kubesphere.io/kubesphere/pkg/simple/client/cache"
runtimecache "sigs.k8s.io/controller-runtime/pkg/cache" runtimecache "sigs.k8s.io/controller-runtime/pkg/cache"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting"
"kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins"
eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/k8s" "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.MultiClusterOptions.AddFlags(fss.FlagSet("multicluster"), s.MultiClusterOptions)
s.EventsOptions.AddFlags(fss.FlagSet("events"), s.EventsOptions) s.EventsOptions.AddFlags(fss.FlagSet("events"), s.EventsOptions)
s.AuditingOptions.AddFlags(fss.FlagSet("auditing"), s.AuditingOptions) 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") fs = fss.FlagSet("klog")
local := flag.NewFlagSet("klog", flag.ExitOnError) local := flag.NewFlagSet("klog", flag.ExitOnError)
@@ -201,12 +201,12 @@ func (s *ServerRunOptions) NewAPIServer(stopCh <-chan struct{}) (*apiserver.APIS
apiServer.OpenpitrixClient = opClient apiServer.OpenpitrixClient = opClient
} }
if s.CustomAlertingOptions != nil { if s.AlertingOptions != nil && (s.AlertingOptions.PrometheusEndpoint != "" || s.AlertingOptions.ThanosRulerEndpoint != "") {
customAlertingClient, err := customalerting.NewRuleClient(s.CustomAlertingOptions) alertingClient, err := alerting.NewRuleClient(s.AlertingOptions)
if err != nil { 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{ server := &http.Server{

View File

@@ -34,7 +34,7 @@ func (s *ServerRunOptions) Validate() []error {
errors = append(errors, s.AuthorizationOptions.Validate()...) errors = append(errors, s.AuthorizationOptions.Validate()...)
errors = append(errors, s.EventsOptions.Validate()...) errors = append(errors, s.EventsOptions.Validate()...)
errors = append(errors, s.AuditingOptions.Validate()...) errors = append(errors, s.AuditingOptions.Validate()...)
errors = append(errors, s.CustomAlertingOptions.Validate()...) errors = append(errors, s.AlertingOptions.Validate()...)
return errors return errors
} }

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package v1alpha1 package v2alpha1
import ( import (
"regexp" "regexp"

View File

@@ -49,9 +49,9 @@ import (
"kubesphere.io/kubesphere/pkg/apiserver/request" "kubesphere.io/kubesphere/pkg/apiserver/request"
"kubesphere.io/kubesphere/pkg/informers" "kubesphere.io/kubesphere/pkg/informers"
alertingv1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v1" alertingv1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v1"
alertingv2alpha1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2alpha1"
clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1" clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1"
configv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/config/v1alpha2" configv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/config/v1alpha2"
customalertingv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/customalerting/v1alpha1"
devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2" devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2"
devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3" devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3"
iamapi "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2" 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/iam/im"
"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/loginrecord" "kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/loginrecord"
"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/user" "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/auditing"
"kubesphere.io/kubesphere/pkg/simple/client/cache" "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/devops"
"kubesphere.io/kubesphere/pkg/simple/client/events" "kubesphere.io/kubesphere/pkg/simple/client/events"
"kubesphere.io/kubesphere/pkg/simple/client/k8s" "kubesphere.io/kubesphere/pkg/simple/client/k8s"
@@ -146,7 +146,7 @@ type APIServer struct {
AuditingClient auditing.Client AuditingClient auditing.Client
CustomAlertingClient customalerting.RuleClient AlertingClient alerting.RuleClient
// controller-runtime cache // controller-runtime cache
RuntimeCache runtimecache.Cache RuntimeCache runtimecache.Cache
@@ -239,9 +239,9 @@ func (s *APIServer) installKubeSphereAPIs() {
s.InformerFactory.KubernetesSharedInformerFactory())) s.InformerFactory.KubernetesSharedInformerFactory()))
urlruntime.Must(notificationv1.AddToContainer(s.container, s.Config.NotificationOptions.Endpoint)) urlruntime.Must(notificationv1.AddToContainer(s.container, s.Config.NotificationOptions.Endpoint))
urlruntime.Must(alertingv1.AddToContainer(s.container, s.Config.AlertingOptions.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(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) { func (s *APIServer) Run(stopCh <-chan struct{}) (err error) {

View File

@@ -25,7 +25,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/alerting" "kubesphere.io/kubesphere/pkg/simple/client/alerting"
auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/cache" "kubesphere.io/kubesphere/pkg/simple/client/cache"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting"
"kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins"
eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/k8s" "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"` AuditingOptions *auditingclient.Options `json:"auditing,omitempty" yaml:"auditing,omitempty" mapstructure:"auditing"`
AlertingOptions *alerting.Options `json:"alerting,omitempty" yaml:"alerting,omitempty" mapstructure:"alerting"` AlertingOptions *alerting.Options `json:"alerting,omitempty" yaml:"alerting,omitempty" mapstructure:"alerting"`
NotificationOptions *notification.Options `json:"notification,omitempty" yaml:"notification,omitempty" mapstructure:"notification"` 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 // newConfig creates a default non-empty Config
@@ -122,7 +120,6 @@ func New() *Config {
MultiClusterOptions: multicluster.NewOptions(), MultiClusterOptions: multicluster.NewOptions(),
EventsOptions: eventsclient.NewElasticSearchOptions(), EventsOptions: eventsclient.NewElasticSearchOptions(),
AuditingOptions: auditingclient.NewElasticSearchOptions(), AuditingOptions: auditingclient.NewElasticSearchOptions(),
CustomAlertingOptions: customalerting.NewOptions(),
} }
} }
@@ -250,7 +247,8 @@ func (conf *Config) stripEmptyOptions() {
conf.S3Options = nil 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 conf.AlertingOptions = nil
} }

View File

@@ -28,7 +28,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/alerting" "kubesphere.io/kubesphere/pkg/simple/client/alerting"
auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch" auditingclient "kubesphere.io/kubesphere/pkg/simple/client/auditing/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/cache" "kubesphere.io/kubesphere/pkg/simple/client/cache"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting"
"kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins" "kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins"
eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch" eventsclient "kubesphere.io/kubesphere/pkg/simple/client/events/elasticsearch"
"kubesphere.io/kubesphere/pkg/simple/client/k8s" "kubesphere.io/kubesphere/pkg/simple/client/k8s"
@@ -120,6 +119,10 @@ func newTestConfig() (*Config, error) {
}, },
AlertingOptions: &alerting.Options{ AlertingOptions: &alerting.Options{
Endpoint: "http://alerting-client-server.kubesphere-alerting-system.svc:9200/api", 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: &notification.Options{ NotificationOptions: &notification.Options{
Endpoint: "http://notification.kubesphere-alerting-system.svc:9200", Endpoint: "http://notification.kubesphere-alerting-system.svc:9200",
@@ -157,11 +160,6 @@ func newTestConfig() (*Config, error) {
IndexPrefix: "ks-logstash-auditing", IndexPrefix: "ks-logstash-auditing",
Version: "6", 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 return conf, nil
} }

View File

@@ -105,7 +105,7 @@ const (
EventsQueryTag = "Events Query" EventsQueryTag = "Events Query"
AuditingQueryTag = "Auditing Query" AuditingQueryTag = "Auditing Query"
CustomAlertingTag = "Custom Alerting" AlertingTag = "Alerting"
) )
var ( var (

View File

@@ -14,35 +14,35 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package v1alpha1 package v2alpha1
import ( import (
"github.com/emicklei/go-restful" "github.com/emicklei/go-restful"
promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned"
"k8s.io/klog" "k8s.io/klog"
ksapi "kubesphere.io/kubesphere/pkg/api" 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" "kubesphere.io/kubesphere/pkg/informers"
customalertingmodels "kubesphere.io/kubesphere/pkg/models/customalerting" alertingmodels "kubesphere.io/kubesphere/pkg/models/alerting"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/alerting"
) )
type handler struct { type handler struct {
operator customalertingmodels.Operator operator alertingmodels.Operator
} }
func newHandler(informers informers.InformerFactory, func newHandler(informers informers.InformerFactory,
promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient,
option *customalerting.Options) *handler { option *alerting.Options) *handler {
return &handler{ return &handler{
operator: customalertingmodels.NewOperator( operator: alertingmodels.NewOperator(
informers, promResourceClient, ruleClient, option), informers, promResourceClient, ruleClient, option),
} }
} }
func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *restful.Response) { func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace") namespace := req.PathParameter("namespace")
query, err := v1alpha1.ParseAlertingRuleQueryParams(req) query, err := v2alpha1.ParseAlertingRuleQueryParams(req)
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
@@ -53,7 +53,7 @@ func (h *handler) handleListCustomAlertingRules(req *restful.Request, resp *rest
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) 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) { func (h *handler) handleListCustomRulesAlerts(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace") namespace := req.PathParameter("namespace")
query, err := v1alpha1.ParseAlertQueryParams(req) query, err := v2alpha1.ParseAlertQueryParams(req)
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
@@ -76,7 +76,7 @@ func (h *handler) handleListCustomRulesAlerts(req *restful.Request, resp *restfu
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)
@@ -94,9 +94,9 @@ func (h *handler) handleGetCustomAlertingRule(req *restful.Request, resp *restfu
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)
@@ -118,9 +118,9 @@ func (h *handler) handleListCustomRuleAlerts(req *restful.Request, resp *restful
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) 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) { func (h *handler) handleCreateCustomAlertingRule(req *restful.Request, resp *restful.Response) {
namespace := req.PathParameter("namespace") namespace := req.PathParameter("namespace")
var rule v1alpha1.PostableAlertingRule var rule v2alpha1.PostableAlertingRule
if err := req.ReadEntity(&rule); err != nil { if err := req.ReadEntity(&rule); err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
@@ -149,9 +149,9 @@ func (h *handler) handleCreateCustomAlertingRule(req *restful.Request, resp *res
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
case err == v1alpha1.ErrAlertingRuleAlreadyExists: case err == v2alpha1.ErrAlertingRuleAlreadyExists:
ksapi.HandleConflict(resp, nil, err) ksapi.HandleConflict(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)
@@ -164,7 +164,7 @@ func (h *handler) handleUpdateCustomAlertingRule(req *restful.Request, resp *res
namespace := req.PathParameter("namespace") namespace := req.PathParameter("namespace")
ruleName := req.PathParameter("rule_name") ruleName := req.PathParameter("rule_name")
var rule v1alpha1.PostableAlertingRule var rule v2alpha1.PostableAlertingRule
if err := req.ReadEntity(&rule); err != nil { if err := req.ReadEntity(&rule); err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
@@ -180,9 +180,9 @@ func (h *handler) handleUpdateCustomAlertingRule(req *restful.Request, resp *res
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)
@@ -199,9 +199,9 @@ func (h *handler) handleDeleteCustomAlertingRule(req *restful.Request, resp *res
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrThanosRulerNotEnabled: case err == v2alpha1.ErrThanosRulerNotEnabled:
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) 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) { func (h *handler) handleListBuiltinAlertingRules(req *restful.Request, resp *restful.Response) {
query, err := v1alpha1.ParseAlertingRuleQueryParams(req) query, err := v2alpha1.ParseAlertingRuleQueryParams(req)
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, 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) { func (h *handler) handleListBuiltinRulesAlerts(req *restful.Request, resp *restful.Response) {
query, err := v1alpha1.ParseAlertQueryParams(req) query, err := v2alpha1.ParseAlertQueryParams(req)
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
ksapi.HandleBadRequest(resp, nil, err) ksapi.HandleBadRequest(resp, nil, err)
@@ -251,7 +251,7 @@ func (h *handler) handleGetBuiltinAlertingRule(req *restful.Request, resp *restf
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)
@@ -273,7 +273,7 @@ func (h *handler) handleListBuiltinRuleAlerts(req *restful.Request, resp *restfu
if err != nil { if err != nil {
klog.Error(err) klog.Error(err)
switch { switch {
case err == v1alpha1.ErrAlertingRuleNotFound: case err == v2alpha1.ErrAlertingRuleNotFound:
ksapi.HandleNotFound(resp, nil, err) ksapi.HandleNotFound(resp, nil, err)
default: default:
ksapi.HandleInternalError(resp, nil, err) ksapi.HandleInternalError(resp, nil, err)

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package v1alpha1 package v2alpha1
import ( import (
"net/http" "net/http"
@@ -24,22 +24,22 @@ import (
promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned" promresourcesclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
ksapi "kubesphere.io/kubesphere/pkg/api" 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/apiserver/runtime"
"kubesphere.io/kubesphere/pkg/constants" "kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/informers" "kubesphere.io/kubesphere/pkg/informers"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/alerting"
) )
const ( 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, func AddToContainer(container *restful.Container, informers informers.InformerFactory,
promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient,
option *customalerting.Options) error { option *alerting.Options) error {
handler := newHandler(informers, promResourceClient, ruleClient, option) 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("sort_type", "sort type, one of `asc`, `desc`")).
Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). 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")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/alerts"). ws.Route(ws.GET("/alerts").
To(handler.handleListCustomRulesAlerts). 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("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("offset", "offset of the result set").DataType("integer").DefaultValue("0")).
Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/rules/{rule_name}"). ws.Route(ws.GET("/rules/{rule_name}").
To(handler.handleGetCustomAlertingRule). To(handler.handleGetCustomAlertingRule).
Doc("get the cluster-level custom alerting rule with the specified name"). Doc("get the cluster-level custom alerting rule with the specified name").
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/rules/{rule_name}/alerts"). ws.Route(ws.GET("/rules/{rule_name}/alerts").
To(handler.handleListCustomRuleAlerts). To(handler.handleListCustomRuleAlerts).
Doc("list the alerts of the cluster-level custom alerting rule with the specified name"). Doc("list the alerts of the cluster-level custom alerting rule with the specified name").
Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.POST("/rules"). ws.Route(ws.POST("/rules").
To(handler.handleCreateCustomAlertingRule). To(handler.handleCreateCustomAlertingRule).
Doc("create a cluster-level custom alerting rule"). Doc("create a cluster-level custom alerting rule").
Reads(customalertingv1alpha1.PostableAlertingRule{}). Reads(alertingv2alpha1.PostableAlertingRule{}).
Returns(http.StatusOK, ksapi.StatusOK, nil). 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}"). ws.Route(ws.PUT("/rules/{rule_name}").
To(handler.handleUpdateCustomAlertingRule). To(handler.handleUpdateCustomAlertingRule).
Doc("update the cluster-level custom alerting rule with the specified name"). Doc("update the cluster-level custom alerting rule with the specified name").
Reads(customalertingv1alpha1.PostableAlertingRule{}). Reads(alertingv2alpha1.PostableAlertingRule{}).
Returns(http.StatusOK, ksapi.StatusOK, nil). 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}"). ws.Route(ws.DELETE("/rules/{rule_name}").
To(handler.handleDeleteCustomAlertingRule). To(handler.handleDeleteCustomAlertingRule).
Doc("delete the cluster-level custom alerting rule with the specified name"). Doc("delete the cluster-level custom alerting rule with the specified name").
Returns(http.StatusOK, ksapi.StatusOK, nil). 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"). ws.Route(ws.GET("/namespaces/{namespace}/rules").
To(handler.handleListCustomAlertingRules). 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("sort_type", "sort type, one of `asc`, `desc`")).
Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). 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")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/namespaces/{namespace}/alerts"). ws.Route(ws.GET("/namespaces/{namespace}/alerts").
To(handler.handleListCustomRulesAlerts). 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("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("offset", "offset of the result set").DataType("integer").DefaultValue("0")).
Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}"). ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}").
To(handler.handleGetCustomAlertingRule). To(handler.handleGetCustomAlertingRule).
Doc("get the custom alerting rule with the specified name in the specified namespace"). Doc("get the custom alerting rule with the specified name in the specified namespace").
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}/alerts"). ws.Route(ws.GET("/namespaces/{namespace}/rules/{rule_name}/alerts").
To(handler.handleListCustomRuleAlerts). To(handler.handleListCustomRuleAlerts).
Doc("get the alerts of the custom alerting rule with the specified name in the specified namespace"). Doc("get the alerts of the custom alerting rule with the specified name in the specified namespace").
Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.POST("/namespaces/{namespace}/rules"). ws.Route(ws.POST("/namespaces/{namespace}/rules").
To(handler.handleCreateCustomAlertingRule). To(handler.handleCreateCustomAlertingRule).
Doc("create a custom alerting rule in the specified namespace"). Doc("create a custom alerting rule in the specified namespace").
Reads(customalertingv1alpha1.PostableAlertingRule{}). Reads(alertingv2alpha1.PostableAlertingRule{}).
Returns(http.StatusOK, ksapi.StatusOK, ""). 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}"). ws.Route(ws.PUT("/namespaces/{namespace}/rules/{rule_name}").
To(handler.handleUpdateCustomAlertingRule). To(handler.handleUpdateCustomAlertingRule).
Doc("update the custom alerting rule with the specified name in the specified namespace"). 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, ""). 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}"). ws.Route(ws.DELETE("/namespaces/{namespace}/rules/{rule_name}").
To(handler.handleDeleteCustomAlertingRule). To(handler.handleDeleteCustomAlertingRule).
Doc("delete the custom alerting rule with the specified rule name in the specified namespace"). Doc("delete the custom alerting rule with the specified rule name in the specified namespace").
Returns(http.StatusOK, ksapi.StatusOK, nil). Returns(http.StatusOK, ksapi.StatusOK, nil).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/builtin/rules"). ws.Route(ws.GET("/builtin/rules").
To(handler.handleListBuiltinAlertingRules). 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("sort_type", "sort type, one of `asc`, `desc`")).
Param(ws.QueryParameter("offset", "offset of the result set").DataType("integer").DefaultValue("0")). 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")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRuleList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRuleList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/builtin/alerts"). ws.Route(ws.GET("/builtin/alerts").
To(handler.handleListBuiltinRulesAlerts). 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("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("offset", "offset of the result set").DataType("integer").DefaultValue("0")).
Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")). Param(ws.QueryParameter("limit", "limit size of the result set").DataType("integer").DefaultValue("10")).
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.AlertList{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.AlertList{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/builtin/rules/{rule_id}"). ws.Route(ws.GET("/builtin/rules/{rule_id}").
To(handler.handleGetBuiltinAlertingRule). To(handler.handleGetBuiltinAlertingRule).
Doc("get the builtin(non-custom) alerting rule with specified id"). Doc("get the builtin(non-custom) alerting rule with specified id").
Returns(http.StatusOK, ksapi.StatusOK, customalertingv1alpha1.GettableAlertingRule{}). Returns(http.StatusOK, ksapi.StatusOK, alertingv2alpha1.GettableAlertingRule{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
ws.Route(ws.GET("/builtin/rules/{rule_id}/alerts"). ws.Route(ws.GET("/builtin/rules/{rule_id}/alerts").
To(handler.handleListBuiltinRuleAlerts). To(handler.handleListBuiltinRuleAlerts).
Doc("list the alerts of the builtin(non-custom) alerting rule with the specified id"). Doc("list the alerts of the builtin(non-custom) alerting rule with the specified id").
Returns(http.StatusOK, ksapi.StatusOK, []customalertingv1alpha1.Alert{}). Returns(http.StatusOK, ksapi.StatusOK, []alertingv2alpha1.Alert{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.CustomAlertingTag})) Metadata(restfulspec.KeyOpenAPITags, []string{constants.AlertingTag}))
container.Add(ws) container.Add(ws)

View File

@@ -1,4 +1,4 @@
package customalerting package alerting
import ( import (
"context" "context"
@@ -13,11 +13,11 @@ import (
"k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/intstr"
coreinformersv1 "k8s.io/client-go/informers/core/v1" 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/constants"
"kubesphere.io/kubesphere/pkg/informers" "kubesphere.io/kubesphere/pkg/informers"
"kubesphere.io/kubesphere/pkg/models/customalerting/rules" "kubesphere.io/kubesphere/pkg/models/alerting/rules"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting" "kubesphere.io/kubesphere/pkg/simple/client/alerting"
) )
const ( const (
@@ -41,36 +41,36 @@ var (
type Operator interface { type Operator interface {
// ListCustomAlertingRules lists the custom alerting rules. // ListCustomAlertingRules lists the custom alerting rules.
ListCustomAlertingRules(ctx context.Context, namespace string, 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 lists the alerts of the custom alerting rules.
ListCustomRulesAlerts(ctx context.Context, namespace string, 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 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 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 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 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 deletes the custom alerting rule with the given name.
DeleteCustomAlertingRule(ctx context.Context, namespace, ruleName string) error DeleteCustomAlertingRule(ctx context.Context, namespace, ruleName string) error
// ListBuiltinAlertingRules lists the builtin(non-custom) alerting rules // ListBuiltinAlertingRules lists the builtin(non-custom) alerting rules
ListBuiltinAlertingRules(ctx context.Context, 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 lists the alerts of the builtin(non-custom) alerting rules
ListBuiltinRulesAlerts(ctx context.Context, 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 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 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, func NewOperator(informers informers.InformerFactory,
promResourceClient promresourcesclient.Interface, ruleClient customalerting.RuleClient, promResourceClient promresourcesclient.Interface, ruleClient alerting.RuleClient,
option *customalerting.Options) Operator { option *alerting.Options) Operator {
o := operator{ o := operator{
namespaceInformer: informers.KubernetesSharedInformerFactory().Core().V1().Namespaces(), namespaceInformer: informers.KubernetesSharedInformerFactory().Core().V1().Namespaces(),
@@ -101,7 +101,7 @@ func NewOperator(informers informers.InformerFactory,
} }
type operator struct { type operator struct {
ruleClient customalerting.RuleClient ruleClient alerting.RuleClient
promResourceClient promresourcesclient.Interface promResourceClient promresourcesclient.Interface
@@ -117,14 +117,14 @@ type operator struct {
} }
func (o *operator) ListCustomAlertingRules(ctx context.Context, namespace string, 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 == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
} }
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) 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, 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 == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
} }
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) 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) ( 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 == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
} }
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) 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) ( func (o *operator) ListCustomRuleAlerts(ctx context.Context, namespace, ruleName string) (
[]*v1alpha1.Alert, error) { []*v2alpha1.Alert, error) {
rule, err := o.GetCustomAlertingRule(ctx, namespace, ruleName) rule, err := o.GetCustomAlertingRule(ctx, namespace, ruleName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if rule == nil { if rule == nil {
return nil, v1alpha1.ErrAlertingRuleNotFound return nil, v2alpha1.ErrAlertingRuleNotFound
} }
return rule.Alerts, nil return rule.Alerts, nil
} }
func (o *operator) ListBuiltinAlertingRules(ctx context.Context, func (o *operator) ListBuiltinAlertingRules(ctx context.Context,
queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) { queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) {
alertingRules, err := o.listBuiltinAlertingRules(ctx) alertingRules, err := o.listBuiltinAlertingRules(ctx)
if err != nil { if err != nil {
@@ -208,7 +208,7 @@ func (o *operator) ListBuiltinAlertingRules(ctx context.Context,
} }
func (o *operator) ListBuiltinRulesAlerts(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) alertingRules, err := o.listBuiltinAlertingRules(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -218,24 +218,24 @@ func (o *operator) ListBuiltinRulesAlerts(ctx context.Context,
} }
func (o *operator) GetBuiltinAlertingRule(ctx context.Context, ruleId string) ( func (o *operator) GetBuiltinAlertingRule(ctx context.Context, ruleId string) (
*v1alpha1.GettableAlertingRule, error) { *v2alpha1.GettableAlertingRule, error) {
return o.getBuiltinAlertingRule(ctx, ruleId) 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) rule, err := o.getBuiltinAlertingRule(ctx, ruleId)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if rule == nil { if rule == nil {
return nil, v1alpha1.ErrAlertingRuleNotFound return nil, v2alpha1.ErrAlertingRuleNotFound
} }
return rule.Alerts, nil return rule.Alerts, nil
} }
func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag string, func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag string,
queryParams *v1alpha1.AlertingRuleQueryParams) (*v1alpha1.GettableAlertingRuleList, error) { queryParams *v2alpha1.AlertingRuleQueryParams) (*v2alpha1.GettableAlertingRuleList, error) {
namespace := rulerNamespace namespace := rulerNamespace
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace)
@@ -243,7 +243,7 @@ func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag stri
return nil, err return nil, err
} }
alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v1alpha1.RuleLevelCluster) alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v2alpha1.RuleLevelCluster)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -252,7 +252,7 @@ func (o *operator) ListClusterAlertingRules(ctx context.Context, customFlag stri
} }
func (o *operator) ListClusterRulesAlerts(ctx context.Context, func (o *operator) ListClusterRulesAlerts(ctx context.Context,
queryParams *v1alpha1.AlertQueryParams) (*v1alpha1.AlertList, error) { queryParams *v2alpha1.AlertQueryParams) (*v2alpha1.AlertList, error) {
namespace := rulerNamespace namespace := rulerNamespace
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace)
@@ -260,7 +260,7 @@ func (o *operator) ListClusterRulesAlerts(ctx context.Context,
return nil, err return nil, err
} }
alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v1alpha1.RuleLevelCluster) alertingRules, err := o.listCustomAlertingRules(ctx, ruleNamespace, v2alpha1.RuleLevelCluster)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -269,14 +269,14 @@ func (o *operator) ListClusterRulesAlerts(ctx context.Context,
} }
func (o *operator) listCustomAlertingRules(ctx context.Context, ruleNamespace *corev1.Namespace, 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() ruler, err := o.getThanosRuler()
if err != nil { if err != nil {
return nil, err return nil, err
} }
if ruler == nil { if ruler == nil {
return nil, v1alpha1.ErrThanosRulerNotEnabled return nil, v2alpha1.ErrThanosRulerNotEnabled
} }
resourceRulesMap, err := o.resourceRuleCache.ListRules(ruler, ruleNamespace, 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, 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() ruler, err := o.getThanosRuler()
if err != nil { if err != nil {
return nil, err return nil, err
} }
if ruler == nil { if ruler == nil {
return nil, v1alpha1.ErrThanosRulerNotEnabled return nil, v2alpha1.ErrThanosRulerNotEnabled
} }
resourceRule, err := o.resourceRuleCache.GetRule(ruler, ruleNamespace, resourceRule, err := o.resourceRuleCache.GetRule(ruler, ruleNamespace,
@@ -314,7 +314,7 @@ func (o *operator) getCustomAlertingRule(ctx context.Context, ruleNamespace *cor
return nil, err return nil, err
} }
if resourceRule == nil { if resourceRule == nil {
return nil, v1alpha1.ErrAlertingRuleNotFound return nil, v2alpha1.ErrAlertingRuleNotFound
} }
ruleGroups, err := o.ruleClient.ThanosRules(ctx) 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) ( func (o *operator) listBuiltinAlertingRules(ctx context.Context) (
[]*v1alpha1.GettableAlertingRule, error) { []*v2alpha1.GettableAlertingRule, error) {
ruler, err := o.getPrometheusRuler() ruler, err := o.getPrometheusRuler()
if err != nil { if err != nil {
@@ -344,8 +344,8 @@ func (o *operator) listBuiltinAlertingRules(ctx context.Context) (
if ruler == nil { if ruler == nil {
// for out-cluster prometheus // for out-cluster prometheus
return rules.ParseAlertingRules(ruleGroups, false, v1alpha1.RuleLevelCluster, return rules.ParseAlertingRules(ruleGroups, false, v2alpha1.RuleLevelCluster,
func(group, id string, rule *customalerting.AlertingRule) bool { func(group, id string, rule *alerting.AlertingRule) bool {
return true return true
}) })
} }
@@ -364,11 +364,11 @@ func (o *operator) listBuiltinAlertingRules(ctx context.Context) (
return rules.GetAlertingRulesStatus(ruleNamespace.Name, &rules.ResourceRuleChunk{ return rules.GetAlertingRulesStatus(ruleNamespace.Name, &rules.ResourceRuleChunk{
ResourceRulesMap: resourceRulesMap, ResourceRulesMap: resourceRulesMap,
Custom: false, Custom: false,
Level: v1alpha1.RuleLevelCluster, Level: v2alpha1.RuleLevelCluster,
}, ruleGroups, ruler.ExternalLabels()) }, 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() ruler, err := o.getPrometheusRuler()
if err != nil { if err != nil {
@@ -382,18 +382,18 @@ func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (*
if ruler == nil { if ruler == nil {
// for out-cluster prometheus // for out-cluster prometheus
alertingRules, err := rules.ParseAlertingRules(ruleGroups, false, v1alpha1.RuleLevelCluster, alertingRules, err := rules.ParseAlertingRules(ruleGroups, false, v2alpha1.RuleLevelCluster,
func(group, id string, rule *customalerting.AlertingRule) bool { func(group, id string, rule *alerting.AlertingRule) bool {
return ruleId == id return ruleId == id
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
if len(alertingRules) == 0 { if len(alertingRules) == 0 {
return nil, v1alpha1.ErrAlertingRuleNotFound return nil, v2alpha1.ErrAlertingRuleNotFound
} }
sort.Slice(alertingRules, func(i, j int) bool { 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 return alertingRules[0], nil
} }
@@ -410,28 +410,28 @@ func (o *operator) getBuiltinAlertingRule(ctx context.Context, ruleId string) (*
} }
if resourceRule == nil { if resourceRule == nil {
return nil, v1alpha1.ErrAlertingRuleNotFound return nil, v2alpha1.ErrAlertingRuleNotFound
} }
return rules.GetAlertingRuleStatus(ruleNamespace.Name, &rules.ResourceRule{ return rules.GetAlertingRuleStatus(ruleNamespace.Name, &rules.ResourceRule{
ResourceRuleItem: *resourceRule, ResourceRuleItem: *resourceRule,
Custom: false, Custom: false,
Level: v1alpha1.RuleLevelCluster, Level: v2alpha1.RuleLevelCluster,
}, ruleGroups, ruler.ExternalLabels()) }, ruleGroups, ruler.ExternalLabels())
} }
func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace string, func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace string,
rule *v1alpha1.PostableAlertingRule) error { rule *v2alpha1.PostableAlertingRule) error {
ruler, err := o.getThanosRuler() ruler, err := o.getThanosRuler()
if err != nil { if err != nil {
return err return err
} }
if ruler == nil { if ruler == nil {
return v1alpha1.ErrThanosRulerNotEnabled return v2alpha1.ErrThanosRulerNotEnabled
} }
var ( var (
level v1alpha1.RuleLevel level v2alpha1.RuleLevel
ruleResourceLabels = make(map[string]string) ruleResourceLabels = make(map[string]string)
) )
for k, v := range o.thanosRuleResourceLabels { for k, v := range o.thanosRuleResourceLabels {
@@ -439,9 +439,9 @@ func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace strin
} }
if namespace == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace) expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace)
if err != nil { if err != nil {
return err return err
@@ -461,7 +461,7 @@ func (o *operator) CreateCustomAlertingRule(ctx context.Context, namespace strin
return err return err
} }
if resourceRule != nil { if resourceRule != nil {
return v1alpha1.ErrAlertingRuleAlreadyExists return v2alpha1.ErrAlertingRuleAlreadyExists
} }
return ruler.AddAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, 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, func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name string,
rule *v1alpha1.PostableAlertingRule) error { rule *v2alpha1.PostableAlertingRule) error {
rule.Name = name rule.Name = name
@@ -478,11 +478,11 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name
return err return err
} }
if ruler == nil { if ruler == nil {
return v1alpha1.ErrThanosRulerNotEnabled return v2alpha1.ErrThanosRulerNotEnabled
} }
var ( var (
level v1alpha1.RuleLevel level v2alpha1.RuleLevel
ruleResourceLabels = make(map[string]string) ruleResourceLabels = make(map[string]string)
) )
for k, v := range o.thanosRuleResourceLabels { for k, v := range o.thanosRuleResourceLabels {
@@ -490,9 +490,9 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name
} }
if namespace == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace) expr, err := rules.InjectExprNamespaceLabel(rule.Query, namespace)
if err != nil { if err != nil {
return err return err
@@ -512,7 +512,7 @@ func (o *operator) UpdateCustomAlertingRule(ctx context.Context, namespace, name
return err return err
} }
if resourceRule == nil { if resourceRule == nil {
return v1alpha1.ErrAlertingRuleNotFound return v2alpha1.ErrAlertingRuleNotFound
} }
return ruler.UpdateAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, return ruler.UpdateAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector,
@@ -525,17 +525,17 @@ func (o *operator) DeleteCustomAlertingRule(ctx context.Context, namespace, name
return err return err
} }
if ruler == nil { if ruler == nil {
return v1alpha1.ErrThanosRulerNotEnabled return v2alpha1.ErrThanosRulerNotEnabled
} }
var ( var (
level v1alpha1.RuleLevel level v2alpha1.RuleLevel
) )
if namespace == "" { if namespace == "" {
namespace = rulerNamespace namespace = rulerNamespace
level = v1alpha1.RuleLevelCluster level = v2alpha1.RuleLevelCluster
} else { } else {
level = v1alpha1.RuleLevelNamespace level = v2alpha1.RuleLevelNamespace
} }
ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace) ruleNamespace, err := o.namespaceInformer.Lister().Get(namespace)
@@ -549,7 +549,7 @@ func (o *operator) DeleteCustomAlertingRule(ctx context.Context, namespace, name
return err return err
} }
if resourceRule == nil { if resourceRule == nil {
return v1alpha1.ErrAlertingRuleNotFound return v2alpha1.ErrAlertingRuleNotFound
} }
return ruler.DeleteAlertingRule(ctx, ruleNamespace, extraRuleResourceSelector, resourceRule.Group, name) 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 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{ return &promresourcesv1.Rule{
Alert: rule.Name, Alert: rule.Name,
Expr: intstr.FromString(rule.Query), Expr: intstr.FromString(rule.Query),
@@ -601,28 +601,28 @@ func parseToPrometheusRule(rule *v1alpha1.PostableAlertingRule) *promresourcesv1
} }
} }
func pageAlertingRules(alertingRules []*v1alpha1.GettableAlertingRule, func pageAlertingRules(alertingRules []*v2alpha1.GettableAlertingRule,
queryParams *v1alpha1.AlertingRuleQueryParams) *v1alpha1.GettableAlertingRuleList { queryParams *v2alpha1.AlertingRuleQueryParams) *v2alpha1.GettableAlertingRuleList {
alertingRules = queryParams.Filter(alertingRules) alertingRules = queryParams.Filter(alertingRules)
queryParams.Sort(alertingRules) queryParams.Sort(alertingRules)
return &v1alpha1.GettableAlertingRuleList{ return &v2alpha1.GettableAlertingRuleList{
Total: len(alertingRules), Total: len(alertingRules),
Items: queryParams.Sub(alertingRules), Items: queryParams.Sub(alertingRules),
} }
} }
func pageAlerts(alertingRules []*v1alpha1.GettableAlertingRule, func pageAlerts(alertingRules []*v2alpha1.GettableAlertingRule,
queryParams *v1alpha1.AlertQueryParams) *v1alpha1.AlertList { queryParams *v2alpha1.AlertQueryParams) *v2alpha1.AlertList {
var alerts []*v1alpha1.Alert var alerts []*v2alpha1.Alert
for _, rule := range alertingRules { for _, rule := range alertingRules {
alerts = append(alerts, queryParams.Filter(rule.Alerts)...) alerts = append(alerts, queryParams.Filter(rule.Alerts)...)
} }
queryParams.Sort(alerts) queryParams.Sort(alerts)
return &v1alpha1.AlertList{ return &v2alpha1.AlertList{
Total: len(alerts), Total: len(alerts),
Items: queryParams.Sub(alerts), Items: queryParams.Sub(alerts),
} }

View File

@@ -9,7 +9,7 @@ import (
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache" "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" "kubesphere.io/kubesphere/pkg/server/errors"
) )
@@ -150,7 +150,7 @@ func (c *RuleCache) GetRule(ruler Ruler, ruleNamespace *corev1.Namespace,
} else if l > 1 { } else if l > 1 {
// guarantees the stability of the get operations. // guarantees the stability of the get operations.
sort.Slice(rules, func(i, j int) bool { 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 return rules[0], nil

View File

@@ -2,7 +2,7 @@ package rules
import ( import (
promresourcesv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" 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 { type ResourceRuleCollection struct {
@@ -19,13 +19,13 @@ type ResourceRuleItem struct {
} }
type ResourceRule struct { type ResourceRule struct {
Level v1alpha1.RuleLevel Level v2alpha1.RuleLevel
Custom bool Custom bool
ResourceRuleItem ResourceRuleItem
} }
type ResourceRuleChunk struct { type ResourceRuleChunk struct {
Level v1alpha1.RuleLevel Level v2alpha1.RuleLevel
Custom bool Custom bool
ResourceRulesMap map[string]*ResourceRuleCollection ResourceRulesMap map[string]*ResourceRuleCollection
} }

View File

@@ -13,7 +13,7 @@ import (
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/labels"
"kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1"
) )
const ( const (
@@ -438,7 +438,7 @@ func (r *ThanosRuler) UpdateAlertingRule(ctx context.Context, ruleNamespace *cor
} }
if !found { if !found {
return v1alpha1.ErrAlertingRuleNotFound return v2alpha1.ErrAlertingRuleNotFound
} }
if !success { if !success {
@@ -478,7 +478,7 @@ func (r *ThanosRuler) DeleteAlertingRule(ctx context.Context, ruleNamespace *cor
} }
} }
if !success { if !success {
return v1alpha1.ErrAlertingRuleNotFound return v2alpha1.ErrAlertingRuleNotFound
} }
return nil return nil
} }

View File

@@ -1,6 +1,7 @@
package rules package rules
import ( import (
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
@@ -14,8 +15,7 @@ import (
"github.com/prometheus/prometheus/promql/parser" "github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/rules" "github.com/prometheus/prometheus/rules"
"k8s.io/klog" "k8s.io/klog"
"kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting"
) )
const ( const (
@@ -92,7 +92,7 @@ func GenResourceRuleIdIgnoreFormat(group string, rule *promresourcesv1.Rule) str
return prommodel.Fingerprint(prommodel.LabelsToSignature(lbls)).String() 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) { externalLabels func() map[string]string) (string, error) {
query, err := FormatExpr(epRule.Query) query, err := FormatExpr(epRule.Query)
if err != nil { 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. // GetAlertingRulesStatus mix rules from prometheusrule custom resources and rules from endpoints.
// Use rules from prometheusrule custom resources as the main reference. // Use rules from prometheusrule custom resources as the main reference.
func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, epRuleGroups []*customalerting.RuleGroup, func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk, epRuleGroups []*alerting.RuleGroup,
extLabels func() map[string]string) ([]*v1alpha1.GettableAlertingRule, error) { extLabels func() map[string]string) ([]*v2alpha1.GettableAlertingRule, error) {
var ( var (
idEpRules = make(map[string]*customalerting.AlertingRule) idEpRules = make(map[string]*alerting.AlertingRule)
nameIds = make(map[string][]string) nameIds = make(map[string][]string)
ret []*v1alpha1.GettableAlertingRule ret []*v2alpha1.GettableAlertingRule
) )
for _, group := range epRuleGroups { for _, group := range epRuleGroups {
fileShort := strings.TrimSuffix(filepath.Base(group.File), filepath.Ext(group.File)) 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 := len(rrArr); l > 0 {
if l > 1 { if l > 1 {
sort.Slice(rrArr, func(i, j int) bool { 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] resRule := rrArr[0]
@@ -181,7 +181,7 @@ func GetAlertingRulesStatus(ruleNamespace string, ruleChunk *ResourceRuleChunk,
} }
} else { } else {
// guarantee the ids of the builtin alerting rules not to be repeated // 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 _, resourceRules := range ruleChunk.ResourceRulesMap {
for id, rule := range resourceRules.IdRules { for id, rule := range resourceRules.IdRules {
if r := getAlertingRuleStatus(rule, idEpRules[id], ruleChunk.Custom, ruleChunk.Level); r != nil { 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 return ret, nil
} }
func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroups []*customalerting.RuleGroup, func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroups []*alerting.RuleGroup,
extLabels func() map[string]string) (*v1alpha1.GettableAlertingRule, error) { extLabels func() map[string]string) (*v2alpha1.GettableAlertingRule, error) {
if rule == nil || rule.Rule == nil { if rule == nil || rule.Rule == nil {
return nil, nil return nil, nil
} }
var epRules = make(map[string]*customalerting.AlertingRule) var epRules = make(map[string]*alerting.AlertingRule)
for _, group := range epRuleGroups { for _, group := range epRuleGroups {
fileShort := strings.TrimSuffix(filepath.Base(group.File), filepath.Ext(group.File)) fileShort := strings.TrimSuffix(filepath.Base(group.File), filepath.Ext(group.File))
if !strings.HasPrefix(fileShort, ruleNamespace+"-") { 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 { if rule.Custom {
// guarantees the stability of the get operations. // guarantees the stability of the get operations.
var ids []string var ids []string
@@ -234,7 +234,7 @@ func GetAlertingRuleStatus(ruleNamespace string, rule *ResourceRule, epRuleGroup
if l := len(ids); l > 0 { if l := len(ids); l > 0 {
if l > 1 { if l > 1 {
sort.Slice(ids, func(i, j int) bool { 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]] 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 return getAlertingRuleStatus(&rule.ResourceRuleItem, epRule, rule.Custom, rule.Level), nil
} }
func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.AlertingRule, func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *alerting.AlertingRule,
custom bool, level v1alpha1.RuleLevel) *v1alpha1.GettableAlertingRule { custom bool, level v2alpha1.RuleLevel) *v2alpha1.GettableAlertingRule {
if resRule == nil || resRule.Rule == nil { if resRule == nil || resRule.Rule == nil {
return nil return nil
} }
rule := v1alpha1.GettableAlertingRule{ rule := v2alpha1.GettableAlertingRule{
AlertingRule: v1alpha1.AlertingRule{ AlertingRule: v2alpha1.AlertingRule{
Id: resRule.Id, Id: resRule.Id,
Name: resRule.Rule.Alert, Name: resRule.Rule.Alert,
Query: resRule.Rule.Expr.String(), Query: resRule.Rule.Expr.String(),
@@ -289,7 +289,7 @@ func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.Ale
rule.State = aState rule.State = aState
} }
} }
rule.Alerts = append(rule.Alerts, &v1alpha1.Alert{ rule.Alerts = append(rule.Alerts, &v2alpha1.Alert{
ActiveAt: a.ActiveAt, ActiveAt: a.ActiveAt,
Labels: a.Labels, Labels: a.Labels,
Annotations: a.Annotations, Annotations: a.Annotations,
@@ -304,10 +304,10 @@ func getAlertingRuleStatus(resRule *ResourceRuleItem, epRule *customalerting.Ale
return &rule return &rule
} }
func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, level v1alpha1.RuleLevel, func ParseAlertingRules(epRuleGroups []*alerting.RuleGroup, custom bool, level v2alpha1.RuleLevel,
filterFunc func(group, ruleId string, rule *customalerting.AlertingRule) bool) ([]*v1alpha1.GettableAlertingRule, error) { 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 _, g := range epRuleGroups {
for _, r := range g.Rules { for _, r := range g.Rules {
id, err := GenEndpointRuleId(g.Name, r, nil) id, err := GenEndpointRuleId(g.Name, r, nil)
@@ -315,8 +315,8 @@ func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, l
return nil, err return nil, err
} }
if filterFunc(g.Name, id, r) { if filterFunc(g.Name, id, r) {
rule := &v1alpha1.GettableAlertingRule{ rule := &v2alpha1.GettableAlertingRule{
AlertingRule: v1alpha1.AlertingRule{ AlertingRule: v2alpha1.AlertingRule{
Id: id, Id: id,
Name: r.Name, Name: r.Name,
Query: r.Query, Query: r.Query,
@@ -344,7 +344,7 @@ func ParseAlertingRules(epRuleGroups []*customalerting.RuleGroup, custom bool, l
rule.State = aState rule.State = aState
} }
} }
rule.Alerts = append(rule.Alerts, &v1alpha1.Alert{ rule.Alerts = append(rule.Alerts, &v2alpha1.Alert{
ActiveAt: a.ActiveAt, ActiveAt: a.ActiveAt,
Labels: a.Labels, Labels: a.Labels,
Annotations: a.Annotations, Annotations: a.Annotations,

View File

@@ -1,14 +1,14 @@
package rules package rules
import ( import (
"kubesphere.io/kubesphere/pkg/simple/client/alerting"
"testing" "testing"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
promresourcesv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" promresourcesv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"github.com/prometheus/prometheus/rules" "github.com/prometheus/prometheus/rules"
"k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/intstr"
"kubesphere.io/kubesphere/pkg/api/customalerting/v1alpha1" "kubesphere.io/kubesphere/pkg/api/alerting/v2alpha1"
"kubesphere.io/kubesphere/pkg/simple/client/customalerting"
) )
func TestGetAlertingRulesStatus(t *testing.T) { func TestGetAlertingRulesStatus(t *testing.T) {
@@ -16,14 +16,14 @@ func TestGetAlertingRulesStatus(t *testing.T) {
description string description string
ruleNamespace string ruleNamespace string
resourceRuleChunk *ResourceRuleChunk resourceRuleChunk *ResourceRuleChunk
ruleGroups []*customalerting.RuleGroup ruleGroups []*alerting.RuleGroup
extLabels func() map[string]string extLabels func() map[string]string
expected []*v1alpha1.GettableAlertingRule expected []*v2alpha1.GettableAlertingRule
}{{ }{{
description: "get alerting rules status", description: "get alerting rules status",
ruleNamespace: "test", ruleNamespace: "test",
resourceRuleChunk: &ResourceRuleChunk{ resourceRuleChunk: &ResourceRuleChunk{
Level: v1alpha1.RuleLevelNamespace, Level: v2alpha1.RuleLevelNamespace,
Custom: true, Custom: true,
ResourceRulesMap: map[string]*ResourceRuleCollection{ ResourceRulesMap: map[string]*ResourceRuleCollection{
"custom-alerting-rule-jqbgn": &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", Name: "alerting.custom.defaults",
File: "/etc/thanos/rules/thanos-ruler-thanos-ruler-rulefiles-0/test-custom-alerting-rule-jqbgn.yaml", File: "/etc/thanos/rules/thanos-ruler-thanos-ruler-rulefiles-0/test-custom-alerting-rule-jqbgn.yaml",
Rules: []*customalerting.AlertingRule{{ Rules: []*alerting.AlertingRule{{
Name: "TestCPUUsageHigh", Name: "TestCPUUsageHigh",
Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`, Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`,
Duration: 60, Duration: 60,
@@ -62,8 +62,8 @@ func TestGetAlertingRulesStatus(t *testing.T) {
}, },
}}, }},
}}, }},
expected: []*v1alpha1.GettableAlertingRule{{ expected: []*v2alpha1.GettableAlertingRule{{
AlertingRule: v1alpha1.AlertingRule{ AlertingRule: v2alpha1.AlertingRule{
Id: "ca7f09e76954e67c", Id: "ca7f09e76954e67c",
Name: "TestCPUUsageHigh", Name: "TestCPUUsageHigh",
Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`, Query: `namespace:workload_cpu_usage:sum{namespace="test"} > 1`,

View File

@@ -16,8 +16,21 @@ limitations under the License.
package alerting package alerting
import (
"fmt"
"strings"
"github.com/spf13/pflag"
"kubesphere.io/kubesphere/pkg/utils/reflectutils"
)
type Options struct { type Options struct {
Endpoint string `json:"endpoint" yaml:"endpoint"` 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 { func NewAlertingOptions() *Options {
@@ -26,13 +39,37 @@ func NewAlertingOptions() *Options {
} }
} }
func (s *Options) ApplyTo(options *Options) { func (o *Options) ApplyTo(options *Options) {
if options == nil { reflectutils.Override(options, o)
options = s }
return
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
}
}
}
} }
if s.Endpoint != "" { return errs
options.Endpoint = s.Endpoint }
}
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)")
} }

View File

@@ -1,4 +1,4 @@
package customalerting package alerting
import ( import (
"context" "context"

View File

@@ -1,4 +1,4 @@
package customalerting package alerting
import ( import (
"context" "context"

View File

@@ -1,4 +1,4 @@
package customalerting package alerting
import ( import (
"time" "time"

View File

@@ -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")
}

View File

@@ -37,8 +37,8 @@ import (
"kubesphere.io/kubesphere/pkg/apiserver/runtime" "kubesphere.io/kubesphere/pkg/apiserver/runtime"
"kubesphere.io/kubesphere/pkg/constants" "kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/informers" "kubesphere.io/kubesphere/pkg/informers"
alertingv2alpha1 "kubesphere.io/kubesphere/pkg/kapis/alerting/v2alpha1"
clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1" clusterkapisv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/cluster/v1alpha1"
customalertingv1alpha1 "kubesphere.io/kubesphere/pkg/kapis/customalerting/v1alpha1"
devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2" devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2"
devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3" devopsv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha3"
iamv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2" 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(terminalv1alpha2.AddToContainer(container, clientsets.Kubernetes(), nil))
urlruntime.Must(metricsv1alpha2.AddToContainer(container)) urlruntime.Must(metricsv1alpha2.AddToContainer(container))
urlruntime.Must(networkv1alpha2.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{ config := restfulspec.Config{
WebServices: container.RegisteredWebServices(), WebServices: container.RegisteredWebServices(),