Skip to content

Commit

Permalink
[feat] - add promagent analyzer
Browse files Browse the repository at this point in the history
Signed-off-by: Hélia Barroso <[email protected]>
  • Loading branch information
heliapb committed Dec 10, 2024
1 parent 2c9c746 commit b8ac6ce
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 67 deletions.
11 changes: 7 additions & 4 deletions cmd/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ import (
type AnalyzeKind string

const (
ServiceMonitor AnalyzeKind = "servicemonitor"
Operator AnalyzeKind = "operator"
Prometheus AnalyzeKind = "prometheus"
Alertmanager AnalyzeKind = "alertmanager"
ServiceMonitor AnalyzeKind = "servicemonitor"
Operator AnalyzeKind = "operator"
Prometheus AnalyzeKind = "prometheus"
Alertmanager AnalyzeKind = "alertmanager"
PrometheusAgent AnalyzeKind = "prometheusagent"
)

type AnalyzeFlags struct {
Expand Down Expand Up @@ -82,6 +83,8 @@ func run(cmd *cobra.Command, _ []string) error {
return analyzers.RunOperatorAnalyzer(cmd.Context(), clientSets, analyzerFlags.Name, analyzerFlags.Namespace)
case Prometheus:
return analyzers.RunPrometheusAnalyzer(cmd.Context(), clientSets, analyzerFlags.Name, analyzerFlags.Namespace)
case PrometheusAgent:
return analyzers.RunPrometheusAgentAnalyzer(cmd.Context(), clientSets, analyzerFlags.Name, analyzerFlags.Namespace)
case Alertmanager:
return analyzers.RunAlertmanagerAnalyzer(cmd.Context(), clientSets, analyzerFlags.Name, analyzerFlags.Namespace)
default:
Expand Down
64 changes: 1 addition & 63 deletions internal/analyzers/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ import (
"context"
"fmt"
"log/slog"
"strings"

"github.com/prometheus-operator/poctl/internal/k8sutil"
v1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
Expand Down Expand Up @@ -61,7 +59,7 @@ func RunPrometheusAnalyzer(ctx context.Context, clientSets *k8sutil.ClientSets,
return fmt.Errorf("failed to get ClusterRole %s", crb.RoleRef.Name)
}

err = checkClusterRoleRules(crb, cr)
err = k8sutil.CheckPrometheusClusterRoleRules(crb, cr)
if err != nil {
return err
}
Expand Down Expand Up @@ -111,66 +109,6 @@ func RunPrometheusAnalyzer(ctx context.Context, clientSets *k8sutil.ClientSets,
return nil
}

func checkClusterRoleRules(crb v1.ClusterRoleBinding, cr *v1.ClusterRole) error {
var errs []string
verbsToCheck := []string{"get", "list", "watch"}
missingVerbs := []string{}

for _, rule := range cr.Rules {
for _, resource := range rule.Resources {
found := false
if resource == "configmaps" {
for _, verb := range rule.Verbs {
if verb == "get" {
found = true
break
}
}
if !found {
errs = append(errs, fmt.Sprintf("ClusterRole %s does not include 'configmaps' with 'get' in its verbs", crb.RoleRef.Name))
}
continue
}
for range rule.APIGroups {
for _, requiredVerb := range verbsToCheck {
found := false
for _, verb := range rule.Verbs {
if verb == requiredVerb {
found = true
break
}
}
if !found {
missingVerbs = append(missingVerbs, requiredVerb)
}
}
if len(missingVerbs) > 0 {
errs = append(errs, fmt.Sprintf("ClusterRole %s is missing necessary verbs for APIGroups: %v", crb.RoleRef.Name, missingVerbs))
}
}
}
for _, nonResource := range rule.NonResourceURLs {
if nonResource == "/metrics" {
hasGet := false
for _, verb := range rule.Verbs {
if verb == "get" {
hasGet = true
break
}
}
if !hasGet {
errs = append(errs, fmt.Sprintf("ClusterRole %s does not include 'get' verb for NonResourceURL '/metrics'", crb.RoleRef.Name))
}
}
}
}

if len(errs) > 0 {
return fmt.Errorf("multiple errors found:\n%s", strings.Join(errs, "\n"))
}
return nil
}

func checkResourceLabelSelectors(ctx context.Context, clientSets *k8sutil.ClientSets, labelSelector *metav1.LabelSelector, resourceName, namespace string) error {
if labelSelector == nil {
return fmt.Errorf("%s selector is not defined", resourceName)
Expand Down
61 changes: 61 additions & 0 deletions internal/analyzers/prometheusagent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright 2024 The prometheus-operator 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 analyzers

import (
"context"
"fmt"
"log/slog"

"github.com/prometheus-operator/poctl/internal/k8sutil"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func RunPrometheusAgentAnalyzer(ctx context.Context, clientSets *k8sutil.ClientSets, name, namespace string) error {
prometheusagent, err := clientSets.MClient.MonitoringV1alpha1().PrometheusAgents(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return fmt.Errorf("prometheus %s not found in namespace %s", name, namespace)
}
return fmt.Errorf("error while getting Prometheus: %v", err)
}

cRb, err := clientSets.KClient.RbacV1().ClusterRoleBindings().List(ctx, metav1.ListOptions{
LabelSelector: "name=prometheus-agent",
})
if err != nil {
return fmt.Errorf("failed to list RoleBindings: %w", err)
}

if !k8sutil.IsServiceAccountBoundToRoleBindingList(cRb, prometheusagent.Spec.ServiceAccountName) {
return fmt.Errorf("serviceAccount %s is not bound to any RoleBindings", prometheusagent.Spec.ServiceAccountName)
}

for _, crb := range cRb.Items {
cr, err := clientSets.KClient.RbacV1().ClusterRoles().Get(ctx, crb.RoleRef.Name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get ClusterRole %s", crb.RoleRef.Name)
}

err = k8sutil.CheckPrometheusClusterRoleRules(crb, cr)
if err != nil {
return err
}
}

slog.Info("Prometheus Agent is compliant, no issues found", "name", name, "namespace", namespace)
return nil
}
60 changes: 60 additions & 0 deletions internal/k8sutil/k8sutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"os"
"os/user"
"path/filepath"
"strings"

monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1"
Expand Down Expand Up @@ -184,6 +185,65 @@ func CheckResourceNamespaceSelectors(ctx context.Context, clientSets ClientSets,
if len(namespaces.Items) == 0 {
return fmt.Errorf("no namespaces match the selector %s", labelSelector)
}
return nil
}

func CheckPrometheusClusterRoleRules(crb v1.ClusterRoleBinding, cr *v1.ClusterRole) error {
var errs []string
verbsToCheck := []string{"get", "list", "watch"}
missingVerbs := []string{}

for _, rule := range cr.Rules {
for _, resource := range rule.Resources {
found := false
if resource == "configmaps" {
for _, verb := range rule.Verbs {
if verb == "get" {
found = true
break
}
}
if !found {
errs = append(errs, fmt.Sprintf("ClusterRole %s does not include 'configmaps' with 'get' in its verbs", crb.RoleRef.Name))
}
continue
}
for range rule.APIGroups {
for _, requiredVerb := range verbsToCheck {
found := false
for _, verb := range rule.Verbs {
if verb == requiredVerb {
found = true
break
}
}
if !found {
missingVerbs = append(missingVerbs, requiredVerb)
}
}
if len(missingVerbs) > 0 {
errs = append(errs, fmt.Sprintf("ClusterRole %s is missing necessary verbs for APIGroups: %v", crb.RoleRef.Name, missingVerbs))
}
}
}
for _, nonResource := range rule.NonResourceURLs {
if nonResource == "/metrics" {
hasGet := false
for _, verb := range rule.Verbs {
if verb == "get" {
hasGet = true
break
}
}
if !hasGet {
errs = append(errs, fmt.Sprintf("ClusterRole %s does not include 'get' verb for NonResourceURL '/metrics'", crb.RoleRef.Name))
}
}
}
}

if len(errs) > 0 {
return fmt.Errorf("multiple errors found:\n%s", strings.Join(errs, "\n"))
}
return nil
}

0 comments on commit b8ac6ce

Please sign in to comment.