integrated the parser with the validator to ge tbetter error messages.

This commit is contained in:
2025-01-12 14:56:36 +01:00
parent 548260d3ab
commit ff816a02ae
7 changed files with 291 additions and 62 deletions
+6 -10
View File
@@ -93,16 +93,6 @@ func (c *Config) Update(config *Config) {
c.Communications = append(c.Communications, config.Communications...)
}
func (c Config) ValidateSchema() error {
validator, err := NewValidator()
if err != nil {
return err
}
err = validator.ValidateStruct(c)
return err
}
func (c Config) Validate() error {
errs := make([]error, 0)
@@ -188,11 +178,17 @@ func LoadConfig(file string) (*Config, error) {
return nil, fmt.Errorf("Error reading YAML file: %v", err)
}
validator, err := NewValidator()
if err != nil {
return nil, err
}
// Parse the YAML content
dec := yaml.NewDecoder(bytes.NewReader(yamlFile),
yaml.UseJSONUnmarshaler(),
yaml.DisallowUnknownField(),
yaml.UseOrderedMap(),
yaml.Validator(validator),
yaml.Strict(),
)
var config Config
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"log"
)
func GetKubernetesConnection() (*kubernetes.Clientset, string) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
config, err := kubeConfig.ClientConfig()
if err != nil {
log.Panicln(err.Error())
}
//log.Println("Using configuration:", config.String())
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Panicln(err.Error())
}
namespace, _, err := kubeConfig.Namespace()
if err != nil {
log.Panicf("Could not get namespace")
}
return clientset, namespace
}
+41 -26
View File
@@ -2,7 +2,6 @@ package main
import (
"fmt"
"github.com/goccy/go-yaml"
"github.com/spf13/cobra"
"log"
"os"
@@ -13,25 +12,30 @@ type Options struct {
policyType string
}
func execute(files []string, options *Options) error {
if len(files) == 0 {
return fmt.Errorf("File expected")
}
func readConfig(files []string) (*Config, error) {
config := &Config{}
for _, file := range files {
log.Printf("LOADING %s\n", file)
configNew, err := LoadConfig(file)
if err != nil {
return fmt.Errorf("%s: %w", file, err)
}
if err = configNew.ValidateSchema(); err != nil {
return fmt.Errorf("%s: %w", file, err)
return nil, fmt.Errorf("%s: %w", file, err)
}
config.Update(configNew)
}
err := config.Validate()
if err != nil {
return fmt.Errorf("Error loading configuration: %w", err)
return nil, fmt.Errorf("Error loading configuration: %w", err)
}
return config, nil
}
func generate(files []string, options *Options) error {
if len(files) == 0 {
return fmt.Errorf("File expected")
}
config, err := readConfig(files)
if err != nil {
return err
}
policyTemplates, err := NewPolicyTemplates()
@@ -51,17 +55,11 @@ func execute(files []string, options *Options) error {
return nil
}
func main() {
func validate(files []string, options *Options) error {
return nil
}
val := map[string]string{
"abc": "1",
}
data, err := yaml.Marshal(val)
if err != nil {
panic(err)
}
log.Printf("val %s", string(data))
//os.Exit(1)
func main() {
options := Options{
cni: "cilium",
@@ -69,14 +67,31 @@ func main() {
}
cmd := &cobra.Command{
Use: "policygen",
Short: "Generate network policies",
Long: "Generated policies based on a more compact representation of topology",
RunE: func(cmd *cobra.Command, args []string) error {
return execute(args, &options)
},
Short: "Defining policies to enforce topology using network policies and service meshes",
Long: "Defining policies to enforce topology using network policies and service meshes",
}
err = cmd.Execute()
generate := &cobra.Command{
Use: "generate",
Short: "Generate policies",
Long: "Generate policies",
RunE: func(cmd *cobra.Command, args []string) error {
return generate(args, &options)
},
}
cmd.AddCommand(generate)
validate := &cobra.Command{
Use: "validate",
Short: "Validate configuration",
Long: "Validate configuration",
RunE: func(cmd *cobra.Command, args []string) error {
return validate(args, &options)
},
}
cmd.AddCommand(validate)
err := cmd.Execute()
if err != nil {
os.Exit(1)
}
+29 -5
View File
@@ -1,7 +1,6 @@
package main
import (
"errors"
"fmt"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
@@ -14,6 +13,11 @@ type Validator struct {
trans ut.Translator
}
func (v Validator) Struct(i interface{}) error {
err := v.validate.Struct(i)
return v.Translate(err)
}
type Translation struct {
format string
params func(fe validator.FieldError) []any
@@ -23,11 +27,27 @@ var translations = map[string]Translation{
"oneof": {
"{0} must be one of [{1}], got '{2}'",
func(fe validator.FieldError) []any {
return []any{fe.Field(), fe.Param(), fe.Value()}
return []any{fe.Namespace(), fe.Param(), fe.Value()}
},
},
}
type TranslatedFieldError struct {
validator.FieldError
msg string
}
func NewTranslatedFieldError(msg string, e validator.FieldError) TranslatedFieldError {
return TranslatedFieldError{
FieldError: e,
msg: msg,
}
}
func (e TranslatedFieldError) Error() string {
return e.msg
}
func NewValidator() (*Validator, error) {
validate := validator.New(validator.WithRequiredStructEnabled())
language := en.New()
@@ -74,9 +94,13 @@ func (v Validator) Translate(err error) error {
return err
}
errorList := make([]error, 0)
var errorList validator.ValidationErrors = nil
for _, e := range errs {
errorList = append(errorList, fmt.Errorf("%s", e.Translate(v.trans)))
var translation validator.FieldError = TranslatedFieldError{
FieldError: e,
msg: e.Translate(v.trans),
}
errorList = append(errorList, translation)
}
return errors.Join(errorList...)
return errorList
}