modulecmd

package
v0.4.88 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modulecmd is the module assistant: `casaos module list|plan|install|remove|status`. It is the one place a module is installed and removed; the sha256 check, the rules of what an archive may write and the reading of manifests and catalogues are the code of osmodule, and this package is what runs them against a box: it asks the box what it is (plan), puts a module on it in steps and takes it off again (install, remove).

Everything the commands touch of the world comes through an Env: the file system (a Roots), the commands they run (a Runner), the network (a Downloader), the gateway, the clock, the terminal, and the few calls that only Linux has (a Host). Production wires the real ones (Production); a test wires a temporary directory and stand-ins. The package compiles everywhere and runs for real on Linux only.

Index

Constants

View Source
const (
	ExitOK      = 0
	ExitRefused = 2 // a code, and nothing was changed
	ExitFailed  = 3 // the work began, failed at a step and was rolled back as said
)

The exit codes of the commands.

View Source
const (
	StepPackages = "packages"
	StepDownload = "download"
	StepVerify   = "verify"
	StepUnpack   = "unpack"
	StepUnits    = "units"
	StepManifest = "manifest"
	StepStart    = "start"
	StepRoute    = "route"
	StepDone     = "done"
)

The steps of an install, in order. Each is a marker in the log; a failure at one of them is rolled back.

View Source
const (
	CodeNotRoot            = "not_root"
	CodeBusy               = "busy"
	CodePlanChanged        = "plan_changed"
	CodeConfirmationNeeded = "confirmation_needed"
	CodeDeclined           = "declined"
	CodeNotInstalled       = "not_installed"
	CodeLogUnwritable      = "log_unwritable"
	CodeLockFailed         = "lock_failed"
	CodeFilesUnreadable    = "files_unreadable"
	CodePackagesFailed     = "packages_failed"
	CodeDpkgBroken         = "dpkg_broken"
	CodeHeldPackage        = osmodule.RefusedHeld
	CodeDownloadFailed     = "download_failed"
	CodeDownloadTooLarge   = "download_too_large"
	CodeChecksumMismatch   = "checksum_mismatch"
	CodeUnpackFailed       = "unpack_failed"
	CodeUnitsFailed        = "units_failed"
	CodeManifestInvalid    = "manifest_invalid"
	CodeManifestMismatch   = "manifest_mismatch"
	CodeManifestWrite      = "manifest_write_failed"
	CodeStartFailed        = "start_failed"
	CodeRouteTimeout       = "route_timeout"
	CodeInterrupted        = "interrupted"
	CodeUnitNotStopped     = "unit_not_stopped"
	CodeRemoveIncomplete   = "remove_incomplete"
	CodeTmpUnusable        = "tmp_unusable"
	CodeStateUnsafe        = "state_unsafe"
	CodeInternal           = "internal_error"
)

The codes a run is refused or failed with, besides the ones of the plan (osmodule.Check*, osmodule.Refused*) and of the unpack (osmodule.Unpack*, osmodule.FileExists).

View Source
const (
	JobIdle        = "idle"
	JobRunning     = "running"
	JobSucceeded   = "succeeded"
	JobFailed      = "failed"
	JobInterrupted = "interrupted"
	JobRefused     = "refused"
)

The states of a job.

View Source
const (
	KindInstall = "install"
	KindRemove  = "remove"
	KindUpdate  = "update"
)

The kinds of a job: what the core started, and said in the first line of the log. The words are those of the verbs of the assistant.

View Source
const (
	UndoRolledBack = "rolled_back"
	UndoIncomplete = "rollback_incomplete"
	// UndoRolledBackWithLeft is a rollback that put back everything but the files that were left as somebody else had left them: the old version is not whole, and the sentences before the RESULT line say which files.
	UndoRolledBackWithLeft = "rolled_back_with_left"
)

The words of Job.Undo: the last field of the RESULT line of a job that failed. The empty word is a failure that had nothing to undo or a verb that does not undo.

View Source
const (
	// InterruptedAfter is how long a unit that is not there is given, from the last sign of life of the job, to have said its RESULT: the unit can be gone just before the last line reached the
	// log, and it can be gone just after the core queued it and before systemd had it.
	InterruptedAfter = 30 * time.Second
	// SilentAfter is the same for systemd that does not answer: it is not known that the unit is gone, and an apt can be quiet for a long time.
	SilentAfter = 30 * time.Minute
	// TailLines is how many lines of the end of the log the state carries.
	TailLines = 20
)
View Source
const (
	StepStop      = "stop"
	StepFiles     = "files"
	StepManifest2 = "manifest"
	StepReload    = "reload"
)

The steps of a remove.

View Source
const (
	StepBackup = "backup"
	StepSwap   = "swap"
)

The steps of an update that an install does not have; the others are those of an install (packages, download, verify, unpack, units, start, route) and StepStop of a remove.

View Source
const (
	CodeBackupFailed       = "backup_failed"
	CodeSwapFailed         = "swap_failed"
	CodeRecoveryIncomplete = "recovery_incomplete"
	CodeBackupNotDropped   = "backup_not_dropped"
)

The codes of an update besides the ones of the plan (osmodule.Refused*: not_installed, up_to_date, downgrade, ...) and of an install.

View Source
const StepLeftovers = "leftovers"

StepLeftovers is the step of a remove that takes away what the new version of an update that was ended put down, when the backup of that update could not be put back and was kept: the lists on the box are the old version's, and know nothing of the files and the directories that only the new version has.

View Source
const (

	// StopWithin is how long a run needs, from the SIGTERM that asks it to stop, to be over: the command it is in is given killGrace to leave, then the rollback has rollbackTime, and the
	// command that ends the rollback is given killGrace in its turn. A unit that waits for less before it kills what is left cuts the rollback of an install.
	StopWithin = 2*killGrace + rollbackTime
)

Variables

View Source
var (
	// ErrLockHeld is the error of Lock for a lock that another process holds.
	ErrLockHeld = errors.New("the lock is held")
	// ErrUnsupported is what a host that is not Linux says.
	ErrUnsupported = errors.New("this system cannot run the module assistant")
)
View Source
var ErrLogChanged = errors.New("the log is no longer the queued line of the job")

ErrLogChanged is the error of Abandon for a log that is no longer the first line of the job: a unit started, and the log holds what it has written.

View Source
var (

	// ErrTooLarge is a download or an unpacked archive that has more bytes than allowed.
	ErrTooLarge = errors.New("more bytes than allowed")
)

Functions

func Abandon

func Abandon(env Env, name, nonce, kind string, queuedAt, at time.Time, said []string) error

Abandon makes the log of a job whose unit could not be started a whole run: the queued line (queuedAt and kind are what Queue was given), what failed, what systemd said (said, as text, behind "| " like the output of a tool) and a RESULT line that says failed, start_failed, with nothing undone because nothing was done. It does not wait for the lock. It writes only while the log is exactly the queued line of this job, or is not there: a unit that did start has replaced the log with its own lines, and they are not for the core to overwrite (ErrLogChanged).

func Dispatch

func Dispatch(args []string) (rest []string, ok bool)

Dispatch says whether a command line is the module assistant's: `casaos module ...`, with "module" as the first argument after the program and spelled exactly so. It gives what follows. Nothing else reaches the code of the assistant: a flag of the core in front of it, a different case, an abbreviation or a word that only starts with it is the core's own command line, and the core starts as it always did.

func HoldLock added in v0.4.82

func HoldLock(env Env, do func() error) error

HoldLock runs do while the lock of the assistant is held (taken as a run takes it, made when it is not there), for a change of the box that a run must see or be seen by: the start of the upgrade of the operating system puts up its flag under it, and a run looks for the flag once it has the lock. ErrLockHeld is a run that holds it, and do is not run.

func JobLogs

func JobLogs(env Env) ([]string, error)

JobLogs are the names of the modules that have a log, in the order the folder gives them. A folder that is not there has none; one that cannot be read is an error.

func LockHeld added in v0.4.82

func LockHeld(env Env) (bool, error)

LockHeld says whether a run of the assistant holds its lock, a run started by hand included, which has no unit to be seen by: the lock is tried, not waited for, and given back at once. A box on which no run ever made the file of the lock has none held, and the look does not make it.

func Main

func Main(ctx context.Context, args []string, env Env) (code int)

Main runs one command and returns its exit code (ExitOK, ExitRefused, ExitFailed).

func PlanOf

func PlanOf(ctx context.Context, env Env, name string) osmodule.PlanResult

PlanOf is the plan of installing the module called name: what the box can say of it, and nothing written.

func PlanUpdateOf added in v0.4.78

func PlanUpdateOf(ctx context.Context, env Env, name string) osmodule.PlanResult

PlanUpdateOf is the plan of updating the installed module called name to the tag of the catalogue: the same, and nothing written.

func Queue

func Queue(env Env, name, nonce, kind string, at time.Time) error

Queue replaces the log of the module called name with the first line of the job whose nonce this is, and whose kind (KindInstall or KindRemove) is said in it: the log is the job's from here on, and a unit that is started next keeps that line, replaces the rest and carries on with the same nonce. It does not wait for the lock (ErrLockHeld when a run has it).

func QueuedLine

func QueuedLine(name, nonce, kind string, at time.Time) string

QueuedLine is the first line of the log of a job that the core is about to start. It carries the nonce, so that the log is the job's from now on, and the kind of the job (KindInstall or KindRemove).

func RemoveRefusal

func RemoveRefusal(ctx context.Context, env Env, name string) string

RemoveRefusal is the code that a remove of the module called name is refused with, "" when it is not: there is nothing of the module to remove (CodeNotInstalled), or a package manager or the upgrade of the operating system is at work (CodeBusy). It reads and changes nothing.

func Run

func Run(args []string, env Env) int

Run is `casaos module ...` as the core's main runs it: args are what follows "module". It ends a run on SIGTERM, SIGINT and SIGHUP the way a failure ends it (the step it is in fails with "interrupted" and is rolled back), and a second signal ends the process at once.

func ValidKind

func ValidKind(kind string) bool

ValidKind says whether kind is the kind of a job.

Types

type CatalogueInfo

type CatalogueInfo struct {
	OK     bool   `json:"ok"`
	Error  string `json:"error,omitempty"`
	Detail string `json:"detail,omitempty"`
}

CatalogueInfo says whether the catalogue of this release was read, and if not why: "none" (there is none), "unreadable" or "invalid" with the place in Detail.

type Clock

type Clock interface {
	Now() time.Time
	Sleep(ctx context.Context, d time.Duration) error
}

A Clock is the time and the wait.

type Cmd

type Cmd struct {
	Argv    []string
	Env     []string
	Dir     string
	Stdout  io.Writer
	Timeout time.Duration
	// Finish, when set, is how long a command that is asked to stop (its context ends) is first given to finish what it is doing and leave on its own: it is sent SIGINT, and nothing else
	// until the time is up or the command has left. apt-get answers SIGINT by finishing the dpkg run it is in (SIGTERM kills apt-get, and dpkg, whose status pipe it was, dies on SIGPIPE
	// between two packages). What is still there when the time is up is stopped as for any command (SIGTERM, the grace, SIGKILL).
	Finish time.Duration
}

A Cmd is a command to run: no shell. Env is the whole environment (nil is the clean one of the install); Dir the directory it runs in ("" is the root). Stdout, when set, takes the output as it comes (and Output.Text is empty); when nil the output is kept, bounded, in Output.Text. Timeout, when set, ends the command with its context error.

type Downloader

type Downloader interface {
	Get(ctx context.Context, url string, dst io.Writer) (int64, error)
}

A Downloader fetches an address into dst and says how many bytes it wrote. An error that retrying cannot mend (a refused address, a refused redirect, too many bytes, a status that is not 200) is a *PermanentError.

func NewHTTPDownloader

func NewHTTPDownloader() Downloader

NewHTTPDownloader is the downloader of production: the archive of a release, at most osmodule.MaxArchiveBytes.

type Env

type Env struct {
	Roots  Roots
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	Getenv func(string) string
	// EUID is the user the assistant runs as; Arch the architecture as the archives name it ("amd64", "arm64"); Version the ReCasaOS release that is running.
	EUID    func() int
	Arch    string
	Version string

	Runner Runner
	// Sandbox makes the sandbox the simulation of apt runs in (osplan.Sandbox): the production one is a directory in /var/tmp.
	Sandbox  func() osplan.Sandbox
	Download Downloader
	Gateway  Gateway
	Clock    Clock
	// Terminal says whether there is someone to ask.
	Terminal func() bool
	Host     Host
	// StepHook, when set, is called at the start and at the end of every step of an install and a remove, with the step and "begin" or "done": a test uses it to stop the run at a
	// chosen point. Production leaves it nil.
	StepHook func(ctx context.Context, step, phase string)
}

An Env is the world of a run of the assistant.

func Production

func Production() Env

Production is the Env of a box: the real file system, commands, network and clock.

type Gateway

type Gateway interface {
	Answers(ctx context.Context, route string) (bool, error)
}

A Gateway says whether the gateway answers on a route.

type Host

type Host interface {
	// Lock takes the lock at path, which is not waited for: ErrLockHeld when another process has it. The lock is the process's, and is gone when the process is.
	Lock(path string) (release func(), err error)
	// FreeBytes is the room left, for a program that is not root, on the file system that holds the path (the nearest directory that exists).
	FreeBytes(path string) (int64, error)
	// DpkgLockHeld says whether another process holds a lock on any of the files; an error says it could not be told.
	DpkgLockHeld(paths []string) (bool, error)
	// NewDest is the file system an archive is unpacked onto, with prefix in front of every path.
	NewDest(prefix string) osmodule.Destination
	// IsTerminal says whether the file is a terminal.
	IsTerminal(f *os.File) bool
	// SafeDir says why a directory is not one that root may keep files in: it must be a directory and not a link, owned by the user the assistant runs as (root, since install and remove
	// refuse any other) and writable by nobody else.
	SafeDir(path string) error
}

A Host is what only the machine has: a lock that dies with its holder, the room on a file system, the question of whether a package manager holds dpkg's lock, and the file system the unpack writes to.

type Installed

type Installed struct {
	Version *string `json:"version"`
}

Installed is what the box has of a module: its version, null when the box does not know it.

type Job

type Job struct {
	Name string `json:"name"`
	// Kind is what the job is: KindInstall, KindRemove or KindUpdate, as the core said when it started the job; "" when the log does not say (a job that was not started by the core).
	Kind  string `json:"kind"`
	State string `json:"state"`
	// Step is where the job is: the step of the last STEP line (the rollback's steps are those of a remove behind "rollback_"), and for a job that failed the step of the RESULT line,
	// which is "" when it failed before its first step. "done" for a job that succeeded; "" for one that was refused or has not begun.
	Step string `json:"step"`
	// Code is the reason of a job that was refused or failed: the code of the RESULT line.
	Code string `json:"code"`
	// Undo is UndoRolledBack or UndoIncomplete for an install or an update that failed after it had changed the box, "" otherwise.
	Undo string `json:"undo"`
	// KeptPackages are the packages of the module that an install that failed left on the box, from the sentence kept_packages that comes before the RESULT line: null when it is not said
	// or not known, an empty list when there are none.
	KeptPackages []string `json:"kept_packages"`
	// StartedAt and EndedAt are the times of the first marker and of the RESULT line, RFC 3339 in UTC; "" when there is none.
	StartedAt string `json:"started_at"`
	EndedAt   string `json:"ended_at"`
	// LogTail is the last TailLines lines of the log that are not marker lines, as text: printable ASCII, a URL reduced to its host, cut.
	LogTail []string `json:"log_tail"`
}

A Job is how the job of a module is going, or how it went.

func ReadJob

func ReadJob(env Env, name string, unit UnitSight, now time.Time) (Job, error)

ReadJob says how the job of the module called name is going, from its log and the state of its unit. The unit is looked at BEFORE the log is read (a unit that is gone has written everything it wrote), and now is the time of the core's clock. A module that has no log has no job. The log is a regular file that is not reached through a link, and the first maxLine bytes of a line are all that is held of it.

func ReduceLines

func ReduceLines(name, nonce string, lines []string, unit UnitSight, now, logWritten time.Time) Job

ReduceLines is the job that the lines of a log, all of them whole, are the word of.

type ListModule

type ListModule struct {
	Name        string     `json:"name"`
	Title       string     `json:"title"`
	Description string     `json:"description"`
	Tier        string     `json:"tier"`
	Tag         string     `json:"tag"`
	Catalogue   bool       `json:"catalogue"`
	Installed   *Installed `json:"installed"`
	System      SystemInfo `json:"system"`
	Broken      string     `json:"broken,omitempty"`
	// Update is there for a module that is installed, that the catalogue has and whose installed version can be read; Available says the catalogue's tag is strictly later.
	Update *UpdateInfo `json:"update,omitempty"`
}

A ListModule is a module of the catalogue or one that is installed. Catalogue says whether the catalogue of this release has it.

type ListResult

type ListResult struct {
	Catalogue CatalogueInfo `json:"catalogue"`
	Modules   []ListModule  `json:"modules"`
}

A ListResult is the answer of list.

func List

func List(ctx context.Context, env Env) (ListResult, error)

List is the catalogue of this release joined with what is installed.

type Output

type Output = osplan.Output

Output is what a command printed (its output and error output, in English, cut) and how it ended.

type PermanentError

type PermanentError struct{ Err error }

A PermanentError is a download that is not tried again.

func (*PermanentError) Error

func (e *PermanentError) Error() string

func (*PermanentError) Unwrap

func (e *PermanentError) Unwrap() error

type Reducer

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

A Reducer reads the log of a module line by line and says how the job it holds is going. The zero value is not usable; NewReducer makes one.

func NewReducer

func NewReducer(name, nonce string) *Reducer

NewReducer is a reducer for the log of the module called name. nonce is the job's; "" says it is not known, and then it is the nonce of the first marker of the module in the log that carries one.

func (*Reducer) Feed

func (r *Reducer) Feed(line string, whole bool)

Feed gives the reducer the next line of the log, without its new line. whole says that the line ended with one and was read to its end: the last line of a log that is being written does not, and a line that is cut is not whole either. Only a whole line can be a marker.

func (*Reducer) Job

func (r *Reducer) Job(unit UnitSight, now, logWritten time.Time) Job

Job says how the job is going, from what was fed, the state of the unit (read BEFORE the log was: a unit that is gone has written everything it wrote), the time now and the time the log was last written (zero when it is not known).

type Roots

type Roots struct {
	Prefix string
}

Roots is where the file system of the box is. The zero value is the real one.

func (Roots) Path

func (r Roots) Path(abs string) string

Path is the real path of an absolute path of the box.

func (Roots) Slash

func (r Roots) Slash(real string) string

Slash is the path of the box of a real path that Path made, or "" when the path is not under the prefix.

type RouteState

type RouteState struct {
	Answers bool `json:"answers"`
}

RouteState says whether the gateway answers on the route of the module.

type Runner

type Runner interface {
	Run(ctx context.Context, c Cmd) (Output, error)
}

A Runner runs commands (apt-get, systemctl). A command that ran and ended with a status is an Output, whatever the status is; one that could not be run, or that was ended by its context or its timeout, is an error.

type StatusResult

type StatusResult struct {
	Name      string     `json:"name"`
	Installed bool       `json:"installed"`
	Version   *string    `json:"version"`
	Unit      UnitState  `json:"unit"`
	Route     RouteState `json:"route"`
}

A StatusResult is the answer of status for one module.

func StatusOf

func StatusOf(ctx context.Context, env Env, name string) (StatusResult, error)

StatusOf is the state of one module. A module that is not installed (no manifest that reads) is not active, not enabled and does not answer.

type SystemInfo

type SystemInfo struct {
	Supported bool     `json:"supported"`
	Reasons   []string `json:"reasons"`
}

SystemInfo says whether this system can have the module, and the checks (by code) that say no.

type UnitSight

type UnitSight int

A UnitSight is what systemd says of the unit of the job.

const (
	// UnitGone: systemd answered, and the unit is not running (it is not there, or it ended).
	UnitGone UnitSight = iota
	// UnitActive: the unit is active, activating or deactivating.
	UnitActive
	// UnitUnknown: systemd did not answer.
	UnitUnknown
)

type UnitState

type UnitState struct {
	Active  bool `json:"active"`
	Enabled bool `json:"enabled"`
}

UnitState is what systemd says of the unit of the module.

type UpdateInfo added in v0.4.78

type UpdateInfo struct {
	Available bool   `json:"available"`
	Installed string `json:"installed"`
	Latest    string `json:"latest"`
}

UpdateInfo says whether the catalogue has a later version of an installed module.

Jump to

Keyboard shortcuts

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