Skip to content

Commit

Permalink
Fix error on startup if ns already exists - now existing ns is used
Browse files Browse the repository at this point in the history
  • Loading branch information
Mtze committed Sep 23, 2023
1 parent 0a5f66e commit 3c6622e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
31 changes: 29 additions & 2 deletions HadesScheduler/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
log "github.com/sirupsen/logrus"

"github.com/Mtze/HadesCI/shared/payload"
"github.com/Mtze/HadesCI/shared/utils"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -29,13 +30,26 @@ var clientset *kubernetes.Clientset
var namespace *corev1.Namespace

func init() {

var k8sCfg utils.K8sConfig
utils.LoadConfig(&k8sCfg)

var err error

hadesCInamespace := k8sCfg.HadesCInamespace
log.Debugf("Using namespace '%s'", hadesCInamespace)

clientset = initializeKubeconfig()
namespace, err = createNamespace(clientset, "hadestesting")
namespace, err = createNamespace(clientset, hadesCInamespace)

if err != nil {
log.Warn("Failed to create hades namespace - Using the existing one")
log.Warn("Failed to create hades namespace)")
log.Info("Trying to get existing namespace")
namespace, err = getNamespace(clientset, hadesCInamespace)
if err != nil {
log.WithError(err).Error("error getting existing namespace - no more options to try - exiting")
os.Exit(1)
}
}
}

Expand Down Expand Up @@ -149,6 +163,19 @@ func getNamespaces(clientset *kubernetes.Clientset) *corev1.NamespaceList {
return namespaces
}

func getNamespace(clientset *kubernetes.Clientset, namespace string) (*corev1.Namespace, error) {
log.Infof("Getting namespace %s", namespace)

ns, err := clientset.CoreV1().Namespaces().Get(context.Background(), namespace, v1.GetOptions{})

if err != nil {
log.WithError(err).Error("error getting namespace")
return nil, err
}

return ns, nil
}

func deleteNamespace(clientset *kubernetes.Clientset, namespace string) {
log.Infof("Deleting namespace %s\n", namespace)

Expand Down
4 changes: 4 additions & 0 deletions shared/utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ type RabbitMQConfig struct {
Password string `env:"RABBITMQ_DEFAULT_PASS,notEmpty"`
}

type K8sConfig struct {
HadesCInamespace string `env:"HADES_CI_NAMESPACE" envDefault:"hades-ci"`
}

func LoadConfig(cfg interface{}) {

if is_debug := os.Getenv("DEBUG"); is_debug == "true" {
Expand Down

0 comments on commit 3c6622e

Please sign in to comment.