setup

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: Apache-2.0, MIT Imports: 57 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PiriServeCommand                  = "serve"
	PiriUpdateCommand                 = "update-internal"
	PiriServiceFile                   = "piri.service"
	PiriUpdateServiceFile             = "piri-updater.service"
	PiriUpdateTimerServiceFile        = "piri-updater.timer"
	PiriServiceName                   = "piri"
	PiriUpdateTimerName               = "piri-updater.timer"
	ReleaseURL                        = "https://api.github.com/repos/storacha/piri/releases/latest"
	PiriUpdateBootDuration            = 2 * time.Minute
	PiriUpdateUnitActiveDuration      = 30 * time.Minute
	PiriUpdateRandomizedDelayDuration = 5 * time.Minute
)

Service-related constants

Variables

View Source
var (
	PiriServerShutdownTimeout = Config.ServerShutdown
	PiriSystemdShutdownBuffer = Config.SystemdBuffer
	PiriOptDir                = Config.OptDir
	PiriBinaryBaseDir         = Config.BinaryBaseDir
	PiriCurrentSymlink        = Config.CurrentSymlink
	PiriBinaryPath            = Config.BinaryPath
	PiriSystemDir             = Config.SystemDir
	PiriSystemdBaseDir        = Config.SystemdBaseDir
	PiriSystemdCurrentSymlink = Config.SystemdCurrentSymlink
	PiriSystemdDir            = Config.SystemdCurrentSymlink // Points to current version for backward compat
)

Compatibility constants for existing code

View Source
var (
	PiriCLISymlinkPath             = Config.CLISymlinkPath
	SystemDPath                    = Config.SystemdPath
	PiriSudoersFile                = Config.SudoersFile
	PiriConfigFileName             = Config.ConfigFileName
	PiriSystemConfigPath           = filepath.Join(Config.SystemDir, Config.ConfigFileName)
	PiriServiceFilePath            = filepath.Join(Config.SystemdPath, PiriServiceFile)
	PiriUpdateServiceFilePath      = filepath.Join(Config.SystemdPath, PiriUpdateServiceFile)
	PiriUpdateTimerServiceFilePath = filepath.Join(Config.SystemdPath, PiriUpdateTimerServiceFile)
)

More compatibility constants

Global default config (can be overridden in tests)

View Source
var InitCmd = &cobra.Command{
	Use:   "init",
	Args:  cobra.NoArgs,
	Short: "Initialize your piri node in the storacha network",
	RunE:  doInit,
}
View Source
var InstallCmd = &cobra.Command{
	Use:   "install",
	Short: "Install Piri as a system service",
	Long: `Install configures Piri to run as a systemd service on Linux systems.

This command performs the following operations:
  - Installs the piri binary to /opt/piri/bin/{version}/piri
  - Creates the /opt/piri/etc directory for configuration
  - Installs the provided configuration file to /opt/piri/systemd, and symlinks to /etc/systemd/system/
  - Creates and enables systemd service files
  - Creates sudoers entry for service restart (required for auto-updates)
  - Optionally enables automatic updates (--enable-auto-update)

Requirements:
  - Linux operating system with systemd
  - Root privileges (run with sudo)
  - Configuration file from 'piri init' command

Automatic updates check for new releases every 30 minutes and apply them when
safe to do so (not during proof generation or active transfers).`,
	Args:   cobra.NoArgs,
	RunE:   runInstall,
	Hidden: true,
}
View Source
var (
	InternalUpdateCmd = &cobra.Command{
		Use:    "update-internal",
		Args:   cobra.NoArgs,
		Hidden: true,
		RunE:   doUpdateInternal,
	}
)
View Source
var SupportedLinuxArch = map[string]bool{
	"amd64": true,
	"arm64": true,
}
View Source
var UninstallCmd = &cobra.Command{
	Use:   "uninstall",
	Short: "Uninstall Piri system service",
	Long: `Uninstall removes the Piri systemd services and symlinks.

This command performs the following operations:
  - Stops all running piri services (piri.service and piri-updater.timer if enabled)
  - Disables systemd services
  - Removes symlinks from /etc/systemd/system/
  - Removes the CLI symlink from /usr/local/bin/piri
  - Reloads systemd daemon

NOTE: The binaries in /opt/piri are preserved for version management.
To completely remove piri, manually delete /opt/piri after uninstalling.

Requirements:
  - Linux operating system with systemd
  - Root privileges (run with sudo)`,
	Args:   cobra.NoArgs,
	RunE:   runUninstall,
	Hidden: true,
}
View Source
var (
	UpdateCmd = &cobra.Command{
		Use:   "update",
		Args:  cobra.NoArgs,
		Short: "Check for and apply updates to piri",
		Long: `Check for new releases and update the piri binary to the latest version.

This command downloads and installs the latest version but does not restart the service.
To check if an update is safe, use 'piri status upgrade-check' first.`,
		RunE: doUpdate,
	}
)

Functions

func FileExists

func FileExists(path string) bool

FileExists checks if a file exists

func GetExecutablePath

func GetExecutablePath() (string, error)

GetExecutablePath returns the path to the current executable, resolved of any symlinks

func IsSymlink(path string) bool

IsSymlink checks if a path is a symbolic link

func NeedsElevatedPrivileges

func NeedsElevatedPrivileges(path string) bool

NeedsElevatedPrivileges checks if we need elevated privileges to write to a path

Types

type CommandExecutor

type CommandExecutor interface {
	Output(name string, args ...string) ([]byte, error)
	Run(name string, args ...string) error
}

CommandExecutor interface for running system commands

type FileSystemManager

type FileSystemManager struct {
	// Track created items for potential rollback
	CreatedDirs  []string
	CreatedFiles []string
}

FileSystemManager handles file system operations with rollback support

func NewFileSystemManager

func NewFileSystemManager() *FileSystemManager

NewFileSystemManager creates a new file system manager

func (*FileSystemManager) CheckExistingFiles

func (fsm *FileSystemManager) CheckExistingFiles(files []string) error

CheckExistingFiles checks if files already exist

func (*FileSystemManager) CopyFile

func (fsm *FileSystemManager) CopyFile(src, dst string, perm os.FileMode) error

CopyFile copies a file from source to destination with permissions

func (*FileSystemManager) CreateDirectory

func (fsm *FileSystemManager) CreateDirectory(path string, perm os.FileMode) error

CreateDirectory creates a directory with specified permissions

func (*FileSystemManager) CreatePiriDirectoryStructure

func (fsm *FileSystemManager) CreatePiriDirectoryStructure(version string) error

CreatePiriDirectoryStructure creates the standard /opt/piri directory structure

func (fsm *FileSystemManager) CreateSymlink(oldpath, newpath string) error

CreateSymlink creates a symbolic link with rollback capability

func (*FileSystemManager) RemoveFiles

func (fsm *FileSystemManager) RemoveFiles(files []string) error

RemoveFiles removes a list of files, ignoring non-existent files

func (*FileSystemManager) Rollback

func (fsm *FileSystemManager) Rollback() error

Rollback removes all created files and directories (in reverse order)

func (*FileSystemManager) SetOwnership

func (fsm *FileSystemManager) SetOwnership(path string, username string) error

SetOwnership sets the ownership of a path to the specified user

func (*FileSystemManager) SetOwnershipFromPath

func (fsm *FileSystemManager) SetOwnershipFromPath(targetPath, referencePath string) error

SetOwnershipFromPath sets ownership based on another path's ownership

func (*FileSystemManager) UpdateSymlinkAtomic

func (fsm *FileSystemManager) UpdateSymlinkAtomic(symlinkPath, newTarget string) (oldTarget string, rollback func() error, err error)

UpdateSymlinkAtomic performs an atomic symlink update with rollback capability

func (*FileSystemManager) WriteFile

func (fsm *FileSystemManager) WriteFile(path string, data []byte, perm os.FileMode) error

WriteFile writes data to a file with specified permissions

type GitHubRelease

type GitHubRelease struct {
	TagName    string    `json:"tag_name"`
	Name       string    `json:"name"`
	Draft      bool      `json:"draft"`
	Prerelease bool      `json:"prerelease"`
	CreatedAt  time.Time `json:"created_at"`
	Assets     []struct {
		Name               string `json:"name"`
		BrowserDownloadURL string `json:"browser_download_url"`
	} `json:"assets"`
}

GitHubRelease represents a GitHub release

type InstallState

type InstallState struct {
	ConfigPath       string
	Config           config.FullServerConfig
	Force            bool
	EnableAutoUpdate bool
	ServiceUser      string
	Version          string
	IsUpdate         bool // true if this is an update operation
}

InstallState holds the state for installation operations

type Installer

type Installer struct {
	FileSystem     *FileSystemManager
	ServiceManager *ServiceManager
	Platform       *PlatformChecker
}

Installer handles the installation and update of Piri

func NewInstaller

func NewInstaller() (*Installer, error)

NewInstaller creates a new installer instance

func (*Installer) Cleanup

func (i *Installer) Cleanup(cmd *cobra.Command, enableAutoUpdate bool) error

Cleanup performs cleanup on installation failure

func (*Installer) CreateSudoersEntry

func (i *Installer) CreateSudoersEntry(cmd *cobra.Command, serviceUser string, enableAutoUpdate bool) error

CreateSudoersEntry creates the sudoers entry for service management

func (i *Installer) CreateSymlink(cmd *cobra.Command) error

CreateSymlink creates the symlink in /usr/local/bin

func (*Installer) EnableAndStartServices

func (i *Installer) EnableAndStartServices(cmd *cobra.Command, enableAutoUpdate bool) error

EnableAndStartServices enables and starts the appropriate services

func (*Installer) GenerateSystemdServices

func (i *Installer) GenerateSystemdServices(serviceUser string, version string) []ServiceFile

GenerateSystemdServices generates systemd service configurations for a specific version

func (*Installer) InstallBinary

func (i *Installer) InstallBinary(cmd *cobra.Command, version string) error

InstallBinary installs the piri binary to the appropriate location

func (*Installer) InstallConfiguration

func (i *Installer) InstallConfiguration(cmd *cobra.Command, cfg config.FullServerConfig) error

InstallConfiguration installs the configuration file

func (*Installer) InstallSystemdServices

func (i *Installer) InstallSystemdServices(cmd *cobra.Command, state *InstallState) error

InstallSystemdServices installs systemd service files

func (*Installer) PerformInstallation

func (i *Installer) PerformInstallation(cmd *cobra.Command, state *InstallState) error

PerformInstallation performs a complete installation

func (*Installer) Uninstall

func (i *Installer) Uninstall(cmd *cobra.Command) error

Uninstall performs a complete uninstallation

type PathConfig

type PathConfig struct {
	OptDir                string        // Base directory for piri installation
	BinaryBaseDir         string        // Base directory for all versioned binaries
	CurrentSymlink        string        // Symlink that points to the current version
	BinaryPath            string        // Path to the current piri binary via symlink
	SystemDir             string        // System configuration directory (not versioned)
	SystemdBaseDir        string        // Base directory for versioned systemd files
	SystemdCurrentSymlink string        // Symlink to current systemd version
	CLISymlinkPath        string        // Location of piri symlink in PATH
	SystemdPath           string        // /etc/systemd/system - where systemd reads from
	SudoersFile           string        // Sudoers configuration file path
	ConfigFileName        string        // Default config file name
	ServerShutdown        time.Duration // Server shutdown timeout
	SystemdBuffer         time.Duration // Additional systemd shutdown buffer
}

PathConfig holds all path-related configuration

func DefaultPathConfig

func DefaultPathConfig() *PathConfig

DefaultPathConfig returns the default path configuration

type PlatformChecker

type PlatformChecker struct {
	OS          string
	IsLinux     bool
	IsDarwin    bool
	HasSystemd  bool
	IsRoot      bool
	ServiceUser string
}

PlatformChecker provides platform and permission checking utilities

func NewPlatformChecker

func NewPlatformChecker() (*PlatformChecker, error)

NewPlatformChecker creates and initializes a platform checker

func (*PlatformChecker) IsManagedInstallation

func (pc *PlatformChecker) IsManagedInstallation(execPath string) bool

IsManagedInstallation checks if the current installation is managed (in /opt/piri)

func (*PlatformChecker) IsRunningUnderSystemd

func (pc *PlatformChecker) IsRunningUnderSystemd() bool

IsRunningUnderSystemd checks if the current process is running under systemd

func (*PlatformChecker) RequireLinux

func (pc *PlatformChecker) RequireLinux() error

RequireLinux returns an error if not running on Linux

func (*PlatformChecker) RequireRoot

func (pc *PlatformChecker) RequireRoot() error

RequireRoot returns an error if not running as root

func (*PlatformChecker) RequireSystemd

func (pc *PlatformChecker) RequireSystemd() error

RequireSystemd returns an error if systemd is not available

type Prerequisites

type Prerequisites struct {
	Platform      *PlatformChecker
	NeedsRoot     bool
	NeedsSystemd  bool
	CheckServices []string // Services that should not be running
	CheckFiles    []string // Files that should not exist (unless --force)
}

func (*Prerequisites) Validate

func (pr *Prerequisites) Validate(force bool) error

Validate checks all prerequisites and returns any errors

type ServiceFile

type ServiceFile struct {
	Name       string
	Content    string
	SourcePath string // Where to write the actual file
	TargetPath string // Where to create the symlink
}

ServiceFile represents a systemd service file to be installed

type ServiceManager

type ServiceManager struct {
	// Services to manage
	Services []string
	// contains filtered or unexported fields
}

ServiceManager handles all systemd service operations

func NewServiceManager

func NewServiceManager(services ...string) *ServiceManager

NewServiceManager creates a new service manager

func NewServiceManagerWithExecutor

func NewServiceManagerWithExecutor(executor CommandExecutor, services ...string) *ServiceManager

NewServiceManagerWithExecutor creates a new service manager with custom executor

func (*ServiceManager) CheckServicesNotRunning

func (sm *ServiceManager) CheckServicesNotRunning() error

CheckServicesNotRunning verifies that none of the services are running

func (*ServiceManager) DisableService

func (sm *ServiceManager) DisableService(service string) error

DisableService disables a service from auto-start

func (*ServiceManager) EnableAndStartService

func (sm *ServiceManager) EnableAndStartService(service string) error

EnableAndStartService enables and starts a service

func (*ServiceManager) EnableService

func (sm *ServiceManager) EnableService(service string) error

EnableService enables a service for auto-start

func (*ServiceManager) GetServiceStatus

func (sm *ServiceManager) GetServiceStatus(service string) (*ServiceStatus, error)

GetServiceStatus returns detailed status of a service

func (*ServiceManager) InstallServiceFiles

func (sm *ServiceManager) InstallServiceFiles(services []ServiceFile) error

InstallServiceFiles creates symlinks to the current version of service files

func (*ServiceManager) IsActive

func (sm *ServiceManager) IsActive(service string) (bool, error)

IsActive checks if a service is currently active

func (*ServiceManager) ReloadDaemon

func (sm *ServiceManager) ReloadDaemon() error

ReloadDaemon reloads the systemd daemon configuration

func (*ServiceManager) RemoveServiceFiles

func (sm *ServiceManager) RemoveServiceFiles(files []string) error

RemoveServiceFiles removes symlinks for systemd service files

func (*ServiceManager) RestartService

func (sm *ServiceManager) RestartService(service string) error

RestartService restarts a service

func (*ServiceManager) RestartServiceWithSudo

func (sm *ServiceManager) RestartServiceWithSudo(service string) error

RestartServiceWithSudo restarts a service using sudo

func (*ServiceManager) StartService

func (sm *ServiceManager) StartService(service string) error

StartService starts a service

func (*ServiceManager) StopAllServices

func (sm *ServiceManager) StopAllServices() error

StopAllServices stops all managed services

func (*ServiceManager) StopAndDisableService

func (sm *ServiceManager) StopAndDisableService(service string) error

StopAndDisableService stops a running service and disables it

func (*ServiceManager) StopService

func (sm *ServiceManager) StopService(service string) error

StopService stops a running service

func (*ServiceManager) VerifyServiceRestart

func (sm *ServiceManager) VerifyServiceRestart(service string, timeoutSec int, useSudo bool) error

VerifyServiceRestart attempts to restart a service and verifies it started successfully

type ServiceStatus

type ServiceStatus struct {
	Name    string
	Active  bool
	Enabled bool
	Running bool
	Failed  bool
}

ServiceStatus represents the status of a systemd service

type UpdateInfo

type UpdateInfo struct {
	CurrentVersion string
	LatestVersion  string
	NeedsUpdate    bool
	Release        *GitHubRelease
}

UpdateInfo contains information about available updates

Jump to

Keyboard shortcuts

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