utils

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 26, 2021 License: Apache-2.0 Imports: 72 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTimestamp

func AddTimestamp(inp string) string

AddTimestamp wraps string with time

func CompareProtoMessages

func CompareProtoMessages(m1, m2 proto.Message) (bool, error)

CompareProtoMessages returns true if messages are equal

func CopyFile

func CopyFile(src string, dst string) (err error)

CopyFile copy file from src to dst with same permission

func CopyFileNotExists

func CopyFileNotExists(src string, dst string) (err error)

CopyFileNotExists copy file from src to dst with same permission if not exists

func CopyFolder

func CopyFolder(source, destination string) error

CopyFolder from source to destination

func CreateAndRunContainer

func CreateAndRunContainer(containerName string, imageName string, portMap map[string]string, volumeMap map[string]string, command []string, envs []string) error

CreateAndRunContainer run container with defined name from image with port and volume mapping and defined command

func CreateCipherCtx

func CreateCipherCtx(cmnCryptoCfg *CommonCryptoConfig) (*config.CipherContext, error)

CreateCipherCtx for edge dev config.

func CreateDockerNetwork

func CreateDockerNetwork(name string) error

CreateDockerNetwork create network for docker`s containers

func CreateImage

func CreateImage(dir, tag, platform string) error

CreateImage create new image from directory with tag If Dockerfile is inside the directory will use it otherwise will create image from scratch

func CreateTarGz

func CreateTarGz(dstFile string, paths []FileToSave) error

CreateTarGz generates tar.gz file in dstFile by putting files and directories described in paths

func CryptoConfigWrapper

func CryptoConfigWrapper(encBlock *config.EncryptionBlock, cmnCryptoCfg *CommonCryptoConfig, cipherCtx *config.CipherContext) (*config.CipherBlock, error)

CryptoConfigWrapper create cipherCtx and encrypt secrets for all the objects.

func CurrentDirConfigPath

func CurrentDirConfigPath() (string, error)

CurrentDirConfigPath returns path to eden-config.yml in current folder

func DefaultConfigPath

func DefaultConfigPath() (string, error)

DefaultConfigPath returns path to default config

func DefaultEdenDir

func DefaultEdenDir() (string, error)

DefaultEdenDir returns path to default directory

func DelEleInSlice

func DelEleInSlice(arr interface{}, index int)

DelEleInSlice delete an element from slice by index

  • arr: the reference of slice
  • index: the index of element will be deleted

func DelEleInSliceByFunction

func DelEleInSliceByFunction(arr interface{}, f func(interface{}) bool)

DelEleInSliceByFunction delete an element from slice by function

  • arr: the reference of slice
  • f: delete if it returns true on element of slice

func DownloadEveInstaller

func DownloadEveInstaller(eve EVEDescription, outputFile string) (err error)

DownloadEveInstaller pulls EVE installer image from docker

func DownloadEveLive

func DownloadEveLive(eve EVEDescription, uefi UEFIDescription, outputFile string) (err error)

DownloadEveLive pulls EVE live image from docker

func DownloadEveNetBoot

func DownloadEveNetBoot(eve EVEDescription, outputDir string) (err error)

DownloadEveNetBoot pulls EVE image from docker and prepares files for net boot

func DownloadEveRootFS

func DownloadEveRootFS(eve EVEDescription, outputDir string) (filePath string, err error)

DownloadEveRootFS pulls EVE rootfs image from docker

func DownloadFile

func DownloadFile(filepath string, url string) error

DownloadFile download a url to a local file.

func ExtractFilesFromDocker

func ExtractFilesFromDocker(u io.ReadCloser, directory string, prefixDirectory string) error

ExtractFilesFromDocker extract all files from docker layer into directory if prefixDirectory is not empty, remove it from path

func FileNameWithoutExtension

func FileNameWithoutExtension(fileName string) string

FileNameWithoutExtension trim file extension and path

func FindEleInSlice

func FindEleInSlice(slice []string, val string) (int, bool)

FindEleInSlice takes a slice and looks for an element in it. If found it will return it's key, otherwise it will return -1 and a bool of false.

func GenCARoot

func GenCARoot() (*x509.Certificate, *rsa.PrivateKey)

GenCARoot gen root CA

func GenServerCertElliptic

func GenServerCertElliptic(cert *x509.Certificate, key *rsa.PrivateKey, serial *big.Int, ip []net.IP, dns []string, uuid string) (*x509.Certificate, *ecdsa.PrivateKey)

GenServerCertElliptic elliptic cert

func GenerateConfigFile

func GenerateConfigFile(filePath string) error

GenerateConfigFile is a function to generate default yml

func GenerateConfigFileDiff

func GenerateConfigFileDiff(filePath string, context *Context) error

GenerateConfigFileDiff is a function to generate diff yml for new context

func GenerateConfigFileFromViper

func GenerateConfigFileFromViper() error

GenerateConfigFileFromViper is a function to generate yml from viper config

func GeneratePassword

func GeneratePassword(length int) string

GeneratePassword returns string with defined length and random characters

func GenerateSSHKeyPair

func GenerateSSHKeyPair(privateKeyFile string, publicKeyFile string) error

GenerateSSHKeyPair generates keypair for ssh

func GenerateStateFile

func GenerateStateFile(dirToSave string, state StateObject) error

GenerateStateFile generates state in file

func GetConfig

func GetConfig(name string) string

GetConfig return path to config file

func GetDesktopName

func GetDesktopName(address string, password string) (string, error)

GetDesktopName return DesktopName from VNC server address with password (if not empty)

func GetDockerNetworks

func GetDockerNetworks() ([]*net.IPNet, error)

GetDockerNetworks returns gateways IPs of networks in docker

func GetFileFollowLinks(filePath string) (string, error)

GetFileFollowLinks resolve file by walking through symlinks

func GetFileSize

func GetFileSize(filePath string) int64

GetFileSize returns file size

func GetFileSizeURL

func GetFileSizeURL(url string) int64

GetFileSizeURL returns file size for url

func GetIPForDockerAccess

func GetIPForDockerAccess() (ip string, err error)

GetIPForDockerAccess is service function to obtain IP for adam access The function is filter out docker bridge

func GetParams

func GetParams(line, regEx string) (paramsMap map[string]string)

GetParams parse line with regexp into map

func GetSubnetIPs

func GetSubnetIPs(subnet string) (result []net.IP)

GetSubnetIPs return all IPs from subnet

func HasImage

func HasImage(image string) (bool, error)

HasImage see if the image is local

func IsInputFromPipe

func IsInputFromPipe() bool

IsInputFromPipe returns true if the command is running from pipe

func LoadConfigFile

func LoadConfigFile(config string) (loaded bool, err error)

LoadConfigFile load config from file with viper

func LoadConfigFileContext

func LoadConfigFileContext(config string) (loaded bool, err error)

LoadConfigFileContext load config from context file with viper

func LoadRegistry

func LoadRegistry(image, remote string) (string, error)

LoadRegistry push image into registry

func LookUp

func LookUp(i interface{}, path string) (value reflect.Value, err error)

LookUp try to resolve values from interface by path

func LookupWithCallback

func LookupWithCallback(inpValue interface{}, inpPath string, callback checkPart)

LookupWithCallback travels through inpValue by inpPath and apply callback you can pass [] without index for iterate over loops

func ParseCertificate

func ParseCertificate(certFile string) (*x509.Certificate, error)

ParseCertificate from file

func ParseFirstCertFromBlock

func ParseFirstCertFromBlock(b []byte) (*x509.Certificate, error)

ParseFirstCertFromBlock process provided certificate date

func ParsePrivateKey

func ParsePrivateKey(keyFile string) (*rsa.PrivateKey, error)

ParsePrivateKey from file

func PullImage

func PullImage(image string) error

PullImage from docker

func PushImage

func PushImage(image, remote string) error

PushImage from docker while optionally changing to a different remote registry

func RemoveGeneratedVolumeOfContainer

func RemoveGeneratedVolumeOfContainer(containerName string) error

RemoveGeneratedVolumeOfContainer remove volumes created by eden

func RenderTemplate

func RenderTemplate(configFile string, tmpl string) (string, error)

RenderTemplate render Go template with Eden-related fuctions

func RepeatableAttempt

func RepeatableAttempt(client *http.Client, req *http.Request) (response *http.Response, err error)

RepeatableAttempt do request several times waiting for nil error and expected status code

func RequestHTTPRepeatWithTimeout

func RequestHTTPRepeatWithTimeout(url string, returnEmpty bool, timeoutSeconds time.Duration) (string, error)

RequestHTTPRepeatWithTimeout make series of requests to url with timeout returnEmpty control if empty string is normal result

func RequestHTTPWithTimeout

func RequestHTTPWithTimeout(url string, timeoutSeconds time.Duration) (string, error)

RequestHTTPWithTimeout make request to url with timeout

func ResolveAbsPath

func ResolveAbsPath(curPath string) string

ResolveAbsPath use eden.root parameter to resolve path

func ResolveHomeDir

func ResolveHomeDir(filePath string) string

ResolveHomeDir resolve ~ in path

func ResolveURL

func ResolveURL(b, p string) (string, error)

ResolveURL concatenate parts of url

func RunCommandAndWait

func RunCommandAndWait(name string, args ...string) (stdout string, stderr string, err error)

RunCommandAndWait run process in foreground

func RunCommandBackground

func RunCommandBackground(name string, logOutput io.Writer, args ...string) (pid int, err error)

RunCommandBackground command run in goroutine

func RunCommandForeground

func RunCommandForeground(name string, args ...string) (err error)

RunCommandForeground command run in foreground

func RunCommandNohup

func RunCommandNohup(name string, logFile string, pidFile string, args ...string) (err error)

RunCommandNohup run process in background

func RunCommandWithLogAndWait

func RunCommandWithLogAndWait(name string, logLevel log.Level, args ...string) (err error)

RunCommandWithLogAndWait run process in foreground

func RunCommandWithSTDINAndWait

func RunCommandWithSTDINAndWait(name string, stdin string, args ...string) (stdout string, stderr string, err error)

RunCommandWithSTDINAndWait run process in foreground with stdin passed as arg

func RunDockerCommand

func RunDockerCommand(image string, command string, volumeMap map[string]string) (result string, err error)

RunDockerCommand is run wrapper for docker container

func SHA256SUM

func SHA256SUM(filePath string) string

SHA256SUM calculates sha256 of file

func SHA256SUMAll

func SHA256SUMAll(dir string) (string, error)

SHA256SUMAll calculates sha256 of directory

func SaveImage

func SaveImage(image string) (io.ReadCloser, error)

SaveImage get a reader to save an image

func SaveImageAndExtract

func SaveImageAndExtract(image, outputDir, defaultEvePrefixInTar string) error

SaveImageAndExtract from docker to outputDir only for path defaultEvePrefixInTar in docker rootfs

func SaveImageToTar

func SaveImageToTar(image, tarFile string) error

SaveImageToTar creates tar from image

func StartContainer

func StartContainer(containerName string) error

StartContainer start container with containerName

func StateContainer

func StateContainer(containerName string) (state string, err error)

StateContainer return state of container if found or "" state if not found

func StatusCommandWithPid

func StatusCommandWithPid(pidFile string) (status string, err error)

StatusCommandWithPid check if process with pid from pidFile running

func StopCommandWithPid

func StopCommandWithPid(pidFile string) (err error)

StopCommandWithPid sends kill to pid from pidFile

func StopContainer

func StopContainer(containerName string, remove bool) error

StopContainer stop container and remove if remove is true

func TagImage

func TagImage(oldTag, newTag string) error

TagImage set new tag to image

func TouchFile

func TouchFile(src string) (err error)

TouchFile create empty file

func UnpackTarGz

func UnpackTarGz(srcFile string, paths []FileToSave) error

UnpackTarGz observes tar.gz file in srcFile and extracts files and directories described in paths

func Untar

func Untar(srcFile string, destination string) error

Untar extracts files from srcFile tar into destination

func UploadFile

func UploadFile(client *http.Client, url, filePath, prefix string) (result *http.Response, err error)

UploadFile send file in form

func WriteToFiles

func WriteToFiles(crt *x509.Certificate, key interface{}, certFile string, keyFile string) (err error)

WriteToFiles write cert and key

Types

type CommonCryptoConfig

type CommonCryptoConfig struct {
	ControllerEncCertHash []byte
	DevCertHash           []byte
	SymmetricKey          []byte
}

CommonCryptoConfig stores information about certificates

func GetCommonCryptoConfig

func GetCommonCryptoConfig(devCert []byte, controllerCert, controllerKey string) (*CommonCryptoConfig, error)

GetCommonCryptoConfig calculate common crypto config and keep it in a structure. Common config are: 1. Calculate sha of controller cert. 2. Calculate sha of device cert. 3. Calculate symmetric key.

type ConfigVars

type ConfigVars struct {
	AdamIP            string
	AdamPort          string
	AdamDomain        string
	AdamDir           string
	AdamCA            string
	AdamRemote        bool
	AdamCaching       bool
	AdamCachingRedis  bool
	AdamCachingPrefix string
	AdamRemoteRedis   bool
	AdamRedisURLEden  string
	AdamRedisURLAdam  string
	EveHV             string
	EveSSID           string
	EveUUID           string
	EveName           string
	EveRemote         bool
	EveRemoteAddr     string
	EveQemuPorts      map[string]string
	EveQemuConfig     string
	EveDist           string
	SSHKey            string
	EveCert           string
	EveDeviceCert     string
	EveSerial         string
	ZArch             string
	DevModel          string
	DevModelFIle      string
	EdenBinDir        string
	EdenProg          string
	TestProg          string
	TestScenario      string
	EServerImageDist  string
	EServerPort       string
	EServerIP         string
	RegistryIP        string
	RegistryPort      string
	LogLevel          string
	AdamLogLevel      string
}

ConfigVars struct with parameters from config file

func InitVars

func InitVars() (*ConfigVars, error)

InitVars loads vars from viper

type Context

type Context struct {
	Current   string `yaml:"current"`
	Directory string `yaml:"directory"`
}

Context for use with multiple config files

func ContextInit

func ContextInit() (*Context, error)

ContextInit generates and returns default context

func ContextLoad

func ContextLoad() (*Context, error)

ContextLoad read file with context data

func (*Context) GetCurrentConfig

func (ctx *Context) GetCurrentConfig() string

GetCurrentConfig return path to config file

func (*Context) ListContexts

func (ctx *Context) ListContexts() (contexts []string)

ListContexts show available contexts

func (*Context) Save

func (ctx *Context) Save()

Save save file with context data

func (*Context) SetContext

func (ctx *Context) SetContext(context string)

SetContext set current contexts

type EVEDescription

type EVEDescription struct {
	ConfigPath  string
	Arch        string
	HV          string
	Registry    string
	Tag         string
	Format      string
	ImageSizeMB int
}

EVEDescription provides information about EVE to download

func (EVEDescription) Image

func (desc EVEDescription) Image() (string, error)

Image extracts image tag from EVEDescription

func (EVEDescription) Version

func (desc EVEDescription) Version() (string, error)

Version extracts version from EVEDescription

type FileToSave

type FileToSave struct {
	Location    string
	Destination string
}

FileToSave provides pattern to save or load files based on Location and Destination inside fs and tar

type IFInfo

type IFInfo struct {
	Subnet        *net.IPNet
	FirstAddress  net.IP
	SecondAddress net.IP
}

IFInfo stores information about net address and subnet

func GetSubnetsNotUsed

func GetSubnetsNotUsed(count int) ([]IFInfo, error)

GetSubnetsNotUsed prepare map with subnets and ip not used by any interface of host

type QemuSettings

type QemuSettings struct {
	DTBDrive   string
	Firmware   []string
	MemoryMB   int
	CPUs       int
	USBSerials int
	USBTablets int
}

QemuSettings struct for pass into template

func (QemuSettings) GenerateQemuConfig

func (settings QemuSettings) GenerateQemuConfig() ([]byte, error)

GenerateQemuConfig provides string representation of Qemu config for QemuSettings object

type QueueWithCapacity

type QueueWithCapacity struct {
	// contains filtered or unexported fields
}

QueueWithCapacity for represent FIFO queue with defined capacity

func InitQueueWithCapacity

func InitQueueWithCapacity(capacity int) *QueueWithCapacity

InitQueueWithCapacity initialises queue

func (*QueueWithCapacity) Dequeue

func (queue *QueueWithCapacity) Dequeue() (item interface{}, err error)

Dequeue get last element from queue

func (*QueueWithCapacity) Enqueue

func (queue *QueueWithCapacity) Enqueue(item interface{}) error

Enqueue add element into queue if queue is full, it drop last element

type RegistryHTTP

type RegistryHTTP struct {
	remotes.Resolver
	// contains filtered or unexported fields
}

RegistryHTTP for http access to local registry

func NewRegistryHTTP

func NewRegistryHTTP(ctx context.Context) (context.Context, *RegistryHTTP, error)

NewRegistryHTTP creates new RegistryHTTP with plainHTTP resolver

func (*RegistryHTTP) Context

func (r *RegistryHTTP) Context() context.Context

Context wrapper

func (*RegistryHTTP) Finalize

func (r *RegistryHTTP) Finalize(_ context.Context) error

Finalize wrapper

type StateObject

type StateObject struct {
	EveConfig  string //if empty will not create/overwrite config file
	EveDir     string
	AdamDir    string
	EveUUID    string
	DeviceUUID string
	QEMUConfig string
}

StateObject is structure to save state in file

type UEFIDescription

type UEFIDescription struct {
	Registry string
	Tag      string
	Arch     string
}

UEFIDescription provides information about UEFI to download

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL