shared

package
v0.0.0-...-07a382d Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2024 License: LGPL-3.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultTransportTimeout stands for the default value for client requests to wait for a reply
	DefaultTransportTimeout = 30 * time.Second
)
View Source
const (
	// ValidActivityNamePattern represents the pattern of valid Android activity name
	ValidActivityNamePattern = `(^([A-Za-z]{1}[A-Za-z\d_]*\.){2,}|^(\.){1})[A-Za-z][A-Za-z\d_]*$`
)

Variables

View Source
var WebsocketUpgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

WebsocketUpgrader websocket.Upgrader

Functions

func AskForBool

func AskForBool(question string, defaultAnswer string) bool

AskForBool asks a question and expect a yes/no answer.

func AskForPassword

func AskForPassword(question string) string

AskForPassword asks the user to enter a password.

func BinaryEndian

func BinaryEndian() binary.ByteOrder

BinaryEndian returns machine native binary endian

func CertFingerprint

func CertFingerprint(cert *x509.Certificate) string

CertFingerprint returns the sha256 fingerprint of the given x509.Certificate

func CertFingerprintStr

func CertFingerprintStr(c string) (string, error)

CertFingerprintStr decodes the given string to x509.Certificate and then generates a sha256 fingerprint

func CompareIntArrays

func CompareIntArrays(s1, s2 []int) bool

CompareIntArrays compares two int arrays and returns true if two int arrays are equal to one another, otherwise returns false.

func CompareStringArrays

func CompareStringArrays(s1, s2 []string) bool

CompareStringArrays compares two string arrays and returns true if two string arrays are equal to one another, otherwise returns false.

func CreateBzip2Tarball

func CreateBzip2Tarball(workingDir, outputPath string, content []string) error

CreateBzip2Tarball creates a bzip2 tarball file with given files path

func CreateZip

func CreateZip(workingDir, outputPath string, content []string) error

CreateZip creates a zip file with given files path

func DirCopy

func DirCopy(source string, dest string) error

DirCopy copies a directory tree recursively

func FileCopy

func FileCopy(source string, dest string) error

FileCopy copies a file, overwriting the target if it exists.

func FileMove

func FileMove(oldPath string, newPath string) error

FileMove tries to move a file by using os.Rename, if that fails it tries to copy the file and remove the source.

func GenerateFingerprint

func GenerateFingerprint(reader io.ReadSeeker) (string, error)

GenerateFingerprint generates a fingerprint for the given reader

func GenerateFingerprintForFile

func GenerateFingerprintForFile(path string) (string, error)

GenerateFingerprintForFile generates a fingerprint (sha256) for the given file

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GenerateRandomString

func GenerateRandomString(s int) (string, error)

GenerateRandomString returns a URL-safe, base64 encoded securely generated random string. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GetByteSizeString

func GetByteSizeString(input int64, precision uint) string

GetByteSizeString returns a string with the given byte size formatted and the right unit added.

func GetFileSize

func GetFileSize(path string) (int64, error)

GetFileSize returns the size of the file at the given path

func GetFreePort

func GetFreePort() (int, error)

GetFreePort asks the kernel for a free open port that is ready to use.

func GetFreePorts

func GetFreePorts(count int) ([]int, error)

GetFreePorts asks the kernel for a number of free open ports that are ready to use.

func GetOwnerMode

func GetOwnerMode(fInfo os.FileInfo) (os.FileMode, int, int)

GetOwnerMode retrieves the file mode and owner of a given file object

func GetRemoteCertificate

func GetRemoteCertificate(address string) (*x509.Certificate, error)

GetRemoteCertificate connects to the server and returns its certificate

func GetRemoteCertificateWithTLSConfig

func GetRemoteCertificateWithTLSConfig(address string, tlsConfig *tls.Config) (*x509.Certificate, error)

GetRemoteCertificateWithTLSConfig connects to the server and returns its certificate

func GetTLS13Config

func GetTLS13Config(tlsClientCertFile, tlsClientKeyFile, tlsClientCAFile string, tlsRemoteCert *x509.Certificate) (*tls.Config, error)

GetTLS13Config returns a tls 1.3 config

func GetTLSConfig

func GetTLSConfig(tlsClientCertFile, tlsClientKeyFile, tlsClientCAFile string, tlsRemoteCert *x509.Certificate) (*tls.Config, error)

GetTLSConfig returns a tls 1.2 config

func GetTLSConfigMem

func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsClientCA string, tlsRemoteCertPEM string, insecureSkipVerify, useTLS12 bool) (*tls.Config, error)

GetTLSConfigMem returns a tls config

func Hash

func Hash(value string) (string, error)

Hash creates a hash of 192 chars from a value. A random salt of 32 bytes is used. The result is that salt plus the hashed result encoded to hexadecimal

func ImageArchToNodeArch

func ImageArchToNodeArch(Arch string) string

ImageArchToNodeArch converts the architecture of an image which is used in simplestream to node machine architecture

func InitTLS13Config

func InitTLS13Config() *tls.Config

InitTLS13Config returns a tls.Config populated with TLS1.3 as the minimum TLS version for TLS configuration

func InitTLSConfig

func InitTLSConfig() *tls.Config

InitTLSConfig returns a tls.Config populated with default encryption parameters. This is used as baseline config server certificate

func ListAvailableAddresses

func ListAvailableAddresses() ([]string, error)

ListAvailableAddresses returns a list of IPv4 network addresses the host has. It ignores the loopback device

func ListFilesInDir

func ListFilesInDir(dirPath string, recursive bool) ([]string, error)

ListFilesInDir lists all files in one specific directory recursively

func LoadFromFile

func LoadFromFile(configPath string, cfg interface{}) error

LoadFromFile loads a configuration from the given file path

func NewCancelableReader

func NewCancelableReader(ctx context.Context, other io.Reader) io.Reader

NewCancelableReader creates a new cancelable io.Reader

func NodeArchToImageArch

func NodeArchToImageArch(Arch string) string

NodeArchToImageArch converts the architecture of node machine architecture to the architecture of an image which is used in simplestream

func ParseByteSizeString

func ParseByteSizeString(input string) (int64, error)

ParseByteSizeString parses a size string in bytes (e.g. 200kB or 5GB) into the number of bytes it represents. Supports suffixes up to EB. "" == 0.

func PathExists

func PathExists(name string) bool

PathExists returns true if param path exists

func ProxyFromConfig

func ProxyFromConfig(httpsProxy string, httpProxy string, noProxy string) func(req *http.Request) (*url.URL, error)

ProxyFromConfig configures the proxy from the given values. If all values are empty a call is equals to ProxyFromEnvironment()

func ProxyFromEnvironment

func ProxyFromEnvironment(req *http.Request) (*url.URL, error)

ProxyFromEnvironment This is basically the same as golang's ProxyFromEnvironment, except it doesn't fall back to http_proxy when https_proxy isn't around, which is incorrect behavior. It still respects HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.

func RFC3493Dialer

func RFC3493Dialer(network, address string) (net.Conn, error)

RFC3493Dialer dialer

func RandomCryptoString

func RandomCryptoString() (string, error)

RandomCryptoString returns a random base64 encoded string from crypto/rand.

func ReaderToChannel

func ReaderToChannel(r io.Reader, bufferSize int) <-chan []byte

ReaderToChannel reads from websocket and sends to a channel

func RunningAsSnap

func RunningAsSnap() bool

RunningAsSnap detects if the ams service runs as a snap

func SetSize

func SetSize(fd int, width int, height int) (err error)

SetSize sets the size of the PTY connected with the given file descriptor

func StringInSlice

func StringInSlice(key string, list []string) bool

StringInSlice returns true if the searched string key is into slice

func StripUserPasswordFromURL

func StripUserPasswordFromURL(value string) string

StripUserPasswordFromURL removes user/password from the given URL

func ValidateHash

func ValidateHash(hashed, value string) error

ValidateHash decodes hexadecimal hashed, extracts the salt from the first 32 bytes and hashes the value param using that salt. The result of that hash function should match the rest of the decoded secret buffer. Otherwise the validation fails

func ValueOrDefault

func ValueOrDefault(value string, defaultValue string) string

ValueOrDefault returns the value if it has a size greater than zero or defaultValue otherwise

func VarPath

func VarPath(path ...string) string

VarPath returns the provided path elements joined by a slash and appended to the end of $SNAP_COMMON, which defaults to /var/lib/ams.

func WebsocketConsoleMirror

func WebsocketConsoleMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser) (chan bool, chan bool)

WebsocketConsoleMirror console mirror

func WebsocketMirror

func WebsocketMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, Reader WebSocketMirrorReader, Writer WebSocketMirrorWriter) (chan bool, chan bool)

WebsocketMirror allows mirroring a reader to a websocket and taking the result and writing it to a writer. This function allows for multiple mirrorings and correctly negotiates stream endings. However, it means any websocket.Conns passed to it are live when it returns, and must be closed explicitly.

func WebsocketProxy

func WebsocketProxy(source *websocket.Conn, target *websocket.Conn) chan bool

WebsocketProxy proxies a websocket connection

func WebsocketRecvStream

func WebsocketRecvStream(w io.Writer, conn *websocket.Conn) chan bool

WebsocketRecvStream manages the recv stream of the socket

func WebsocketSendStream

func WebsocketSendStream(conn *websocket.Conn, r io.Reader, bufferSize int) chan bool

WebsocketSendStream manages the send stream of the websocket

func WriteFileAtomic

func WriteFileAtomic(targetPath string, content []byte, mode os.FileMode) error

WriteFileAtomic writes the given content to the target path in an atomic way

Types

type AtomicFile

type AtomicFile struct {
	*os.File
	// contains filtered or unexported fields
}

AtomicFile allows operation on a file to happen atomicly. Changes must be committed in the end before the final file will appear at its target location

func NewAtomicFile

func NewAtomicFile(targetPath string, mode os.FileMode) (*AtomicFile, error)

NewAtomicFile creates a new AtomicFile with the given target path and mode

func (*AtomicFile) Cancel

func (af *AtomicFile) Cancel() error

Cancel all changes made. Is a no-op when Commit was already called

func (*AtomicFile) Commit

func (af *AtomicFile) Commit() error

Commit commits changes made to the file and moves the temporary file to its final location

type BufferedReader

type BufferedReader struct {
	Reader io.Reader
	Size   chan float64
}

BufferedReader represents a reader with buf size

func (*BufferedReader) Read

func (r *BufferedReader) Read(p []byte) (int, error)

BufferedReader implements io.Reader interface

type Locker

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

Locker represents a locker which acquires the lock only if it is not held by another goroutine at the time of invocation.

func NewLocker

func NewLocker() *Locker

NewLocker returns a new Locker which can be used by a goroutine to hold the internal lock and perform task which can not be invoked by other goroutine

func (*Locker) TryLock

func (l *Locker) TryLock() bool

TryLock attempts to acquire the lock immediately, return true if locking succeeds otherwise return false.

func (*Locker) UnLock

func (l *Locker) UnLock()

UnLock attempts to release the lock immediately.

type RevertFunc

type RevertFunc func(ctx context.Context) error

RevertFunc describes a function used to revert an operation

type Reverter

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

Reverter provides functionality to automatically revert a set of executed operations. It can be used this way:

r := shared.NewReverter() defer r.Finish()

doOperation()

r.Add(func(ctx context.Context) error {
  revertOperation()
  return nil
})

if err := doOtherOperation(); err != nil {
  return err
}

r.Defuse()

func NewReverter

func NewReverter() *Reverter

NewReverter constructs a new reverter.

func (*Reverter) Add

func (r *Reverter) Add(f ...RevertFunc)

Add adds a new revert function to the reverter which will be called when Finish() is called unless the reverter gets defused.

func (*Reverter) Defuse

func (r *Reverter) Defuse()

Defuse defuses the reverter. If defused none of the added revert functions will be called when Finish() is invoked.

func (*Reverter) Finish

func (r *Reverter) Finish()

Finish invokes all added revert functions if the reverter was not defused.

type WebSocketMirrorReader

type WebSocketMirrorReader func(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool)

WebSocketMirrorReader mirror reader

type WebSocketMirrorWriter

type WebSocketMirrorWriter func(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool)

WebSocketMirrorWriter mirror writer

Directories

Path Synopsis
* This file is part of AMS SDK * Copyright 2021 Canonical Ltd.
* This file is part of AMS SDK * Copyright 2021 Canonical Ltd.
rest
api

Jump to

Keyboard shortcuts

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