go 获取k8s servicemonitor
package test
import (
"context"
"fmt"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"os"
"testing"
)
func TestAddEndpoints(t *testing.T) {
_ = monitoringv1.AddToScheme(scheme.Scheme)
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig == "" {
kubeconfig = "E:/kubeconfig"
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
config.GroupVersion = &monitoringv1.SchemeGroupVersion
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs
restClient, err := rest.RESTClientFor(config)
if err != nil {
fmt.Println(err)
}
svcMonitorClient := restClient.
Get().
Resource("servicemonitors").
Namespace("cloudos-dbaas-nosql").
Name("redis-monitor-servicemonitor")
svcMonitor := &monitoringv1.ServiceMonitor{}
err = svcMonitorClient.Do(context.Background()).Into(svcMonitor)
if err != nil {
panic(err.Error())
}
fmt.Println(svcMonitor)
}
go 向servicemonitor中添加endpoints
package test
import (
"context"
"fmt"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"os"
"testing"
)
func TestAddEndpoints(t *testing.T) {
_ = monitoringv1.AddToScheme(scheme.Scheme)
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig == "" {
kubeconfig = "E:/kubeconfig"
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
config.GroupVersion = &monitoringv1.SchemeGroupVersion
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs
restClient, err := rest.RESTClientFor(config)
if err != nil {
fmt.Println(err)
}
svcMonitorClient := restClient.
Get().
Resource("servicemonitors").
Namespace("cloudos-dbaas-nosql").
Name("redis-monitor-servicemonitor")
svcMonitor := &monitoringv1.ServiceMonitor{}
err = svcMonitorClient.Do(context.Background()).Into(svcMonitor)
if err != nil {
panic(err.Error())
}
newEndpoint := monitoringv1.Endpoint{
Port: "http",
Path: "/metrics",
Interval: "30s",
Scheme: "HTTP",
}
svcMonitor.Spec.Endpoints = append(svcMonitor.Spec.Endpoints, newEndpoint)
err = restClient.
Put().
Resource("servicemonitors").
Namespace(svcMonitor.Namespace).
Name(svcMonitor.Name).
Body(svcMonitor).
Do(context.Background()).Into(svcMonitor)
if err != nil {
panic(err.Error())
}
fmt.Printf("Updated ServiceMonitor %s with new endpoints\n", err)
}