Skip to content

Commit

Permalink
[CHORE] adding create svc monitor command
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas Takashi <[email protected]>
  • Loading branch information
nicolastakashi committed Jul 1, 2024
1 parent d234e47 commit 40278a5
Show file tree
Hide file tree
Showing 2 changed files with 133 additions and 2 deletions.
130 changes: 130 additions & 0 deletions cmd/servicemonitor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
"context"
"errors"
"fmt"

"github.com/prometheus-operator/poctl/internal/k8sutil"
"github.com/prometheus-operator/poctl/internal/log"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1"
monitoringclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
applyConfigMetav1 "k8s.io/client-go/applyconfigurations/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/utils/ptr"
)

// servicemonitorCmd represents the servicemonitor command

Check failure on line 22 in cmd/servicemonitor.go

View workflow job for this annotation

GitHub Actions / Golang linter

Comment should end in a period (godot)
var (
serviceName string
namespace string
port string
servicemonitorCmd = &cobra.Command{
Use: "servicemonitor",
Short: "Create a service monitor object",
Long: `Create a service monitor object based on user input parameters or taking as source of truth a kubernetes service`,
RunE: runServiceMonitor,
}
)

func runServiceMonitor(cmd *cobra.Command, args []string) error {

Check failure on line 35 in cmd/servicemonitor.go

View workflow job for this annotation

GitHub Actions / Golang linter

unused-parameter: parameter 'cmd' seems to be unused, consider removing or renaming it as _ (revive)
logger, err := log.NewLogger()
if err != nil {
fmt.Println(err)
return err
}

//TODO(nicolastakashi): Replace it when the PR #6623 is merged
restConfig, err := k8sutil.GetRestConfig(logger, kubeconfig)
if err != nil {
logger.With("error", err.Error()).Error("error while getting kubeconfig")
return err
}

kclient, err := kubernetes.NewForConfig(restConfig)
if err != nil {
logger.With("error", err.Error()).Error("error while creating k8s client")
return err
}

mclient, err := monitoringclient.NewForConfig(restConfig)
if err != nil {
logger.With("error", err.Error()).Error("error while creating Prometheus Operator client")
return err
}

if serviceName == "" {
return errors.New("service name is required")
}

err = createFromService(context.Background(), kclient, mclient, namespace, serviceName, port)
if err != nil {
logger.With("error", err.Error()).Error("error while creating service monitor")
return err
}

return nil
}

func createFromService(
ctx context.Context,
k8sClient *kubernetes.Clientset,
mClient *monitoringclient.Clientset,
namespace string,
serviceName string,
port string) error {

// Get the service
service, err := k8sClient.CoreV1().Services(namespace).Get(ctx, serviceName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("error while getting service %s: %v", serviceName, err)
}

// Create the service monitor
svcMonitor := &monitoringv1.ServiceMonitorApplyConfiguration{
TypeMetaApplyConfiguration: applyConfigMetav1.TypeMetaApplyConfiguration{
Kind: ptr.To("ServiceMonitor"),
APIVersion: ptr.To("monitoring.coreos.com/v1"),
},
ObjectMetaApplyConfiguration: &applyConfigMetav1.ObjectMetaApplyConfiguration{
Name: ptr.To(serviceName),
Namespace: ptr.To(namespace),
Labels: service.Labels,
},
Spec: &monitoringv1.ServiceMonitorSpecApplyConfiguration{
Selector: &metav1.LabelSelector{
MatchLabels: service.Spec.Selector,
},
},
}

for _, p := range service.Spec.Ports {
if port != "" && p.Name != port {
continue
}

svcMonitor.Spec.Endpoints = append(svcMonitor.Spec.Endpoints, monitoringv1.EndpointApplyConfiguration{
HonorLabels: ptr.To(true),
Port: ptr.To(p.Name),
})
}

_, err = mClient.MonitoringV1().ServiceMonitors(namespace).Apply(ctx, svcMonitor, k8sutil.ApplyOption)
if err != nil {
return fmt.Errorf("error while creating service monitor %s: %v", serviceName, err)
}

return nil
}

func init() {
createCmd.AddCommand(servicemonitorCmd)
servicemonitorCmd.Flags().StringVarP(&serviceName, "service", "s", "", "Service name to create the service monitor from")
servicemonitorCmd.Flags().StringVarP(&namespace, "namespace", "n", "default", "Namespace of the service")
servicemonitorCmd.Flags().StringVarP(&port, "port", "p", "", "Port of the service")
}
5 changes: 3 additions & 2 deletions cmd/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
Expand All @@ -39,7 +40,7 @@ var (
Use: "stack",
Short: "create a stack of Prometheus Operator resources.",
Long: `create a stack of Prometheus Operator resources.`,
Run: run,
Run: runStack,
}

crds = []string{
Expand Down Expand Up @@ -70,7 +71,7 @@ func init() {
// stackCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func run(cmd *cobra.Command, _ []string) {
func runStack(cmd *cobra.Command, _ []string) {
logger, err := log.NewLogger()
if err != nil {
fmt.Println(err)
Expand Down

0 comments on commit 40278a5

Please sign in to comment.