...

Source file src/edge-infra.dev/pkg/sds/emergencyaccess/rules/storage/file/data.go

Documentation: edge-infra.dev/pkg/sds/emergencyaccess/rules/storage/file

     1  package file
     2  
     3  // Contract: Be a service layer for data storage and retrieval
     4  // see validation.go for details on json.
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"io/fs"
    10  	"os"
    11  	"path"
    12  	"strings"
    13  
    14  	rulesengine "edge-infra.dev/pkg/sds/emergencyaccess/rules"
    15  
    16  	"github.com/go-logr/logr"
    17  )
    18  
    19  const (
    20  	defaultRolesName = "default"
    21  )
    22  
    23  type Dataset struct {
    24  	rootDir       string
    25  	log           logr.Logger
    26  	bannerRoleMap map[string]map[string][]string
    27  	rulesengine.Dataset
    28  }
    29  
    30  // New generates a new dataset struct by loading all json files under the input directory and stores it as a map in memory.
    31  func New(log logr.Logger, dir string) (Dataset, error) {
    32  	ds := Dataset{
    33  		rootDir:       dir,
    34  		log:           log,
    35  		bannerRoleMap: map[string]map[string][]string{},
    36  	}
    37  	// loadfiles checks if rootdir is correct and no duplicate bannerids exist
    38  	return ds, ds.loadFiles()
    39  }
    40  
    41  func (ds *Dataset) loadFiles() error {
    42  	dirEntries, err := os.ReadDir(ds.rootDir)
    43  	if err != nil {
    44  		return err
    45  	}
    46  	for _, dirEntry := range dirEntries {
    47  		var vals jsonData
    48  		if dirEntry.IsDir() {
    49  			continue
    50  		}
    51  		if !strings.HasSuffix(dirEntry.Name(), ".json") {
    52  			continue
    53  		}
    54  		err := ds.parseJSONFile(dirEntry, &vals)
    55  		if err != nil {
    56  			ds.log.Error(err, "error when parsing file", "file", dirEntry.Name())
    57  			continue
    58  		}
    59  
    60  		if _, exists := ds.bannerRoleMap[vals.BannerID]; exists {
    61  			// continuing with load here would result in unpredictable behaviour depending on what order the file are loaded in
    62  			return fmt.Errorf("cannot overwrite unique id %s", vals.BannerID)
    63  		}
    64  		ds.bannerRoleMap[vals.BannerID] = vals.Roles
    65  	}
    66  	return nil
    67  }
    68  
    69  func (ds Dataset) parseJSONFile(dirEntry fs.DirEntry, vals *jsonData) error {
    70  	file, err := os.ReadFile(path.Join(ds.rootDir, dirEntry.Name()))
    71  	if err != nil {
    72  		return err
    73  	}
    74  	return json.Unmarshal(file, vals)
    75  }
    76  

View as plain text