Documentation

Index

Constants

View Source
const (
	Day      = 24 * time.Hour
	Week     = 7 * Day
	Month    = 30 * Day
	Year     = 12 * Month
	LongTime = 37 * Year
)

Seconds-based time units

View Source
const (
	// DefaultVolumeLabel is the default label of a volume created with mkfs
	DefaultVolumeLabel = "default"

	// VolumeDelimiter is the reserved character used as delimiter between
	// volume name and uuid/label
	VolumeDelimiter = ":"
)
View Source
const OpsReleaseURL = "https://storage.googleapis.com/cli/%v/ops"

OpsReleaseURL gives URL to download latest ops binary

View Source
const PackageBaseURL string = "https://storage.googleapis.com/packagehub"

PackageBaseURL gives URL for downloading of packages

View Source
const PackageManifestFileName string = "manifest.json"

PackageManifestFileName is manifest file path

View Source
const PackageManifestURL string = "https://storage.googleapis.com/packagehub/manifest.json"

PackageManifestURL stores info about all packages

View Source
const PackageSysRootFolderName = "sysroot"

PackageSysRootFolderName is the name of package root folder

Variables

View Source
var (
	// ErrVolumeNotFound is error returned when a volume with a given id does not exist
	ErrVolumeNotFound = func(id string) error { return errors.Errorf("volume with UUID %s not found", id) }
)
View Source
var LatestReleaseVersion = getLatestRelVersion()

LatestReleaseVersion give latest stable release for nanos

View Source
var LocalImageDir = path.Join(GetOpsHome(), "images")

LocalImageDir is the directory where ops save images

View Source
var LocalReleaseVersion = getLocalRelVersion()

LocalReleaseVersion is version latest release downloaded in ops home

View Source
var (
	// LocalVolumeDir is the default local volume directory
	LocalVolumeDir = path.Join(GetOpsHome(), "volumes")
)
View Source
var NightlyLocalFolder = nightlyLocalFolder()

NightlyLocalFolder is directory path where nightly builds are stored

View Source
var NightlyReleaseURL = nightlyReleaseURL()

NightlyReleaseURL give URL for nightly build

View Source
var PackagesCache = getPackageCache()

PackagesCache where all packages are stored

View Source
var (
	// TTLDefault is the default ttl value used to create DNS records
	TTLDefault = 300
)
View Source
var Version string

Version for ops

Functions

func Apply

func Apply(update io.Reader, opts Options) error

Apply performs an update of the current executable (or opts.TargetFile, if set) with the contents of the given io.Reader.

Apply performs the following actions to ensure a safe cross-platform update:

1. If configured, applies the contents of the update io.Reader as a binary patch.

2. If configured, computes the checksum of the new executable and verifies it matches.

3. If configured, verifies the signature with a public key.

4. Creates a new file, /path/to/.target.new with the TargetMode with the contents of the updated file

5. Renames /path/to/target to /path/to/.target.old

6. Renames /path/to/.target.new to /path/to/target

7. If the final rename is successful, deletes /path/to/.target.old, returns no error. On Windows, the removal of /path/to/target.old always fails, so instead Apply hides the old file instead.

8. If the final rename fails, attempts to roll back by renaming /path/to/.target.old back to /path/to/target.

func BuildImage

func BuildImage(c types.Config) error

BuildImage builds a unikernel image for user supplied ELF binary.

func BuildImageFromPackage

func BuildImageFromPackage(packagepath string, c types.Config) error

BuildImageFromPackage builds nanos image using a package

func BuildManifest

func BuildManifest(c *types.Config) (*fs.Manifest, error)

BuildManifest builds manifest using config

func BuildPackageManifest

func BuildPackageManifest(packagepath string, c *types.Config) (*fs.Manifest, error)

BuildPackageManifest builds manifest using package

func Bytes2Human

func Bytes2Human(b int64) string

Bytes2Human parses bytes to other byte units as MegaByte and Gigabyte

func CheckNanosVersionExists

func CheckNanosVersionExists(version string) (bool, error)

CheckNanosVersionExists verifies whether version exists in filesystem

func CreateArchive

func CreateArchive(archive string, files []string) error

CreateArchive compress files into an archive

func CreateDNSRecord

func CreateDNSRecord(config *types.Config, aRecordIP string, dnsService DNSService) error

CreateDNSRecord does the necessary operations to create a DNS record without issues in an cloud provider

func CustomRelTime

func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string

CustomRelTime formats a time into a relative string.

It takes two times two labels and a table of relative time formats. In addition to the generic time delta string (e.g. 5 minutes), the labels are used applied so that the label corresponding to the smaller time is applied.

func DoUpdate

func DoUpdate(url string) error

DoUpdate updates file using provided URL

func DownloadCommonFiles

func DownloadCommonFiles() error

DownloadCommonFiles dowloads common tarball files and extract them to common directory

func DownloadFile

func DownloadFile(filepath string, url string, timeout int, showProgress bool) error

DownloadFile downloads file using URL

func DownloadFileWithProgress

func DownloadFileWithProgress(filepath string, url string, timeout int) error

DownloadFileWithProgress downloads file using URL displaying progress counter

func DownloadNightlyImages

func DownloadNightlyImages(c *types.Config) error

DownloadNightlyImages downloads nightly build for nanos

func DownloadPackage

func DownloadPackage(name string, config *types.Config) (string, error)

DownloadPackage downloads package by name

func DownloadReleaseImages

func DownloadReleaseImages(version string) error

DownloadReleaseImages downloads nanos for particular release version

func ErrInstanceNotFound

func ErrInstanceNotFound(name string) error

ErrInstanceNotFound creates new error stating instance with given name cannot be found

func ExtractPackage

func ExtractPackage(archive, dest string, config *types.Config)

ExtractPackage extracts package in ops home. This function is currently over-loaded.

func GenerateImageName

func GenerateImageName(program string) string

GenerateImageName generate image name

func GetElfFileInfo

func GetElfFileInfo(path string) (*elf.File, error)

GetElfFileInfo returns an object with elf information of the path program

func GetLocalPackageList

func GetLocalPackageList() (*map[string]Package, error)

GetLocalPackageList provides list of local packages

func GetOpsHome

func GetOpsHome() string

GetOpsHome get ops directory path We store all ops related info, packages, images in this directory

func GetPackageList

func GetPackageList(config *types.Config) (*map[string]Package, error)

GetPackageList provides list of packages

func GetPackageManifestFile

func GetPackageManifestFile() string

GetPackageManifestFile give path for package manifest file

func GetUefiBoot

func GetUefiBoot(version string) string

GetUefiBoot retrieves UEFI bootloader file path, if found

func HasDebuggingSymbols

func HasDebuggingSymbols(efd *elf.File) bool

HasDebuggingSymbols checks whether elf file has debugging symbols

func HomeDir

func HomeDir() (string, error)

HomeDir returns the home directory for the executing user. This uses an OS-specific method for discovering the home directory. An error is returned if a home directory cannot be detected.

func IsDynamicLinked

func IsDynamicLinked(efd *elf.File) bool

IsDynamicLinked checks whether elf file was linked dynamically

func IsInstanceNotFoundError

func IsInstanceNotFoundError(err error) bool

IsInstanceNotFoundError checks if given error is an ErrInstanceNotFound

func LocalTimeStamp

func LocalTimeStamp() (string, error)

LocalTimeStamp gives local timestamp from download nightly build

func NewConfig

func NewConfig() *types.Config

NewConfig construct instance of Config with default values

func PackageManifestChanged

func PackageManifestChanged(fino os.FileInfo, remoteURL string) bool

PackageManifestChanged verifies if package manifest changed

func PrintVolumesList

func PrintVolumesList(volumes *[]NanosVolume)

PrintVolumesList writes into console a table with volumes details

func RelTime

func RelTime(a, b time.Time, albl, blbl string) string

RelTime formats a time into a relative string.

It takes two times and two labels. In addition to the generic time delta string (e.g. 5 minutes), the labels are used applied so that the label corresponding to the smaller time is applied.

RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"

func RemoteTimeStamp

func RemoteTimeStamp() (string, error)

RemoteTimeStamp gives latest nightly build timestamp

func RollbackError

func RollbackError(err error) error

RollbackError takes an error value returned by Apply and returns the error, if any, that occurred when attempting to roll back from a failed update. Applications should always call this function on any non-nil errors returned by Apply.

If no rollback was needed or if the rollback was successful, RollbackError returns nil, otherwise it returns the error encountered when trying to roll back.

func SliceAtoi

func SliceAtoi(sa []string) ([]int, error)

SliceAtoi converts slice of strings to a slice of integers

func Time2Human

func Time2Human(then time.Time) string

Time2Human formats a time into a relative string. Time(someT) -> "3 weeks ago"

func UpdateLocalRelease

func UpdateLocalRelease(version string) error

UpdateLocalRelease updates nanos version used on ops operations

func ValidateELF

func ValidateELF(executablePath string)

ValidateELF validates ELF executable format given the file path

Types

type CloudImage

type CloudImage struct {
	ID      string
	Name    string
	Status  string
	Size    int64
	Path    string
	Created time.Time
}

CloudImage abstracts images for various cloud providers

type CloudInstance

type CloudInstance struct {
	ID         string
	Name       string
	Status     string
	Created    string // TODO: prob. should be datetime w/helpers for human formatting
	PrivateIps []string
	PublicIps  []string
	Ports      []string
	Image      string
}

CloudInstance represents the instance that widely use in different Cloud Providers.

type Context

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

Context captures required info for provider operation

func NewContext

func NewContext(c *types.Config) *Context

NewContext Create a new context for the given provider valid providers are "gcp", "aws" and "onprem"

func (Context) Config

func (c Context) Config() *types.Config

Config returns context configuration

func (Context) Logger

func (c Context) Logger() *log.Logger

Logger returns logger

type DNSRecord

type DNSRecord struct {
	Name string
	IP   string
	Type string
	TTL  int
}

DNSRecord is ops representation of a dns record

type DNSService

type DNSService interface {
	FindOrCreateZoneIDByName(config *types.Config, name string) (string, error)
	DeleteZoneRecordIfExists(config *types.Config, zoneID string, recordName string) error
	CreateZoneRecord(config *types.Config, zoneID string, record *DNSRecord) error
}

DNSService is an interface for DNS related operations

type JSONStore

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

JSONStore implements volumeStore TODO probably use a more established KV-store

func (*JSONStore) Delete

func (s *JSONStore) Delete(id string) (NanosVolume, error)

Delete deletes volume of a given UUID

func (*JSONStore) Get

func (s *JSONStore) Get(id string) (NanosVolume, error)

Get gets volume data of a given UUID

func (*JSONStore) GetAll

func (s *JSONStore) GetAll() ([]NanosVolume, error)

GetAll gets all volume data

func (*JSONStore) Insert

func (s *JSONStore) Insert(vol NanosVolume) error

Insert inserts volume data

func (*JSONStore) Update

func (s *JSONStore) Update(v NanosVolume) error

Update updates a given volume

type NanosVolume

type NanosVolume struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Label      string `json:"label"`
	Data       string `json:"data"`
	Size       string `json:"size"`
	Path       string `json:"path"`
	AttachedTo string `json:"attached_to"`
	CreatedAt  string `json:"created_at"`
	Status     string `json:"status"`
}

NanosVolume information for nanos-managed volume

func CreateLocalVolume

func CreateLocalVolume(config *types.Config, name, data, size, provider string) (NanosVolume, error)

CreateLocalVolume creates volume on ops directory creates a volume named <name>:<uuid> where <uuid> is generated on creation also creates a symlink to volume label at <name> TODO investigate symlinked volume interaction with image

func (NanosVolume) MatchedByQueries

func (v NanosVolume) MatchedByQueries(query map[string]string) bool

MatchedByQueries returns true if this volume matched one or more given query.

type Options

type Options struct {
	// TargetPath defines the path to the file to update.
	// The empty string means 'the executable file of the running program'.
	TargetPath string

	// Create TargetPath replacement with this file mode. If zero, defaults to 0755.
	TargetMode os.FileMode

	// Checksum of the new binary to verify against. If nil, no checksum or signature verification is done.
	Checksum []byte

	// Public key to use for signature verification. If nil, no signature verification is done.
	PublicKey crypto.PublicKey

	// Signature to verify the updated file. If nil, no signature verification is done.
	Signature []byte

	// Use this hash function to generate the checksum. If not set, SHA256 is used.
	Hash crypto.Hash

	// Store the old executable file at this path after a successful update.
	// The empty string means the old executable file will be removed after the update.
	OldSavePath string
}

Options for binary update

func (*Options) CheckPermissions

func (o *Options) CheckPermissions() error

CheckPermissions determines whether the process has the correct permissions to perform the requested update. If the update can proceed, it returns nil, otherwise it returns the error that would occur if an update were attempted.

func (*Options) SetPublicKeyPEM

func (o *Options) SetPublicKeyPEM(pembytes []byte) error

SetPublicKeyPEM is a convenience method to set the PublicKey property used for checking a completed update's signature by parsing a Public Key formatted as PEM data.

type Package

type Package struct {
	Runtime     string `json:"runtime"`
	Version     string `json:"version"`
	Language    string `json:"language"`
	Description string `json:"description,omitempty"`
	SHA256      string `json:"sha256"`
}

Package is the definition of an OPS package.

type PackageList

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

PackageList contains a list of known packages.

type Provider

type Provider interface {
	Initialize(config *types.ProviderConfig) error

	BuildImage(ctx *Context) (string, error)
	BuildImageWithPackage(ctx *Context, pkgpath string) (string, error)
	CreateImage(ctx *Context, imagePath string) error
	ListImages(ctx *Context) error
	GetImages(ctx *Context) ([]CloudImage, error)
	DeleteImage(ctx *Context, imagename string) error
	ResizeImage(ctx *Context, imagename string, hbytes string) error
	SyncImage(config *types.Config, target Provider, imagename string) error
	CustomizeImage(ctx *Context) (string, error)

	CreateInstance(ctx *Context) error
	ListInstances(ctx *Context) error
	GetInstances(ctx *Context) ([]CloudInstance, error)
	GetInstanceByName(ctx *Context, name string) (*CloudInstance, error)
	DeleteInstance(ctx *Context, instancename string) error
	StopInstance(ctx *Context, instancename string) error
	StartInstance(ctx *Context, instancename string) error
	GetInstanceLogs(ctx *Context, instancename string) (string, error)
	PrintInstanceLogs(ctx *Context, instancename string, watch bool) error

	VolumeService
}

Provider is an interface that provider must implement

type RelTimeMagnitude

type RelTimeMagnitude struct {
	D      time.Duration
	Format string
	DivBy  time.Duration
}

A RelTimeMagnitude struct contains a relative time point at which the relative format of time will switch to a new format string. A slice of these in ascending order by their "D" field is passed to CustomRelTime to format durations.

The Format field is a string that may contain a "%s" which will be replaced with the appropriate signed label (e.g. "ago" or "from now") and a "%d" that will be replaced by the quantity.

The DivBy field is the amount of time the time difference must be divided by in order to display correctly.

e.g. if D is 2*time.Minute and you want to display "%d minutes %s" DivBy should be time.Minute so whatever the duration is will be expressed in minutes.

type Storage

type Storage interface {
	CopyToBucket(config *types.Config, source string) error
}

Storage is an interface that provider's storage must implement

type VolumeService

type VolumeService interface {
	CreateVolume(ctx *Context, name, data, size, provider string) (NanosVolume, error)
	GetAllVolumes(ctx *Context) (*[]NanosVolume, error)
	DeleteVolume(ctx *Context, name string) error
	AttachVolume(ctx *Context, image, name string) error
	DetachVolume(ctx *Context, image, name string) error
}

VolumeService is an interface for volume related operations

type WriteCounter

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

WriteCounter counts the number of bytes written to it. It implements to the io.Writer interface and we can pass this into io.TeeReader() which will report progress on each write cycle.

func NewWriteCounter

func NewWriteCounter(total int) *WriteCounter

NewWriteCounter creates new write counter

func (*WriteCounter) Finish

func (wc *WriteCounter) Finish()

Finish progress bar

func (*WriteCounter) Start

func (wc *WriteCounter) Start()

Start progress bar

func (*WriteCounter) Write

func (wc *WriteCounter) Write(p []byte) (int, error)