format Unix

This commit is contained in:
admju 2024-09-02 11:44:44 +00:00
parent 11f56722f7
commit 9cf954776f
24 changed files with 1097 additions and 1097 deletions

View File

@ -1,34 +1,34 @@
package chart package chart
import ( import (
"os" "os"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
type ChartData struct { type ChartData struct {
Name string `yaml:"name"` Name string `yaml:"name"`
Chart string `yaml:"chart"` Chart string `yaml:"chart"`
Version string `yaml:"version"` Version string `yaml:"version"`
Opts string `yaml:"helm_opts"` Opts string `yaml:"helm_opts"`
Values string `yaml:"helm_values"` Values string `yaml:"helm_values"`
FileValues string `yaml:"helm_filevalues"` FileValues string `yaml:"helm_filevalues"`
} }
type ChartRepoData struct { type ChartRepoData struct {
Name string `yaml:"name"` Name string `yaml:"name"`
Repository string `yaml:"repository"` Repository string `yaml:"repository"`
Charts []ChartData `yaml:"charts"` Charts []ChartData `yaml:"charts"`
} }
type chartsRepoData struct { type chartsRepoData struct {
Charts []ChartRepoData `yaml:"opencloud"` Charts []ChartRepoData `yaml:"opencloud"`
} }
func FromConfigFile(filename string) ([]ChartRepoData) { func FromConfigFile(filename string) ([]ChartRepoData) {
yamlFile, _ := os.ReadFile(filename) yamlFile, _ := os.ReadFile(filename)
var data chartsRepoData var data chartsRepoData
yaml.Unmarshal(yamlFile, &data) yaml.Unmarshal(yamlFile, &data)
return data.Charts return data.Charts
} }

View File

@ -1,30 +1,30 @@
package chart package chart
// https://pkg.go.dev/github.com/stretchr/testify/assert // https://pkg.go.dev/github.com/stretchr/testify/assert
import ( import (
"testing" "testing"
"path/filepath" "path/filepath"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestReadConfChart(t *testing.T){ func TestReadConfChart(t *testing.T){
src := filepath.Join(TEST_SRC_DIR, "oc.yml") src := filepath.Join(TEST_SRC_DIR, "oc.yml")
assert.FileExists(t, src, "FromConfigFile error") assert.FileExists(t, src, "FromConfigFile error")
data := FromConfigFile(src) data := FromConfigFile(src)
assert.Equal(t, data[0].Name, "bitnami", "FromConfigFile error") assert.Equal(t, data[0].Name, "bitnami", "FromConfigFile error")
assert.Equal(t, data[0].Repository, "https://charts.bitnami.com/bitnami", "FromConfigFile error") assert.Equal(t, data[0].Repository, "https://charts.bitnami.com/bitnami", "FromConfigFile error")
wordpress := data[0].Charts[0] wordpress := data[0].Charts[0]
assert.Equal(t, wordpress.Name, "wordpress", "FromConfigFile error") assert.Equal(t, wordpress.Name, "wordpress", "FromConfigFile error")
assert.Equal(t, wordpress.Chart, "bitnami/wordpress", "FromConfigFile error") assert.Equal(t, wordpress.Chart, "bitnami/wordpress", "FromConfigFile error")
assert.Equal(t, wordpress.Version, "23.1.0", "FromConfigFile error") assert.Equal(t, wordpress.Version, "23.1.0", "FromConfigFile error")
phpmyadmin := data[0].Charts[1] phpmyadmin := data[0].Charts[1]
assert.Equal(t, phpmyadmin.Name, "phpmyadmin", "FromConfigFile error") assert.Equal(t, phpmyadmin.Name, "phpmyadmin", "FromConfigFile error")
assert.Equal(t, phpmyadmin.Chart, "bitnami/phpmyadmin", "FromConfigFile error") assert.Equal(t, phpmyadmin.Chart, "bitnami/phpmyadmin", "FromConfigFile error")
assert.Equal(t, phpmyadmin.Version, "17.0.4", "FromConfigFile error") assert.Equal(t, phpmyadmin.Version, "17.0.4", "FromConfigFile error")
} }

View File

@ -1,23 +1,23 @@
package chart package chart
import ( import (
"os" "os"
"testing" "testing"
"path/filepath" "path/filepath"
) )
var TEST_DEST_DIR = "../wrk_chart" var TEST_DEST_DIR = "../wrk_chart"
var TEST_SRC_DIR = filepath.Join("../../test", "chart") var TEST_SRC_DIR = filepath.Join("../../test", "chart")
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
folderPath := TEST_DEST_DIR folderPath := TEST_DEST_DIR
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.MkdirAll(folderPath, os.ModePerm) os.MkdirAll(folderPath, os.ModePerm)
// call flag.Parse() here if TestMain uses flags // call flag.Parse() here if TestMain uses flags
exitCode := m.Run() exitCode := m.Run()
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.Exit(exitCode) os.Exit(exitCode)
} }

View File

@ -1,27 +1,27 @@
package cmd package cmd
import ( import (
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
"oc-deploy/versionOc" "oc-deploy/versionOc"
"oc-deploy/generate" "oc-deploy/generate"
) )
func GenerateCmd(project string, version string) { func GenerateCmd(project string, version string) {
log.Log().Info().Msg("Generate >> ") log.Log().Info().Msg("Generate >> ")
version, err := versionOc.Get(version) version, err := versionOc.Get(version)
if err != nil { if err != nil {
log.Log().Fatal().Msg("OpenCloud >> " + err.Error()) log.Log().Fatal().Msg("OpenCloud >> " + err.Error())
} }
log.Log().Info().Msg(" >> Version : " + version) log.Log().Info().Msg(" >> Version : " + version)
obj := generate.GenerateClass{Workspace: "workspace_" + project, Version: version} obj := generate.GenerateClass{Workspace: "workspace_" + project, Version: version}
fic, err := obj.New() fic, err := obj.New()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
log.Log().Info().Msg(" >> Value : " + fic) log.Log().Info().Msg(" >> Value : " + fic)
} }

View File

@ -1,45 +1,45 @@
package cmd package cmd
import ( import (
"fmt" "fmt"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
"oc-deploy/install" "oc-deploy/install"
) )
func InstallCmd(context string, version string) { func InstallCmd(context string, version string) {
log.Log().Info().Msg("Install >> ") log.Log().Info().Msg("Install >> ")
log.Log().Info().Msg(" << Contexte : " + context) log.Log().Info().Msg(" << Contexte : " + context)
workspace := fmt.Sprintf("workspace_%s", context) workspace := fmt.Sprintf("workspace_%s", context)
obj := install.InstallClass{Workspace: workspace, Version: version} obj := install.InstallClass{Workspace: workspace, Version: version}
file, err := obj.NewInstall() file, err := obj.NewInstall()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
log.Log().Info().Msg(fmt.Sprintf(" << Version : %s", obj.Version)) log.Log().Info().Msg(fmt.Sprintf(" << Version : %s", obj.Version))
log.Log().Info().Msg(fmt.Sprintf(" >> Config : %s", file)) log.Log().Info().Msg(fmt.Sprintf(" >> Config : %s", file))
err = obj.Tools() err = obj.Tools()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
err = obj.ChartRepo() err = obj.ChartRepo()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
err = obj.K8s(context) err = obj.K8s(context)
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
err = obj.InstallCharts() err = obj.InstallCharts()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
} }

View File

@ -1,43 +1,43 @@
package cmd package cmd
import ( import (
"fmt" "fmt"
// "strings" // "strings"
// "github.com/spf13/cobra" // "github.com/spf13/cobra"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
// "oc-deploy/versionOc" // "oc-deploy/versionOc"
"oc-deploy/install" "oc-deploy/install"
) )
func UninstallCmd(context string) { func UninstallCmd(context string) {
log.Log().Info().Msg("Unnstall >> ") log.Log().Info().Msg("Unnstall >> ")
log.Log().Info().Msg(" << Contexte : " + context) log.Log().Info().Msg(" << Contexte : " + context)
workspace := fmt.Sprintf("workspace_%s", context) workspace := fmt.Sprintf("workspace_%s", context)
obj := install.InstallClass{Workspace: workspace} obj := install.InstallClass{Workspace: workspace}
file, err := obj.NewUninstall() file, err := obj.NewUninstall()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
log.Log().Info().Msg(fmt.Sprintf(" << Version : %s", obj.Version)) log.Log().Info().Msg(fmt.Sprintf(" << Version : %s", obj.Version))
log.Log().Info().Msg(fmt.Sprintf(" >> Config : %s", file)) log.Log().Info().Msg(fmt.Sprintf(" >> Config : %s", file))
err = obj.Tools() err = obj.Tools()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
err = obj.K8s(context) err = obj.K8s(context)
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
err = obj.UninstallCharts() err = obj.UninstallCharts()
if err != nil { if err != nil {
log.Log().Fatal().Msg(" >> " + err.Error()) log.Log().Fatal().Msg(" >> " + err.Error())
} }
} }

View File

@ -1,129 +1,129 @@
package helm package helm
import ( import (
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"errors" "errors"
"path/filepath" "path/filepath"
"encoding/json" "encoding/json"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
type HelmChart struct { type HelmChart struct {
Bin string Bin string
Name string Name string
Chart string Chart string
Version string Version string
Workspace string Workspace string
Opts string Opts string
Values string Values string
FileValues string FileValues string
} }
type installInfoOutput struct { type installInfoOutput struct {
Description string `json:"description"` Description string `json:"description"`
Notes string `json:"notes"` Notes string `json:"notes"`
Status string `json:"status"` Status string `json:"status"`
} }
type installOutput struct { type installOutput struct {
Info installInfoOutput `json:"info"` Info installInfoOutput `json:"info"`
} }
func (this HelmChart) Install() (string, error) { func (this HelmChart) Install() (string, error) {
bin := this.Bin bin := this.Bin
existe, err := this.exists() existe, err := this.exists()
if err != nil { if err != nil {
return "", err return "", err
} }
if existe { if existe {
return "Existe déjà", nil return "Existe déjà", nil
} }
msg := fmt.Sprintf("%s install %s %s %s --output json", bin, this.Name, this.Chart, this.Opts) msg := fmt.Sprintf("%s install %s %s %s --output json", bin, this.Name, this.Chart, this.Opts)
if this.Version != "" { if this.Version != "" {
msg = fmt.Sprintf("%s --version %s", msg, this.Version) msg = fmt.Sprintf("%s --version %s", msg, this.Version)
} }
if this.FileValues != "" { if this.FileValues != "" {
fic := filepath.Join(this.Workspace, this.FileValues) fic := filepath.Join(this.Workspace, this.FileValues)
if _, err := os.Stat(fic); err != nil { if _, err := os.Stat(fic); err != nil {
log.Log().Warn().Msg(fic) log.Log().Warn().Msg(fic)
} else { } else {
msg = fmt.Sprintf("%s --values %s", msg, fic) msg = fmt.Sprintf("%s --values %s", msg, fic)
} }
} }
msg = strings.Replace(msg, " ", " ", -1) msg = strings.Replace(msg, " ", " ", -1)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd_args := strings.Split(msg, " ") cmd_args := strings.Split(msg, " ")
cmd := exec.Command(cmd_args[0], cmd_args[1:]...) cmd := exec.Command(cmd_args[0], cmd_args[1:]...)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
return "", errors.New(res) return "", errors.New(res)
} }
var objmap installOutput var objmap installOutput
json.Unmarshal(stdout, &objmap) json.Unmarshal(stdout, &objmap)
res := objmap.Info.Status res := objmap.Info.Status
return res, nil return res, nil
} }
func (this HelmChart) Uninstall() (string, error) { func (this HelmChart) Uninstall() (string, error) {
bin := this.Bin bin := this.Bin
log.Log().Info().Msg(" >> Chart : " + this.Name) log.Log().Info().Msg(" >> Chart : " + this.Name)
existe, err := this.exists() existe, err := this.exists()
if err != nil { if err != nil {
return "", err return "", err
} }
if ! existe { if ! existe {
return "Non présent", nil return "Non présent", nil
} }
msg := fmt.Sprintf("%s uninstall %s", bin, this.Name) msg := fmt.Sprintf("%s uninstall %s", bin, this.Name)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd := exec.Command(bin, "uninstall", this.Name) cmd := exec.Command(bin, "uninstall", this.Name)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
return string(stdout), err return string(stdout), err
} }
// ../bin/helm list --filter phpmyadminm --short // ../bin/helm list --filter phpmyadminm --short
func (this HelmChart) exists() (bool, error) { func (this HelmChart) exists() (bool, error) {
bin := this.Bin bin := this.Bin
msg := fmt.Sprintf("%s list --filter %s --no-headers", bin, this.Name) msg := fmt.Sprintf("%s list --filter %s --no-headers", bin, this.Name)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd_args := strings.Split(msg, " ") cmd_args := strings.Split(msg, " ")
cmd := exec.Command(cmd_args[0], cmd_args[1:]...) cmd := exec.Command(cmd_args[0], cmd_args[1:]...)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return false, errors.New(string(stdout)) return false, errors.New(string(stdout))
} }
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
log.Log().Debug().Msg(string(stdout)) log.Log().Debug().Msg(string(stdout))
return res != "", nil return res != "", nil
} }

View File

@ -1,24 +1,24 @@
package helm package helm
import ( import (
"os" "os"
"testing" "testing"
"path/filepath" "path/filepath"
) )
var TEST_DEST_DIR = "../wrk_helm" var TEST_DEST_DIR = "../wrk_helm"
var TEST_SRC_DIR = filepath.Join("../../test", "helm") var TEST_SRC_DIR = filepath.Join("../../test", "helm")
var TEST_BIN_DIR = filepath.Join("../../test", "bin") var TEST_BIN_DIR = filepath.Join("../../test", "bin")
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
folderPath := TEST_DEST_DIR folderPath := TEST_DEST_DIR
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.MkdirAll(folderPath, os.ModePerm) os.MkdirAll(folderPath, os.ModePerm)
// call flag.Parse() here if TestMain uses flags // call flag.Parse() here if TestMain uses flags
exitCode := m.Run() exitCode := m.Run()
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.Exit(exitCode) os.Exit(exitCode)
} }

View File

@ -1,53 +1,53 @@
package helm package helm
import ( import (
"fmt" "fmt"
"strings" "strings"
"os/exec" "os/exec"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
type HelmRepo struct { type HelmRepo struct {
Bin string // Chemin vers le binaire Bin string // Chemin vers le binaire
Name string Name string
Repository string // Url du dépôt Repository string // Url du dépôt
ForceUpdate bool ForceUpdate bool
Opts string Opts string
} }
func (this HelmRepo) AddRepository() (string, error) { func (this HelmRepo) AddRepository() (string, error) {
helm_bin := this.Bin helm_bin := this.Bin
force_update := "--force-update=false" force_update := "--force-update=false"
if this.ForceUpdate { if this.ForceUpdate {
force_update = "--force-update=true" force_update = "--force-update=true"
} }
msg := fmt.Sprintf("%s repo add %s %s %s %s", helm_bin, this.Name, this.Repository, force_update, this.Opts) msg := fmt.Sprintf("%s repo add %s %s %s %s", helm_bin, this.Name, this.Repository, force_update, this.Opts)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd := exec.Command(helm_bin, "repo", "add", this.Name, this.Repository, force_update) cmd := exec.Command(helm_bin, "repo", "add", this.Name, this.Repository, force_update)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
return res, err return res, err
} }
// helm repo remove [NAME] // helm repo remove [NAME]
func (this HelmRepo) RemoveRepository() (string, error) { func (this HelmRepo) RemoveRepository() (string, error) {
helm_bin := this.Bin helm_bin := this.Bin
msg := fmt.Sprintf("%s repo remove %s", helm_bin, this.Name) msg := fmt.Sprintf("%s repo remove %s", helm_bin, this.Name)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd := exec.Command(helm_bin, "repo", "remove", this.Name) cmd := exec.Command(helm_bin, "repo", "remove", this.Name)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
return res, err return res, err
} }

View File

@ -1,23 +1,23 @@
package helm package helm
import ( import (
// "os" // "os"
// "path/filepath" // "path/filepath"
"testing" "testing"
// "github.com/stretchr/testify/assert" // "github.com/stretchr/testify/assert"
) )
func TestHelmRepoAdd(t *testing.T){ func TestHelmRepoAdd(t *testing.T){
// fmt.Println(" TestVersion ", TEST_BIN_DIR) // fmt.Println(" TestVersion ", TEST_BIN_DIR)
// bin := filepath.Join(TEST_BIN_DIR, "helm") // bin := filepath.Join(TEST_BIN_DIR, "helm")
// os.Chmod(bin, 0700) // os.Chmod(bin, 0700)
// assert.FileExists(t, bin, "TestHelmVersion error") // assert.FileExists(t, bin, "TestHelmVersion error")
// version, err := Version(bin) // version, err := Version(bin)
// assert.Nilf(t, err, "error message %s", bin) // assert.Nilf(t, err, "error message %s", bin)
// assert.Equal(t, version, "v3.15.4+gfa9efb0", "TestHelmVersion error") // assert.Equal(t, version, "v3.15.4+gfa9efb0", "TestHelmVersion error")
} }

View File

@ -1,20 +1,20 @@
package helm package helm
import ( import (
"strings" "strings"
"os/exec" "os/exec"
) )
func Version(path string) (string, error) { func Version(path string) (string, error) {
cmd := exec.Command(path, "version", "--short") cmd := exec.Command(path, "version", "--short")
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return "", err return "", err
} }
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
return res, nil return res, nil
} }

View File

@ -1,22 +1,22 @@
package helm package helm
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestHelmVersion(t *testing.T){ func TestHelmVersion(t *testing.T){
bin := filepath.Join(TEST_BIN_DIR, "helm") bin := filepath.Join(TEST_BIN_DIR, "helm")
os.Chmod(bin, 0700) os.Chmod(bin, 0700)
assert.FileExists(t, bin, "TestHelmVersion error") assert.FileExists(t, bin, "TestHelmVersion error")
version, err := Version(bin) version, err := Version(bin)
assert.Nilf(t, err, "error message %s", bin) assert.Nilf(t, err, "error message %s", bin)
assert.Equal(t, version, "v3.15.4+gfa9efb0", "TestHelmVersion error") assert.Equal(t, version, "v3.15.4+gfa9efb0", "TestHelmVersion error")
} }

View File

@ -1,90 +1,90 @@
package install package install
import ( import (
"fmt" "fmt"
"errors" "errors"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
"oc-deploy/tool" "oc-deploy/tool"
"oc-deploy/kubectl" "oc-deploy/kubectl"
) )
func (this *InstallClass) Tools() (error) { func (this *InstallClass) Tools() (error) {
var mem []tool.ToolClass var mem []tool.ToolClass
for _, v := range this.tools { for _, v := range this.tools {
tool2 := tool.ToolClass{} tool2 := tool.ToolClass{}
v.Bin = this.Workspace v.Bin = this.Workspace
err := tool2.New(v) err := tool2.New(v)
if err != nil { if err != nil {
return err return err
} }
mem = append(mem,tool2) mem = append(mem,tool2)
} }
this.toolsBin = make(map[string]string) this.toolsBin = make(map[string]string)
for _, p := range mem { for _, p := range mem {
data := p.Obj.Get() data := p.Obj.Get()
log.Log().Info().Msg(fmt.Sprintf(" >> Outils : %s", data.Name)) log.Log().Info().Msg(fmt.Sprintf(" >> Outils : %s", data.Name))
err := p.Locate() err := p.Locate()
if err != nil { if err != nil {
log.Log().Info().Msg(fmt.Sprintf(" << %s ", err)) log.Log().Info().Msg(fmt.Sprintf(" << %s ", err))
return err return err
} }
log.Log().Info().Msg(fmt.Sprintf(" << %s ", p.Path)) log.Log().Info().Msg(fmt.Sprintf(" << %s ", p.Path))
version, err1 := p.Version() version, err1 := p.Version()
if err1 != nil { if err1 != nil {
log.Log().Info().Msg(fmt.Sprintf(" << %s ", err1)) log.Log().Info().Msg(fmt.Sprintf(" << %s ", err1))
return err1 return err1
} }
log.Log().Info().Msg(fmt.Sprintf(" << %s ", version)) log.Log().Info().Msg(fmt.Sprintf(" << %s ", version))
this.toolsBin[data.Name] = p.Path this.toolsBin[data.Name] = p.Path
} }
return nil return nil
} }
func (this *InstallClass) getToolBin(name string) (string, error) { func (this *InstallClass) getToolBin(name string) (string, error) {
for key, value := range this.toolsBin { for key, value := range this.toolsBin {
if key == name { if key == name {
return value, nil return value, nil
} }
} }
return "", errors.New("Error") return "", errors.New("Error")
} }
func (this *InstallClass) K8s(context string) (error) { func (this *InstallClass) K8s(context string) (error) {
bin_path, _ := this.getToolBin("kubectl") bin_path, _ := this.getToolBin("kubectl")
kube := kubectl.KubeContext{Bin: bin_path} kube := kubectl.KubeContext{Bin: bin_path}
err := kube.UseContext(context) err := kube.UseContext(context)
if err != nil { if err != nil {
log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", err)) log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", err))
return err return err
} }
currentcontext, namespace, server, err := kube.GetContext() currentcontext, namespace, server, err := kube.GetContext()
if err != nil { if err != nil {
log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", err)) log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", err))
return err return err
} }
log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", currentcontext)) log.Log().Info().Msg(fmt.Sprintf(" << Kube : %s ", currentcontext))
log.Log().Info().Msg(fmt.Sprintf(" << : %s ", namespace)) log.Log().Info().Msg(fmt.Sprintf(" << : %s ", namespace))
log.Log().Info().Msg(fmt.Sprintf(" << : %s ", server)) log.Log().Info().Msg(fmt.Sprintf(" << : %s ", server))
err = kube.Check() err = kube.Check()
if err != nil { if err != nil {
log.Log().Info().Msg(fmt.Sprintf(" << : %s ", err)) log.Log().Info().Msg(fmt.Sprintf(" << : %s ", err))
return err return err
} }
log.Log().Info().Msg(fmt.Sprintf(" << : %s ", "OK")) log.Log().Info().Msg(fmt.Sprintf(" << : %s ", "OK"))
return nil return nil
} }

View File

@ -1,108 +1,108 @@
package kubectl package kubectl
import ( import (
// "fmt" // "fmt"
"strings" "strings"
"errors" "errors"
"os/exec" "os/exec"
"encoding/json" "encoding/json"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
type KubeContext struct { type KubeContext struct {
Bin string // Chemin vers le binaire Bin string // Chemin vers le binaire
} }
type kubeConfig struct { type kubeConfig struct {
CurrentContext string `json:"current-context"` CurrentContext string `json:"current-context"`
Contexts [] kubeConfigContexts `json:"contexts"` Contexts [] kubeConfigContexts `json:"contexts"`
Clusters [] kubeConfigClusters `json:"clusters"` Clusters [] kubeConfigClusters `json:"clusters"`
} }
type kubeConfigContexts struct { type kubeConfigContexts struct {
Name string `json:"name"` Name string `json:"name"`
Context kubeConfigContext `json:"context"` Context kubeConfigContext `json:"context"`
} }
type kubeConfigContext struct { type kubeConfigContext struct {
Cluster string `json:"cluster"` Cluster string `json:"cluster"`
User string `json:"user"` User string `json:"user"`
Namespace string `json:"namespace"` Namespace string `json:"namespace"`
} }
type kubeConfigCluster struct { type kubeConfigCluster struct {
Server string `json:"server"` Server string `json:"server"`
} }
type kubeConfigClusters struct { type kubeConfigClusters struct {
Name string `json:"name"` Name string `json:"name"`
Cluster kubeConfigCluster `json:"cluster"` Cluster kubeConfigCluster `json:"cluster"`
} }
func (this KubeContext) GetCurrentContext() (string, error) { func (this KubeContext) GetCurrentContext() (string, error) {
cmd := exec.Command(this.Bin, "config", "current-context") cmd := exec.Command(this.Bin, "config", "current-context")
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
res := string(stdout) res := string(stdout)
res = strings.TrimSuffix(res, "\n") res = strings.TrimSuffix(res, "\n")
return res, err return res, err
} }
// Current Context // Current Context
// namespace, server // namespace, server
func (this KubeContext) GetContext() (string, string, string, error) { func (this KubeContext) GetContext() (string, string, string, error) {
cmd := exec.Command(this.Bin, "config", "view", "-o", "json") cmd := exec.Command(this.Bin, "config", "view", "-o", "json")
stdout, _ := cmd.CombinedOutput() stdout, _ := cmd.CombinedOutput()
var objmap kubeConfig var objmap kubeConfig
json.Unmarshal(stdout, &objmap) json.Unmarshal(stdout, &objmap)
currentContext := objmap.CurrentContext currentContext := objmap.CurrentContext
currentCluster := "" currentCluster := ""
currentNamespace := "" currentNamespace := ""
for _, v := range objmap.Contexts { for _, v := range objmap.Contexts {
if v.Name == currentContext { if v.Name == currentContext {
currentNamespace = v.Context.Namespace currentNamespace = v.Context.Namespace
currentCluster = v.Context.Cluster currentCluster = v.Context.Cluster
} }
} }
currentServer := "" currentServer := ""
for _, v := range objmap.Clusters { for _, v := range objmap.Clusters {
if v.Name == currentCluster { if v.Name == currentCluster {
currentServer = v.Cluster.Server currentServer = v.Cluster.Server
} }
} }
return currentContext, currentNamespace, currentServer, nil return currentContext, currentNamespace, currentServer, nil
} }
func (this KubeContext) UseContext(newContext string) (error) { func (this KubeContext) UseContext(newContext string) (error) {
cmd := exec.Command(this.Bin, "config", "use-context", newContext) cmd := exec.Command(this.Bin, "config", "use-context", newContext)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
log.Log().Debug().Msg(string(stdout)) log.Log().Debug().Msg(string(stdout))
return errors.New(string(stdout)) return errors.New(string(stdout))
} }
return nil return nil
} }
func (this KubeContext) Check() (error) { func (this KubeContext) Check() (error) {
cmd := exec.Command(this.Bin, "cluster-info") cmd := exec.Command(this.Bin, "cluster-info")
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
log.Log().Debug().Msg(string(stdout)) log.Log().Debug().Msg(string(stdout))
return errors.New("Kube non disponible") return errors.New("Kube non disponible")
} }
return nil return nil
} }

View File

@ -1,82 +1,82 @@
package kubectl package kubectl
import ( import (
"fmt" "fmt"
"strings" "strings"
"errors" "errors"
"time" "time"
"os/exec" "os/exec"
"encoding/json" "encoding/json"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
type KubeObject struct { type KubeObject struct {
Bin string // Chemin vers le binaire Bin string // Chemin vers le binaire
Name string Name string
} }
type getOutput struct { type getOutput struct {
Kind string `json:"kind"` Kind string `json:"kind"`
Status getStatusOutput `json:"status"` Status getStatusOutput `json:"status"`
} }
type getStatusOutput struct { type getStatusOutput struct {
Replicas int `json:"replicas"` Replicas int `json:"replicas"`
UnavailableReplicas int `json:"unavailableReplicas"` UnavailableReplicas int `json:"unavailableReplicas"`
} }
func (this KubeObject) Get() (map[string]any, error) { func (this KubeObject) Get() (map[string]any, error) {
bin := this.Bin bin := this.Bin
name := this.Name name := this.Name
msg := fmt.Sprintf("%s get deployment %s -o json", bin, name) msg := fmt.Sprintf("%s get deployment %s -o json", bin, name)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
m := make(map[string]any) m := make(map[string]any)
cmd_args := strings.Split(msg, " ") cmd_args := strings.Split(msg, " ")
cmd := exec.Command(cmd_args[0], cmd_args[1:]...) cmd := exec.Command(cmd_args[0], cmd_args[1:]...)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return m, errors.New(string(stdout)) return m, errors.New(string(stdout))
} }
var objmap getOutput var objmap getOutput
json.Unmarshal(stdout, &objmap) json.Unmarshal(stdout, &objmap)
kind := objmap.Kind kind := objmap.Kind
status := objmap.Status status := objmap.Status
m["name"] = name m["name"] = name
m["kind"] = kind m["kind"] = kind
m["replicas"] = status.Replicas m["replicas"] = status.Replicas
m["UnavailableReplicas"] = status.UnavailableReplicas m["UnavailableReplicas"] = status.UnavailableReplicas
return m, nil return m, nil
} }
func (this KubeObject) Wait() (error) { func (this KubeObject) Wait() (error) {
boucle := 10 boucle := 10
sleep := 10000 * time.Millisecond sleep := 10000 * time.Millisecond
for _ = range boucle { for _ = range boucle {
log.Log().Debug().Msg(fmt.Sprintf("Check Deployement %s", this.Name)) log.Log().Debug().Msg(fmt.Sprintf("Check Deployement %s", this.Name))
m, err := this.Get() m, err := this.Get()
if err != nil { if err != nil {
return err return err
} }
ko := m["UnavailableReplicas"].(int) ko := m["UnavailableReplicas"].(int)
if ko == 0 { if ko == 0 {
return nil return nil
} }
time.Sleep(sleep) time.Sleep(sleep)
} }
return errors.New("Temps d'attente dépassé") return errors.New("Temps d'attente dépassé")
} }

View File

@ -1,31 +1,31 @@
package kubectl package kubectl
import ( import (
"os/exec" "os/exec"
"encoding/json" "encoding/json"
) )
type toolClientVersion struct { type toolClientVersion struct {
GitVersion string `json:"gitVersion"` GitVersion string `json:"gitVersion"`
} }
type toolVersion struct { type toolVersion struct {
ClientVersion toolClientVersion `json:"clientVersion"` ClientVersion toolClientVersion `json:"clientVersion"`
} }
func Version(path string) (string, error) { func Version(path string) (string, error) {
cmd := exec.Command(path, "version", "-o", "json", "--client=true") cmd := exec.Command(path, "version", "-o", "json", "--client=true")
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return "", err return "", err
} }
var objmap toolVersion var objmap toolVersion
json.Unmarshal(stdout, &objmap) json.Unmarshal(stdout, &objmap)
res := objmap.ClientVersion.GitVersion res := objmap.ClientVersion.GitVersion
return res, nil return res, nil
} }

View File

@ -1,17 +1,17 @@
package tool package tool
import ( import (
"os" "os"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
type toolsData struct { type toolsData struct {
Tools []ToolData `yaml:"tools"` Tools []ToolData `yaml:"tools"`
} }
func FromConfigFile(filename string) ([]ToolData) { func FromConfigFile(filename string) ([]ToolData) {
yamlFile, _ := os.ReadFile(filename) yamlFile, _ := os.ReadFile(filename)
var data toolsData var data toolsData
yaml.Unmarshal(yamlFile, &data) yaml.Unmarshal(yamlFile, &data)
return data.Tools return data.Tools
} }

View File

@ -1,53 +1,53 @@
package tool package tool
import ( import (
"fmt" "fmt"
"os" "os"
// log "oc-deploy/log_wrapper" // log "oc-deploy/log_wrapper"
"oc-deploy/utils" "oc-deploy/utils"
"oc-deploy/helm" "oc-deploy/helm"
) )
type HelmInstallData struct { type HelmInstallData struct {
obj ToolData obj ToolData
tmp string tmp string
} }
func (this HelmInstallData) Get() (ToolData) { func (this HelmInstallData) Get() (ToolData) {
return this.obj return this.obj
} }
func (this HelmInstallData) Download() (error) { func (this HelmInstallData) Download() (error) {
bin_dir := this.obj.Bin bin_dir := this.obj.Bin
err2 := os.MkdirAll(bin_dir, os.ModePerm) err2 := os.MkdirAll(bin_dir, os.ModePerm)
if err2 != nil { if err2 != nil {
fmt.Println(err2) fmt.Println(err2)
return err2 return err2
} }
tmp_file := fmt.Sprintf("%s/oc-deploy-%s", this.tmp, this.obj.Name) tmp_file := fmt.Sprintf("%s/oc-deploy-%s", this.tmp, this.obj.Name)
url := fmt.Sprintf(this.obj.Url, this.obj.Version) url := fmt.Sprintf(this.obj.Url, this.obj.Version)
err := utils.DownloadFromUrl(tmp_file, url, 0777) err := utils.DownloadFromUrl(tmp_file, url, 0777)
if err != nil { if err != nil {
return err return err
} }
r, _ := os.Open(tmp_file) r, _ := os.Open(tmp_file)
err1 := utils.ExtractTarGz(bin_dir, r) err1 := utils.ExtractTarGz(bin_dir, r)
os.Remove(tmp_file) os.Remove(tmp_file)
bin_file := fmt.Sprintf("%s/%s", bin_dir, this.obj.Name) bin_file := fmt.Sprintf("%s/%s", bin_dir, this.obj.Name)
os.Chmod(bin_file, 0755) os.Chmod(bin_file, 0755)
return err1 return err1
} }
/////////////// ///////////////
func (this HelmInstallData) Version(path string) (string, error) { func (this HelmInstallData) Version(path string) (string, error) {
return helm.Version(path) return helm.Version(path)
} }

View File

@ -1,41 +1,41 @@
package tool package tool
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
"oc-deploy/utils" "oc-deploy/utils"
"oc-deploy/kubectl" "oc-deploy/kubectl"
) )
type KubecltInstallData struct { type KubecltInstallData struct {
obj ToolData obj ToolData
} }
func (this KubecltInstallData) Get() (ToolData) { func (this KubecltInstallData) Get() (ToolData) {
return this.obj return this.obj
} }
func (this KubecltInstallData) Download() (error) { func (this KubecltInstallData) Download() (error) {
bin_dir := this.obj.Bin bin_dir := this.obj.Bin
bin := filepath.Join(bin_dir, this.obj.Name) bin := filepath.Join(bin_dir, this.obj.Name)
url := fmt.Sprintf(this.obj.Url, this.obj.Version) url := fmt.Sprintf(this.obj.Url, this.obj.Version)
log.Log().Debug().Msg(fmt.Sprintf("Téléchargement : %s, %s", bin, url)) log.Log().Debug().Msg(fmt.Sprintf("Téléchargement : %s, %s", bin, url))
os.MkdirAll(bin_dir, os.ModePerm) os.MkdirAll(bin_dir, os.ModePerm)
err := utils.DownloadFromUrl(bin, url, 0777) err := utils.DownloadFromUrl(bin, url, 0777)
if err != nil {return err} if err != nil {return err}
os.Chmod(bin, 0755) os.Chmod(bin, 0755)
return nil return nil
} }
/////////////// ///////////////
func (this KubecltInstallData) Version(path string) (string, error) { func (this KubecltInstallData) Version(path string) (string, error) {
return kubectl.Version(path) return kubectl.Version(path)
} }

View File

@ -1,80 +1,80 @@
package tool package tool
import ( import (
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"errors" "errors"
"path/filepath" "path/filepath"
) )
type ToolData struct { type ToolData struct {
Name string `yaml:"name"` Name string `yaml:"name"`
Url string `yaml:"url"` Url string `yaml:"url"`
Version string `yaml:"version"` Version string `yaml:"version"`
Bin string Bin string
} }
type ToolClass struct { type ToolClass struct {
Obj Forme Obj Forme
Path string Path string
} }
type Forme interface { type Forme interface {
Download() error Download() error
Version(string) (string, error) Version(string) (string, error)
Get() ToolData Get() ToolData
} }
////////// //////////
func (this *ToolClass) New(data ToolData) (error) { func (this *ToolClass) New(data ToolData) (error) {
f, err := factory(data) f, err := factory(data)
if err != nil { if err != nil {
return err return err
} }
this.Obj = f this.Obj = f
return nil return nil
} }
func (this *ToolClass) Locate() (error) { func (this *ToolClass) Locate() (error) {
obj := this.Obj obj := this.Obj
data := obj.Get() data := obj.Get()
path := filepath.Join(data.Bin, data.Name) path := filepath.Join(data.Bin, data.Name)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
path2, _ := exec.LookPath(data.Name) path2, _ := exec.LookPath(data.Name)
if path2 != "" { if path2 != "" {
path = path2 path = path2
} else { } else {
err = obj.Download() err = obj.Download()
if err != nil { if err != nil {
return err return err
} }
} }
} }
this.Path = path this.Path = path
return nil return nil
} }
func (this *ToolClass) Version() (string, error) { func (this *ToolClass) Version() (string, error) {
obj := (this.Obj) obj := (this.Obj)
return obj.Version(this.Path) return obj.Version(this.Path)
} }
////////// //////////
func factory(data ToolData) (Forme, error) { func factory(data ToolData) (Forme, error) {
var f Forme var f Forme
switch data.Name { switch data.Name {
case "kubectl": case "kubectl":
f = KubecltInstallData{obj: data} f = KubecltInstallData{obj: data}
case "helm": case "helm":
f = HelmInstallData{obj: data, tmp: "/tmp"} f = HelmInstallData{obj: data, tmp: "/tmp"}
default: default:
return f, errors.New(fmt.Sprintf("Outil Inconnu : %s", data.Name)) return f, errors.New(fmt.Sprintf("Outil Inconnu : %s", data.Name))
} }
return f, nil return f, nil
} }

View File

@ -1,35 +1,35 @@
package utils package utils
import ( import (
"os" "os"
"io" "io"
"path/filepath" "path/filepath"
) )
func CopyFile(src string, dst string) (error) { func CopyFile(src string, dst string) (error) {
if _, err := os.Stat(src); err != nil { if _, err := os.Stat(src); err != nil {
return err return err
} }
fin, errOpen := os.Open(src) fin, errOpen := os.Open(src)
if errOpen != nil { if errOpen != nil {
return errOpen return errOpen
} }
defer fin.Close() defer fin.Close()
folderPath := filepath.Dir(dst) folderPath := filepath.Dir(dst)
os.MkdirAll(folderPath, os.ModePerm) os.MkdirAll(folderPath, os.ModePerm)
fout, errCreate := os.Create(dst) fout, errCreate := os.Create(dst)
if errCreate != nil { if errCreate != nil {
return errCreate return errCreate
} }
defer fout.Close() defer fout.Close()
_, errCopy := io.Copy(fout, fin) _, errCopy := io.Copy(fout, fin)
if errCopy != nil { if errCopy != nil {
return errCopy return errCopy
} }
return nil return nil
} }

View File

@ -1,47 +1,47 @@
package utils package utils
// https://pkg.go.dev/github.com/stretchr/testify/assert#Nilf // https://pkg.go.dev/github.com/stretchr/testify/assert#Nilf
import ( import (
"testing" "testing"
"path/filepath" "path/filepath"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestCopyFileExist(t *testing.T){ func TestCopyFileExist(t *testing.T){
src := filepath.Join(TEST_SRC_DIR, "fichier1") src := filepath.Join(TEST_SRC_DIR, "fichier1")
dest := filepath.Join(TEST_DEST_DIR, "fichier1") dest := filepath.Join(TEST_DEST_DIR, "fichier1")
err := CopyFile(src, dest) err := CopyFile(src, dest)
assert.Nilf(t, err, "error message %s", src) assert.Nilf(t, err, "error message %s", src)
assert.FileExists(t, dest, "CopyFile error") assert.FileExists(t, dest, "CopyFile error")
} }
func TestCopyErrSrcFileNotExist(t *testing.T) { func TestCopyErrSrcFileNotExist(t *testing.T) {
src := filepath.Join(TEST_SRC_DIR, "inconnu") src := filepath.Join(TEST_SRC_DIR, "inconnu")
dest := filepath.Join(TEST_DEST_DIR, "inconnu") dest := filepath.Join(TEST_DEST_DIR, "inconnu")
err := CopyFile(src, dest) err := CopyFile(src, dest)
assert.NotNilf(t, err, "CopyFile error %s", src) assert.NotNilf(t, err, "CopyFile error %s", src)
} }
func TestCopyFileErrCreate(t *testing.T){ func TestCopyFileErrCreate(t *testing.T){
src := filepath.Join(TEST_SRC_DIR, "fichier1") src := filepath.Join(TEST_SRC_DIR, "fichier1")
dest := filepath.Join("/INCONNU", "fichier1") dest := filepath.Join("/INCONNU", "fichier1")
err := CopyFile(src, dest) err := CopyFile(src, dest)
assert.NotNilf(t, err, "error message %s", src) assert.NotNilf(t, err, "error message %s", src)
assert.NoFileExists(t, dest, "CopyFile error") assert.NoFileExists(t, dest, "CopyFile error")
} }
func TestCopyErrSrcWrite(t *testing.T) { func TestCopyErrSrcWrite(t *testing.T) {
src := "/" src := "/"
dest := filepath.Join(TEST_DEST_DIR, "inconnu") dest := filepath.Join(TEST_DEST_DIR, "inconnu")
err := CopyFile(src, dest) err := CopyFile(src, dest)
assert.NotNilf(t, err, "CopyFile error %s", src) assert.NotNilf(t, err, "CopyFile error %s", src)
} }

View File

@ -1,28 +1,28 @@
package utils package utils
// https://pkg.go.dev/github.com/stretchr/testify/assert#Nilf // https://pkg.go.dev/github.com/stretchr/testify/assert#Nilf
import ( import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/jarcoal/httpmock" "github.com/jarcoal/httpmock"
) )
func TestDownload(t *testing.T){ func TestDownload(t *testing.T){
httpmock.Activate() httpmock.Activate()
defer httpmock.DeactivateAndReset() defer httpmock.DeactivateAndReset()
url := "http://test.download.com" url := "http://test.download.com"
httpmock.RegisterResponder("GET", url, httpmock.RegisterResponder("GET", url,
httpmock.NewStringResponder(200, `CONTENU_URL`)) httpmock.NewStringResponder(200, `CONTENU_URL`))
dest := filepath.Join(TEST_DEST_DIR, "url") dest := filepath.Join(TEST_DEST_DIR, "url")
err := DownloadFromUrl(dest, url, 777) err := DownloadFromUrl(dest, url, 777)
assert.Nilf(t, err, "error message %s", url) assert.Nilf(t, err, "error message %s", url)
assert.FileExists(t, dest, "DownloadFromUrl error") assert.FileExists(t, dest, "DownloadFromUrl error")
} }

View File

@ -1,23 +1,23 @@
package utils package utils
import ( import (
"os" "os"
"testing" "testing"
"path/filepath" "path/filepath"
) )
var TEST_DEST_DIR = "../wrk_utils" var TEST_DEST_DIR = "../wrk_utils"
var TEST_SRC_DIR = filepath.Join("../../test", "utils") var TEST_SRC_DIR = filepath.Join("../../test", "utils")
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
folderPath := TEST_DEST_DIR folderPath := TEST_DEST_DIR
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.MkdirAll(folderPath, os.ModePerm) os.MkdirAll(folderPath, os.ModePerm)
// call flag.Parse() here if TestMain uses flags // call flag.Parse() here if TestMain uses flags
exitCode := m.Run() exitCode := m.Run()
os.RemoveAll(folderPath) os.RemoveAll(folderPath)
os.Exit(exitCode) os.Exit(exitCode)
} }