Skip to content
Snippets Groups Projects
utils.go 1.52 KiB
Newer Older
  • Learn to ignore specific revisions
  • package store
    
    import (
    
    	"code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors"
    
    	"github.com/google/uuid"
    	log "github.com/sirupsen/logrus"
    )
    
    
    const (
    	pathToStores string = "stores"
    )
    
    
    // FromString is a helper to check if a provided string as a valid UUID or a name.
    func FromString(id string) (uuid.UUID, error) {
    	idAsUUID, err := uuid.Parse(id)
    
    	// id is no UUID therefore it could be a device name.
    	// The name will be returned within the error.
    	if err != nil {
    		log.WithFields(log.Fields{
    			"identifier": id,
    		}).Debug(err)
    		return uuid.Nil, &errors.ErrInvalidUUID{DeviceName: id}
    	}
    
    	return idAsUUID, nil
    }
    
    
    func ensureFilesystemStorePathExists(storeFileName string) error {
    	completeStorePath := filepath.Join(pathToStores, storeFileName)
    	if _, err := os.Stat(completeStorePath); os.IsNotExist(err) {
    		err := ensureFileSystemStoreExists(completeStorePath)
    		if err != nil {
    			return err
    		}
    	}
    
    	return nil
    }
    
    func ensureFileSystemStoreExists(pathToStore string) error {
    	err := ensureDirExists(pathToStore)
    	if err != nil {
    		return err
    	}
    
    	emptyArray := []byte("[]")
    	err = os.WriteFile(pathToStore, emptyArray, 0600)
    	if err != nil {
    		return err
    	}
    
    	return nil
    }
    
    func ensureDirExists(fileName string) error {
    	dirName := filepath.Dir(fileName)
    	if _, serr := os.Stat(dirName); serr != nil {
    		merr := os.MkdirAll(dirName, os.ModePerm)
    		if merr != nil {
    			return merr
    		}
    	}
    
    	return nil
    }
    
    func getCompletePathToFileStore(storeName string) string {
    
    	return filepath.Join(pathToStores, storeName)