templatefile/pkg/templater/packages.go

94 lines
2.2 KiB
Go

package templater
import (
"fmt"
"log"
"runtime"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
type SystemPackage struct {
Name string `json:"name"`
Type string `json:"type"`
Action string `json:"action"`
OS string `json:"os"`
Distribution string `json:"distribution"`
NameSpace string `json:"namespace"`
Repository string `json:"repository"`
URL string `json:"url"`
}
func (p *SystemPackage) SetDistribution() error {
// If the package type is helm or kubectl we set distribution to k8s
if p.Type == "helm" || p.Type == "kubectl" {
p.Distribution = p.Type
if len(p.NameSpace) == 0 {
p.NameSpace = p.Name
}
return nil
}
OSConfig, err := utils.ReadOSRelease()
if err != nil {
return err
}
p.Distribution = OSConfig["ID_LIKE"]
return nil
}
func (p *SystemPackage) SetOS() error {
p.OS = runtime.GOOS
return nil
}
func (p *SystemPackage) Manage() error {
var pkErr error
var stdErr []byte
if p.OS == "" {
if err := p.SetOS(); err != nil {
return err
}
}
if p.Distribution == "" {
if err := p.SetDistribution(); err != nil {
return err
}
}
log.Printf("\tInstalling %s package\n", p.Name)
switch os := p.Distribution; os {
case "debian", "ubuntu":
_, stdErr, pkErr = utils.RunSystemCommand("apt", "install", "-y", p.Name)
case "alpine":
_, stdErr, pkErr = utils.RunSystemCommand("apk", "add", p.Name)
case "redhat":
_, stdErr, pkErr = utils.RunSystemCommand("yum", "install", "-y", p.Name)
case "arch":
_, stdErr, pkErr = utils.RunSystemCommand("pacman", "-Suy", p.Name)
case "helm":
toInstall := fmt.Sprintf("%s/%s", p.Repository, p.Name)
nameSpaceOPT := fmt.Sprintf("--namespace=%s", p.NameSpace)
_, stdErr, pkErr = utils.RunSystemCommand("helm", "upgrade", "--install", p.Name, nameSpaceOPT, toInstall)
case "kubectl":
_, stdErr, pkErr = utils.RunSystemCommand("kubectl", "apply", p.URL)
default:
pkErr = fmt.Errorf("Unsupported OS %s [%s]", p.OS, stdErr)
}
if pkErr != nil {
var msg string
if len(stdErr) != 0 {
msg = string(stdErr)
} else {
msg = pkErr.Error()
}
return fmt.Errorf("Package %s, os %s, failed with error: %v", p.Name, p.OS, msg)
}
return nil
}