Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CHORE] installing crds #11

Merged
merged 2 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ var createCmd = &cobra.Command{
// Run: func(cmd *cobra.Command, args []string) { },
}

const LatestVersion = "0.74.0"

func init() {
rootCmd.AddCommand(createCmd)
createCmd.PersistentFlags().String("version", LatestVersion, "Prometheus Operator version")

// Here you will define your flags and configuration settings.

Expand Down
171 changes: 133 additions & 38 deletions cmd/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,54 +20,41 @@ import (
"log/slog"
"os"

"github.com/google/go-github/v62/github"
"github.com/prometheus-operator/poctl/internal/builder"
"github.com/prometheus-operator/poctl/internal/k8sutil"
"github.com/prometheus-operator/poctl/internal/log"
monitoringclient "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned"
"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"
"k8s.io/client-go/kubernetes"
)

// stackCmd represents the stack command.
var stackCmd = &cobra.Command{
Use: "stack",
Short: "create a stack of Prometheus Operator resources.",
Long: `create a stack of Prometheus Operator resources.`,
Run: func(cmd *cobra.Command, _ []string) {
logger, err := log.NewLogger()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

//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")
os.Exit(1)
}

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

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

if err := createPrometheusOperator(cmd.Context(), logger, kclient, mclient, metav1.NamespaceDefault, "0.73.2"); err != nil {
logger.With("error", err.Error()).Error("error while creating Prometheus Operator")
os.Exit(1)
}
var (
stackCmd = &cobra.Command{
Use: "stack",
Short: "create a stack of Prometheus Operator resources.",
Long: `create a stack of Prometheus Operator resources.`,
Run: run,
}

logger.Info("Prometheus Operator stack created successfully.")
},
}
crds = []string{
"alertmanagers",
"alertmanagerconfigs",
"podmonitors",
"probes",
"prometheusagents",
"prometheuses",
"prometheusrules",
"scrapeconfigs",
"servicemonitors",
"thanosrulers",
}
)

func init() {
createCmd.AddCommand(stackCmd)
Expand All @@ -83,6 +70,114 @@ func init() {
// stackCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func run(cmd *cobra.Command, _ []string) {
logger, err := log.NewLogger()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

version, err := cmd.Flags().GetString("version")
if err != nil {
logger.With("error", err.Error()).Error("error while getting version flag")
os.Exit(1)
}

logger.Info(version)

//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")
os.Exit(1)
}

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

kdynamicClient, err := dynamic.NewForConfig(restConfig)
if err != nil {
logger.With("error", err.Error()).Error("error while creating dynamic client")
os.Exit(1)
}

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

gitHubClient := github.NewClient(nil)

if err := installCRDs(cmd.Context(), logger, version, kdynamicClient, gitHubClient); err != nil {
logger.With("error", err.Error()).Error("error while installing CRDs")
os.Exit(1)
}

if err := createPrometheusOperator(cmd.Context(), logger, kclient, mclient, metav1.NamespaceDefault, version); err != nil {
logger.With("error", err.Error()).Error("error while creating Prometheus Operator")
os.Exit(1)
}

logger.Info("Prometheus Operator stack created successfully.")
}

func installCRDs(
ctx context.Context,
logger *slog.Logger,
version string,
k8sClient *dynamic.DynamicClient,
gitHubClient *github.Client) error {

nodeResource := schema.GroupVersionResource{Group: "apiextensions.k8s.io", Version: "v1", Resource: "customresourcedefinitions"}

for _, crd := range crds {
l := logger.With("crd", crd)

reader, _, err := gitHubClient.Repositories.DownloadContents(
ctx,
"prometheus-operator",
"prometheus-operator",
fmt.Sprintf("example/prometheus-operator-crd/monitoring.coreos.com_%s.yaml", crd),
&github.RepositoryContentGetOptions{
Ref: fmt.Sprintf("v%s", version),
})

if err != nil {
l.Error("error while downloading crds", "error", err)
return err
}

crds, err := k8sutil.CrdDeserilezer(logger, reader)
if err != nil {
l.Error("error while deserializing crds", "error", err)
return err
}

unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(crds)
if err != nil {
l.Error("error while converting CRDs to Unstructured", "error", err)
return err
}

_, err = k8sClient.Resource(nodeResource).Apply(ctx, fmt.Sprintf("%s.monitoring.coreos.com", crd), &unstructured.Unstructured{Object: unstructuredObj}, metav1.ApplyOptions{
FieldManager: "application/apply-patch",
})

if err != nil {
l.Error("error while applying", "error", err)
return err
}

logger.Info("applied successfully", "CRD", crd)
}

return nil
}

func createPrometheusOperator(
ctx context.Context,
logger *slog.Logger,
Expand Down
8 changes: 6 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ module github.com/prometheus-operator/poctl

go 1.22.0

require k8s.io/client-go v0.30.1
require (
k8s.io/apiextensions-apiserver v0.30.1
k8s.io/client-go v0.30.1
)

require (
k8s.io/apiextensions-apiserver v0.30.1 // indirect
github.com/google/go-querystring v1.1.0 // indirect
sigs.k8s.io/controller-runtime v0.18.2 // indirect
)

Expand Down Expand Up @@ -52,6 +55,7 @@ require (
)

require (
github.com/google/go-github/v62 v62.0.0
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/prometheus-operator/prometheus-operator/pkg/client v0.74.0
)
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-github/v62 v62.0.0 h1:/6mGCaRywZz9MuHyw9gD1CwsbmBX8GWsbFkwMmHdhl4=
github.com/google/go-github/v62 v62.0.0/go.mod h1:EMxeUqGJq2xRu9DYBMwel/mr7kZrzUOfQmmpYrZn2a4=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
Expand Down
36 changes: 36 additions & 0 deletions internal/k8sutil/k8sutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,21 @@
package k8sutil

import (
"bytes"
"fmt"
"io"
"log/slog"
"os"
"os/user"
"path/filepath"

monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1"
apiv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
Expand Down Expand Up @@ -59,3 +68,30 @@ func GetRestConfig(logger *slog.Logger, kubeConfig string) (*rest.Config, error)

return config, nil
}

func CrdDeserilezer(logger *slog.Logger, reader io.ReadCloser) (runtime.Object, error) {
sch := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(sch)
_ = apiextv1beta1.AddToScheme(sch)
_ = apiv1.AddToScheme(sch)

_ = monitoringv1.AddToScheme(sch)
_ = monitoringv1alpha1.AddToScheme(sch)

buf := new(bytes.Buffer)
_, err := buf.ReadFrom(reader)
if err != nil {
logger.Error("error while reading CRD", "error", err)
return &runtime.Unknown{}, err
}

decode := serializer.NewCodecFactory(sch).UniversalDeserializer().Decode

obj, _, err := decode(buf.Bytes(), nil, nil)
if err != nil {
logger.Error("error while decoding CRD", "error", err)
return &runtime.Unknown{}, err
}

return obj, nil
}