github.com/datreeio/datree@v1.9.22-rc/pkg/jsonSchemaValidator/extensions/customKeyRule81.go (about)

     1  // This file defines a custom key to implement the logic for the rule:
     2  // https://hub.datree.io/built-in-rules/ensure-memory-request-limit-equal
     3  
     4  package jsonSchemaValidator
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  
    10  	"github.com/santhosh-tekuri/jsonschema/v5"
    11  )
    12  
    13  type CustomKeyRule81Compiler struct{}
    14  
    15  type CustomKeyRule81Schema map[string]interface{}
    16  
    17  var CustomKeyRule81 = jsonschema.MustCompileString("customKeyRule81.json", `{
    18  	"properties" : {
    19  		"customKeyRule81": {
    20  			"type": "string"
    21  		}
    22  	}
    23  }`)
    24  
    25  func (CustomKeyRule81Compiler) Compile(ctx jsonschema.CompilerContext, m map[string]interface{}) (jsonschema.ExtSchema, error) {
    26  	if customKeyRule81, ok := m["customKeyRule81"]; ok {
    27  		customKeyRule81Str, validStr := customKeyRule81.(map[string]interface{})
    28  		if !validStr {
    29  			return nil, fmt.Errorf("customKeyRule81 must be a string")
    30  		}
    31  		return CustomKeyRule81Schema(customKeyRule81Str), nil
    32  	}
    33  	return nil, nil
    34  }
    35  
    36  type Resources struct {
    37  	Requests Requests `json:"requests"`
    38  	Limits   Limits   `json:"limits"`
    39  }
    40  type Requests struct {
    41  	CPU    string `json:"cpu"`
    42  	Memory string `json:"memory"`
    43  }
    44  
    45  type Limits struct {
    46  	CPU    string `json:"cpu"`
    47  	Memory string `json:"memory"`
    48  }
    49  
    50  func (s CustomKeyRule81Schema) Validate(ctx jsonschema.ValidationContext, dataValue interface{}) error {
    51  	b, _ := json.Marshal(dataValue)
    52  	var resources Resources
    53  	err := json.Unmarshal(b, &resources)
    54  	if err != nil {
    55  		// We expect a certain format, if this fails that means the format is wrong and we can ignore this validation and move on
    56  		return nil
    57  	}
    58  
    59  	if (resources.Requests.Memory == "" || resources.Limits.Memory == "") && (resources.Requests.Memory != resources.Limits.Memory) {
    60  		return ctx.Error("customKeyRule81", "empty value in %v", dataValue)
    61  	}
    62  
    63  	if resources.Requests.Memory != resources.Limits.Memory {
    64  		return ctx.Error("customKeyRule81", "values in data value %v do not match", dataValue)
    65  	}
    66  
    67  	return nil
    68  }