Skip to content

[SREP-609] POC adding a Golang scripts #217

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,15 @@ RUN OUT_DIR=/out make hypershift
# Make binaries executable
RUN chmod -R +x /out

# build the golang scripts
COPY goapp /goapp
COPY scripts /scripts
WORKDIR /goapp
RUN go build -o /out/goapp main.go
RUN chmod -R +x /out



FROM registry.access.redhat.com/ubi8/ubi:8.9
RUN yum -y install --disableplugin=subscription-manager \
python3.11 python3.11-pip jq openssh-clients sshpass \
Expand All @@ -133,6 +142,7 @@ COPY --from=build-stage0 /aws/bin/ /usr/local/bin
COPY --from=build-stage0 /usr/local/aws-cli /usr/local/aws-cli
COPY --from=build-stage0 /out/hypershift /usr/local/bin
COPY --from=build-stage0 /out/ocm /usr/local/bin
COPY --from=build-stage0 /out/goapp /usr/local/bin
COPY scripts /managed-scripts

# Install python packages
Expand Down
22 changes: 22 additions & 0 deletions goapp/cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Assisted by GenAI

package cmd

import (
"github.com/openshift/managed-scripts/goapp/internal/cli"
)

var moduleRegistry map[string]cli.CommandModule

// Allow runtime injection of module registry
func SetModuleRegistry(m map[string]cli.CommandModule) {
moduleRegistry = m
}

// Add all registered modules to RootCmd using cli.WrapModule
func AddModuleCommands() {
for _, module := range moduleRegistry {
cmd := cli.WrapModule(module) // This builds the Cobra command with flag/env/param loading
RootCmd.AddCommand(cmd)
}
}
19 changes: 19 additions & 0 deletions goapp/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cmd

import (
"os"

"github.com/spf13/cobra"
)

var RootCmd = &cobra.Command{
Use: "goapp",
Short: "entry point for running golang managed-scripts",
}

func Execute() {
if err := RootCmd.Execute(); err != nil {
os.Exit(1)
}
}

62 changes: 62 additions & 0 deletions goapp/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
module github.com/openshift/managed-scripts/goapp

go 1.24.1

require (
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.20.1
k8s.io/api v0.33.1
k8s.io/apimachinery v0.33.1
k8s.io/client-go v0.33.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/gnostic-models v0.6.9 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.12.0 // indirect
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/net v0.38.0 // indirect
golang.org/x/oauth2 v0.27.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/term v0.30.0 // indirect
golang.org/x/text v0.23.0 // indirect
golang.org/x/time v0.9.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)
183 changes: 183 additions & 0 deletions goapp/go.sum

Large diffs are not rendered by default.

107 changes: 107 additions & 0 deletions goapp/internal/cli/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Assisted by GenAI

package cli

import (
"fmt"
"reflect"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

type Params interface{}

type CommandModule interface {
Name() string // return the name of the subcommand (script).
Summary() string // return a short summary of what this subcommand does.
Params() Params // return a pointer to a struct of needed parameters.
Execute() error // main logic goes here.
}

func WrapModule(module CommandModule) *cobra.Command {
params := module.Params()

cmd := &cobra.Command{
Use: module.Name(),
Short: module.Summary(),
PreRunE: func(cmd *cobra.Command, args []string) error {
return LoadParamsFromViper(params)
},
RunE: func(cmd *cobra.Command, args []string) error {
return module.Execute()
},
}

BindFlagsWithViper(cmd, params)
return cmd
}

func BindFlagsWithViper(cmd *cobra.Command, params Params) {
if params == nil {
return // nothing to bind
}

v := reflect.ValueOf(params).Elem()
t := v.Type()

viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))

for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
flag := field.Tag.Get("flag")
env := field.Tag.Get("env")
usage := field.Tag.Get("usage")
def := field.Tag.Get("default")

if flag == "" {
flag = strings.ToLower(field.Name)
}
if env == "" {
env = strings.ToUpper(flag)
}

key := flag // same key for flag/env/viper

switch field.Type.Kind() {
case reflect.String:
cmd.Flags().String(flag, def, usage)
viper.BindPFlag(key, cmd.Flags().Lookup(flag))
viper.BindEnv(key, env)
case reflect.Bool:
cmd.Flags().Bool(flag, def == "true", usage)
viper.BindPFlag(key, cmd.Flags().Lookup(flag))
viper.BindEnv(key, env)
}
}
}

func LoadParamsFromViper(params Params) error {
if params == nil {
return nil // nothing to load
}

v := reflect.ValueOf(params).Elem()
t := v.Type()

for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
key := field.Tag.Get("flag")
if key == "" {
key = strings.ToLower(field.Name)
}
val := v.Field(i)

switch field.Type.Kind() {
case reflect.String:
val.SetString(viper.GetString(key))
case reflect.Bool:
val.SetBool(viper.GetBool(key))
default:
return fmt.Errorf("unsupported param type: %s", field.Type.Kind())
}
}
return nil
}
34 changes: 34 additions & 0 deletions goapp/internal/cli/cli_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Assisted by GenAI
package cli

import (
"testing"

"github.com/spf13/cobra"
)

func TestBindFlagsWithViper_NilParams(t *testing.T) {
cmd := &cobra.Command{
Use: "test-cmd",
}

// Prevent panic when nil is passed
defer func() {
if r := recover(); r != nil {
t.Errorf("BindFlagsWithViper panicked when params was nil: %v", r)
}
}()

BindFlagsWithViper(cmd, nil)

if cmd.Flags().HasFlags() {
t.Errorf("expected no flags to be bound when params is nil")
}
}

func TestLoadParamsFromViper_NilParams(t *testing.T) {
err := LoadParamsFromViper(nil)
if err != nil {
t.Errorf("expected no error when loading nil params, got: %v", err)
}
}
20 changes: 20 additions & 0 deletions goapp/internal/registry/registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Assisted by GenAI

package registry

// Contributor TODO: import your package here
import (
"github.com/openshift/managed-scripts/goapp/internal/cli"
pods "github.com/openshift/managed-scripts/goapp/pkg/ceepod"
nodes "github.com/openshift/managed-scripts/goapp/pkg/srepnode"
"github.com/openshift/managed-scripts/goapp/pkg/utils"
)

// Contributor TODO: register your module here.
// clientFn provides a kube client, you can use it if your code needs to interact with the cluster.
func NewRegistry(clientFn utils.ClientFactoryFunc) map[string]cli.CommandModule {
return map[string]cli.CommandModule{
"getnodes": nodes.NewNodeModule(clientFn),
"getpods": pods.NewPodModule(clientFn),
}
}
20 changes: 20 additions & 0 deletions goapp/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Assisted by GenAI
package main

import (
"github.com/openshift/managed-scripts/goapp/cmd"
"github.com/openshift/managed-scripts/goapp/internal/registry"
"github.com/openshift/managed-scripts/goapp/pkg/utils"
)

func main() {
// utils.GetOrInitKubeClient is for lazy load
// it will only load the kube client when it actual gets called
// so that kubeconfig is not a hard requirement for running the root command
modules := registry.NewRegistry(utils.GetOrInitKubeClient)

cmd.SetModuleRegistry(modules)
cmd.AddModuleCommands()

cmd.Execute()
}
1 change: 1 addition & 0 deletions goapp/pkg/ceepod
1 change: 1 addition & 0 deletions goapp/pkg/srepnode
37 changes: 37 additions & 0 deletions goapp/pkg/utils/kubeclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Assisted-by Generative AI.

package utils

import (
"sync"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)

type ClientFactoryFunc func() (kubernetes.Interface, error)

var (
clientOnce sync.Once
cachedClient kubernetes.Interface
clientErr error
)

func GetOrInitKubeClient() (kubernetes.Interface, error) {
clientOnce.Do(func() {
cachedClient, clientErr = GetKubeClient(NewDefaultConfigLoader())
})
return cachedClient, clientErr
}

type ConfigLoader interface {
ClientConfig() (*rest.Config, error)
}

func GetKubeClient(loader ConfigLoader) (*kubernetes.Clientset, error) {
config, err := loader.ClientConfig()
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
13 changes: 13 additions & 0 deletions goapp/pkg/utils/kubeclient_loader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Assisted-by Generative AI.

package utils

import (
"k8s.io/client-go/tools/clientcmd"
)

func NewDefaultConfigLoader() ConfigLoader {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
overrides := &clientcmd.ConfigOverrides{}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides)
}
Loading