Skip to content

Commit

Permalink
fixes, new tests, remote kubernetes manifest
Browse files Browse the repository at this point in the history
  • Loading branch information
arti-shalb committed Aug 19, 2024
1 parent bf14214 commit 26c2e74
Show file tree
Hide file tree
Showing 25 changed files with 276 additions and 92 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
"subcommand",
"submodules",
"sysctl",
"templating",
"testrepo",
"tfmodule",
"tfplan",
Expand Down
1 change: 1 addition & 0 deletions internal/project/scanners.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func StateOutputsReplacer(data reflect.Value, unit Unit) (reflect.Value, error)
resString := subVal.String()
markersList := unit.Project().UnitLinks.ByLinkTypes(OutputLinkType).Map()
for key, marker := range markersList {
// log.Warnf("StateOutputsReplacer: %v", key)
if strings.Contains(resString, key) {
resString = strings.ReplaceAll(resString, key, fmt.Sprintf("<output %v.%v.%v>", marker.TargetStackName, marker.TargetUnitName, marker.OutputName))
}
Expand Down
4 changes: 0 additions & 4 deletions internal/project/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,6 @@ func (p *Project) LoadState() (*StateProject, error) {
if err != nil {
return nil, err
}
for key := range statePrj.Units {
log.Warnf("LoadState %v", key)
}

return statePrj, nil
}

Expand Down
6 changes: 3 additions & 3 deletions internal/project/templating.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,9 @@ func (d *GlobalTemplateDriver) AddTemplateFunctions(mp template.FuncMap, p *Proj

addOutputMarkerFunk := func(path string) (string, error) {
splittedPath := strings.Split(path, ".")
// if len(splittedPath) != 3 {
// return "", fmt.Errorf("bad dependency path 2")
// }
if len(splittedPath) == 2 {
splittedPath = append([]string{"this"}, splittedPath...)
}

dep := ULinkT{
Unit: nil,
Expand Down
2 changes: 1 addition & 1 deletion internal/units/shell/common/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/apex/log"
)

var fileSizeLimit int64 = 102400
var fileSizeLimit int64 = 1024000
var ignorePatterns []string = []string{
".*\\.terraform/.*",
".*\\.git/.*",
Expand Down
3 changes: 1 addition & 2 deletions internal/units/shell/common/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,9 @@ func (u *Unit) GetUnitDiff() UnitDiffSpec {
for _, file := range *u.CreateFiles {
fileLines := strings.Split(file.Content, "\n")
if len(fileLines) < 2 {
filesListDiff[file.FileName][0] = file.Content
filesListDiff[file.FileName] = append(filesListDiff[file.FileName], file.Content)
} else {
for _, line := range fileLines {
//log.Warnf("filesListDiff %v", line)
if line == "" {
continue // Ignore empty lines
}
Expand Down
26 changes: 8 additions & 18 deletions internal/units/shell/common/unit.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,7 @@ type OperationConfig struct {
Commands []interface{} `yaml:"commands" json:"commands"`
}

type OutputsT struct {
List map[string]*project.ULinkT `json:"outputs_list,omitempty"`
}

// OutputsConfigSpec describe how to retrive parse unit outputs.
// OutputsConfigSpec describe how to retrieve parse unit outputs.
type OutputsConfigSpec struct {
Command string `yaml:"command,omitempty" json:"command,omitempty"`
Type string `yaml:"type" json:"type"`
Expand Down Expand Up @@ -105,7 +101,7 @@ func (u *Unit) ForceApply() bool {
return u.FApply
}

// WasApplied return true if unit's method Apply was runned.
// WasApplied return true if unit's method Apply was ran.
func (u *Unit) WasApplied() bool {
return u.AlreadyApplied
}
Expand Down Expand Up @@ -314,8 +310,6 @@ func (u *Unit) Apply() error {
err = parser(string(u.OutputRaw), u.ProjectPtr.UnitLinks.ByTargetUnit(u).ByLinkTypes(project.OutputLinkType))
if err != nil {

//str := fmt.Sprintf("Outputs data: %s", string(u.OutputRaw))
// log.Warnf("Len: %v", len(str))
u.SetTainted(true, err)
return fmt.Errorf("parse outputs '%v': %w", u.GetOutputsConf.Type, err)
}
Expand All @@ -327,14 +321,6 @@ func (u *Unit) Apply() error {
return err
}

// func (u *Unit) MarkTainted(err error) {
// u.ExecErr = err
// if u.SavedState != nil {
// u.SavedState.SetTainted(true)
// log.Warnf("MarkTainted %v", u.SavedState.IsTainted())
// }
// }

func (u *Unit) runCommands(commandsCnf OperationConfig, name string) ([]byte, error) {
if len(commandsCnf.Commands) == 0 {
log.Debugf("configuration for '%v' is empty for unit '%v'. Skip.", name, u.Key())
Expand Down Expand Up @@ -439,7 +425,6 @@ func (u *Unit) UpdateProjectRuntimeData(p *project.Project) error {
}

func (u *Unit) ScanData(scanner project.MarkerScanner) error {
// log.Warnf("Replacing markers...")
if u.Env != nil {
err := project.ScanMarkers(u.Env, scanner, u)
if err != nil {
Expand Down Expand Up @@ -547,7 +532,7 @@ func readHook(hookData interface{}, hookType string) (*HookSpec, error) {
cmd, cmdExists := hook["command"].(string)

if !cmdExists {
return nil, fmt.Errorf("error in %s config, use 'script' option", hookType)
return nil, fmt.Errorf("error in %s config, 'command' option is required", hookType)
}

ScriptData := HookSpec{
Expand Down Expand Up @@ -586,14 +571,19 @@ func (u *Unit) EnvSlice() []string {
return res
}

// SetExecStatus set unit execution status (backlog, in progress, etc).
func (u *Unit) SetExecStatus(status project.ExecutionStatus) {
if u.GetExecStatus() != status {
u.ExecStatus = status
}
}

// GetExecStatus get current execution status.
func (u *Unit) GetExecStatus() project.ExecutionStatus {
return u.ExecStatus
}

// ExecError return last execution error
func (u *Unit) ExecError() error {
return u.ExecErr
}
7 changes: 5 additions & 2 deletions internal/units/shell/k8s_manifest/unit.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (u *Unit) ReadManifestsPath(src string) error {
}
if isDir {
u.ManifestsFiles.ReadDir(manifestsPath, baseDir, `.ya{0,1}ml$`)
// log.Debugf("List %v", u.ManifestsFiles.SPrintLs())
log.Debugf("List %v", u.ManifestsFiles.SPrintLs())
if u.ManifestsFiles.IsEmpty() {
return fmt.Errorf("read unit '%v': no manifests found in path %v", u.Name(), u.Path)
}
Expand All @@ -139,7 +139,7 @@ func (u *Unit) ReadManifestsPath(src string) error {
} else {
manifest, err := utils.GetFileByUrl(src)
if err != nil {
return fmt.Errorf("get remote file: %w", err)
return fmt.Errorf("get remote file by url (%v): %w", src, err)
}
err = u.ManifestsFiles.AddOverride("./main.yaml", manifest, fs.ModePerm)
if err != nil {
Expand Down Expand Up @@ -215,6 +215,9 @@ func (u *Unit) GetManifestsMap() (res map[string]interface{}, namespaces []strin
res = make(map[string]interface{})
namespaces = []string{}
nsUniq := map[string]bool{}
if u == nil {
return
}
for _, file := range *u.ManifestsFiles {
mns, err := utils.ReadYAMLObjects([]byte(file.Content))
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/units/shell/terraform/helm/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,15 @@ func (u *Unit) GetUnitDiff() UnitDiffSpec {
Source: u.Source,
HelmOpts: u.HelmOpts,
Sets: u.Sets,
// Values: u.ValuesFilesList,
}
filesListDiff := make([]interface{}, len(u.ValuesFilesList))
st.Outputs = nil
for i, str := range u.ValuesFilesList {
fileLines := strings.Split(str, "\n")
if len(fileLines) < 2 {
filesListDiff[i] = str
} else {
for _, line := range fileLines {
//log.Warnf("filesListDiff %v", line)
if line == "" {
continue // Ignore empty lines
}
Expand All @@ -69,6 +68,7 @@ func (u *Unit) GetDiffData() interface{} {
res := map[string]interface{}{}
utils.JSONCopy(st, &res)
project.ScanMarkers(res, base.StringRemStScanner, u)
project.ScanMarkers(res, project.OutputsReplacer, u)
return res
}

Expand Down
45 changes: 28 additions & 17 deletions internal/units/shell/terraform/kubernetes/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/apex/log"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/shalb/cluster.dev/internal/config"
"github.com/shalb/cluster.dev/internal/units/shell/terraform/base"
"github.com/shalb/cluster.dev/pkg/hcltools"

Expand Down Expand Up @@ -71,30 +72,40 @@ func (u *Unit) ReadConfig(spec map[string]interface{}, stack *project.Stack) err
if !ok {
return fmt.Errorf("reading kubernetes unit '%v': malformed unit source", u.Key())
}
tmplDir := u.Stack().TemplateDir
var absSource string
if source[1:2] == "/" {
absSource = filepath.Join(tmplDir, source)
} else {
absSource = source
}
fileInfo, err := os.Stat(absSource)
if err != nil {
return fmt.Errorf("reading kubernetes unit '%v': reading kubernetes manifests form source '%v': %v", u.Key(), source, err.Error())
}
var filesList []string
if fileInfo.IsDir() {
filesList, err = filepath.Glob(absSource + "/*.yaml")
if utils.IsLocalPath(source) {
if utils.IsAbsolutePath(source) {
absSource = source
} else {
absSource = filepath.Join(config.Global.ProjectConfigsPath, u.Stack().TemplateDir, source)
}

fileInfo, err := os.Stat(absSource)
if err != nil {
return fmt.Errorf("reading kubernetes unit '%v': reading kubernetes manifests form source '%v': %v", u.Key(), source, err.Error())
return fmt.Errorf("reading kubernetes unit '%v': check file: '%v': %v", u.Key(), source, err.Error())
}
if fileInfo.IsDir() {
filesList, err = utils.ListFilesByRegex(absSource, `\.ya{0,1}ml$`) //filepath.Glob(absSource + "/*.yaml")
if err != nil {
return fmt.Errorf("reading kubernetes unit '%v': list manifests in dir '%v': %v", u.Key(), source, err.Error())
}
} else {
filesList = append(filesList, absSource)
}
} else {
filesList = append(filesList, absSource)
filesList = append(filesList, source)
}
for _, fileName := range filesList {
file, err := os.ReadFile(fileName)
var file []byte
var err error
if utils.IsLocalPath(fileName) {
file, err = os.ReadFile(fileName)
} else {
file, err = utils.GetFileByUrlByte(fileName)
}
if err != nil {
return fmt.Errorf("reading kubernetes unit '%v': reading kubernetes manifests form source '%v': %v", u.Key(), source, err.Error())
return fmt.Errorf("reading kubernetes unit '%v': read manifest from '%v': %v", u.Key(), source, err.Error())
}
manifest, errIsWarn, err := u.Stack().TemplateTry(file, fileName)
if err != nil {
Expand All @@ -119,7 +130,7 @@ func (u *Unit) ReadConfig(spec map[string]interface{}, stack *project.Stack) err
return fmt.Errorf("the kubernetes unit must contain at least one manifest")
}

err = utils.YAMLInterfaceToType(spec, u)
err := utils.YAMLInterfaceToType(spec, u)
if err != nil {
return err
}
Expand Down
13 changes: 13 additions & 0 deletions internal/units/shell/terraform/kubernetes/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,21 @@ func (u *Unit) GetStateUnit() *Unit {
log.Fatalf("read unit '%v': create state: %w", u.Name(), err)
}
unitState.Unit = *u.Unit.GetStateUnit()
// unitState.GetOutputsConf = nil
return &unitState
}

func printStateDebug(state interface{}, comment string) {
js, _ := utils.JSONEncodeString(state)
log.Warnf("printStateDebug [%v]: %v", comment, js)
}

func (u *Unit) GetState() project.Unit {
if u.StateData != nil {
// printStateDebug(u.StateData, "GetState")
return u.StateData
}
// printStateDebug(u.GetStateUnit(), "GetState")
return u.GetStateUnit()
}

Expand All @@ -47,8 +55,10 @@ func (u *Unit) GetUnitDiff() UnitDiffSpec {
func (u *Unit) GetDiffData() interface{} {
st := u.GetUnitDiff()
res := map[string]interface{}{}
st.Outputs = nil
utils.JSONCopy(st, &res)
project.ScanMarkers(res, base.StringRemStScanner, u)
// printStateDebug(res, "GetDiffData")
return res
}

Expand All @@ -61,5 +71,8 @@ func (u *Unit) LoadState(stateData interface{}, modKey string, p *project.StateP
if err != nil {
return fmt.Errorf("load state: %v", err.Error())
}
// u.GetState()
// u.GetDiffData()
u.GetOutputsConf = nil
return nil
}
29 changes: 29 additions & 0 deletions pkg/utils/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,32 @@ func RemoveDirContent(dir string) error {
}
return nil
}

func ListFilesByRegex(dirPath, pattern string) ([]string, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("invalid regex pattern: %s", err)
}

var matches []string
err = filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

if info.IsDir() {
return nil
}

if re.MatchString(info.Name()) {
matches = append(matches, path)
}
return nil
})

if err != nil {
return nil, fmt.Errorf("error walking directory: %s", err)
}

return matches, nil
}
19 changes: 19 additions & 0 deletions pkg/utils/net.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package utils

import (
"bytes"
"errors"
"fmt"
"io"
"math/big"
Expand Down Expand Up @@ -60,3 +62,20 @@ func GetFileByUrl(srcUrl string) (string, error) {

return buf.String(), nil
}

func GetFileByUrlByte(URL string) ([]byte, error) {
response, err := http.Get(URL)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, errors.New(response.Status)
}
var data bytes.Buffer
_, err = io.Copy(&data, response.Body)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
4 changes: 3 additions & 1 deletion pkg/utils/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ func ReadYAMLObjects(objData []byte) ([]map[string]interface{}, error) {
// log.Debugf("can't decode config to yaml: %s", err.Error())
return nil, fmt.Errorf("can't decode config to yaml: %s", ResolveYamlError(objData, err))
}
objects = append(objects, parsedConf)
if len(parsedConf) > 0 { // Ignore empty yaml parts, like two '---' with only comment between.
objects = append(objects, parsedConf)
}
}
return objects, nil
}
Expand Down
Loading

0 comments on commit 26c2e74

Please sign in to comment.