templatefile/pkg/templater/services.go

123 lines
2.8 KiB
Go

package templater
import (
"encoding/json"
"fmt"
"log"
"path/filepath"
)
type Service struct {
ConfigFiles []ConfigFile `json:"ConfigFiles"`
Vars map[string]interface{} `json:"Vars"`
Daemons map[string]SystemService `json:"Daemons"`
Users map[string]SystemUser `json:"Users"`
Repos map[string]Repository `json:"Repositories"`
Packages map[string]SystemPackage `json:"Packages"`
}
func (s *Service) manageRepos(repos map[string]Repository) error {
for _, repo := range s.Repos {
if repo.Type == "helm" {
rp := HelmRepository{repo}
if err := rp.Manage(); err != nil {
return err
}
}
if repo.Type == "apk" {
rp := APKRepository{repo}
if err := rp.Manage(); err != nil {
return err
}
}
if repo.Type == "deb" {
rp := DebRepository{}
if err := rp.Manage(); err != nil {
return err
}
}
}
return nil
}
func (s *Service) Manage(templateDir string, rootDir string) error {
// Manage packages repositories
log.Print(" Managing package repositories")
err := s.manageRepos(s.Repos)
if err != nil {
return err
}
// Create system users
log.Print(" Managing system users")
for _, user := range s.Users {
err := user.Manage()
if err != nil {
return err
}
}
// Manage system packages
log.Print(" Installing packages")
for _, pack := range s.Packages {
err := pack.Manage()
if err != nil {
return err
}
log.Printf("\tPackage %s installed\n", pack.Name)
}
log.Print(" Generating configuration files\n")
err = processConfigFiles(s, templateDir, rootDir)
if err != nil {
return fmt.Errorf("ProcessingTemplatesFailed with error: %v", err)
}
log.Print(" Managing services:\n")
for _, daemon := range s.Daemons {
err = daemon.Manage()
if err != nil {
return fmt.Errorf("Error managing service daemons: %v", err)
}
}
return nil
}
func processConfigFiles(s *Service, templateDir string, rootDir string) error {
values, err := json.Marshal(s)
if err != nil {
return fmt.Errorf("Error unmarshaling values on template process; %v", err)
}
var servicesToRestart []string
for _, tpl := range s.ConfigFiles {
fileExt := filepath.Ext(tpl.Source)
if fileExt == ".hcl" {
tpl.TemplateType = "hcl"
} else if fileExt == ".tpl" {
tpl.TemplateType = "go"
} else {
return fmt.Errorf("Unsupported file type %s, templates extensions have to be '.hcl' or '.tpl'", fileExt)
}
if err := tpl.Generate(rootDir, templateDir, values); err != nil {
return fmt.Errorf("Template %s generation failed with error %v", tpl.Source, err)
}
if len(tpl.Service) != 0 {
servicesToRestart = append(servicesToRestart, tpl.Service)
}
}
for _, srv := range servicesToRestart {
sv := SystemService{
Name: srv,
Enabled: true,
Type: "",
ToStart: true,
}
return sv.Restart()
}
return nil
}