package module
v0.0.0-...-c865b3d Latest Latest

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

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 20 Imported by: 2



Utility functions used throughout Fornaxian projects. Needs to be centrally accessible in order to keep everything consistent.




This section is empty.


View Source
var ErrSocketNotFound = errors.New("socket not found")


func AddressIsLocal

func AddressIsLocal(ip string) bool

AddressIsLocal checks if an IP address falls on a private subnet

func ConvertToInt

func ConvertToInt(i any) (int, error)

ConvertToInt converts any type of number interface to a regular old integer. Runes will be treated as int32 and bytes as uint8. Strings will be converted using strings.Atoi. An error will be returned if the passed parameter cannot be converted to an int

func ConvertToString

func ConvertToString(i any) (string, error)

func DetectPauses

func DetectPauses()

DetectPauses runs a continuous loop which detects stalls in the runtime and garbage collection cycles

func DiskSpace

func DiskSpace(dir string) (uint64, error)

DiskSpace uses a syscall to get the size of a storage device

func FormatData

func FormatData[T Number](size T) string

FormatData prints an amount of bytes in a readable rounded amount. The total number of digits before and after the decimal point will always be 3.

func FreeSpace

func FreeSpace(dir string) (uint64, error)

FreeSpace uses a syscall to get the amount of free bytes in a directory

func IPMask

func IPMask(addr net.IP, v4mask, v6mask int) net.IP

IPMaskPrefix applies a netmask to an IPv4 or IPv6 address. Only the bits inside the mask are retained, the remaining bits are set to 0

func IsNetError

func IsNetError(err error) bool

func NewBackgroundTask

func NewBackgroundTask(
	task func(),
	taskName string,
	wg *sync.WaitGroup,
	stopChannel chan bool,
	interval time.Duration,
	randomness time.Duration,

NewBackgroundTask runs a function at an interval with some randomness. If the interval is 30 seconds and the randomness is 10 seconds the function will run every 25 to 35 seconds. The function will register itself to the waitgroup when starting and mark itself as done when the stopChannel is closed. When the stopChannel is closed the task will run one last time regardless of how long ago it ran.

func PBKDF2Check

func PBKDF2Check(password, legacyHash string) (valid bool, err error)

PBKDF2Check checks the passwords of legacy pixeldrain-spring users.

func RandString

func RandString(n int) string

RandString generates a random base64 string of n characters long

func RemoteAddress

func RemoteAddress(r *http.Request) (addr string)

RemoteAddress resolves the address of a HTTP request to the real remote address. It takes in account proxies if the request is originated from a private IP range

func SystemdFileByName

func SystemdFileByName(name string) (*os.File, error)

SystemdFileByName returns a *os.File if there is a systemd socket with that name available

func SystemdListenerByName

func SystemdListenerByName(name string) (net.Listener, error)

SystemdSocketByName returns a net.Listener if there is a systemd socket with that name available


type ChangeWatcher

type ChangeWatcher[T any] struct {
	// contains filtered or unexported fields

ChangeWatcher watches a database row for changes and relays the events to a list of listeners

func NewChangeWatcher

func NewChangeWatcher[T any](
	changeFunc ChangeWatcherFunc[T],
	intervalStep time.Duration,
	maxInterval time.Duration,
) *ChangeWatcher[T]

NewChangeWatcher creates a new change watcher. The changeFunc is used to check whether a change occurred

func (*ChangeWatcher[T]) Close

func (s *ChangeWatcher[T]) Close(id string, c chan T)

Close closes a channel and removes it from the list of change listeners. If this is the last listener for that feed the feed will be removed

func (*ChangeWatcher[T]) Open

func (s *ChangeWatcher[T]) Open(id string) chan T

Open creates a new change listener for an item. Do not close the channel yourself because then the watcher thread will crash. Call Close() instead

func (*ChangeWatcher[T]) Stats

func (s *ChangeWatcher[T]) Stats() (watchers int, listeners int)

Stats returns some statistics about the change watcher. Currently the only available stat is the number of watcher threads active

type ChangeWatcherFunc

type ChangeWatcherFunc[T any] func(id string, previousThing T) (changed bool, thing T)

ChangeWatcherFunc is the function which periodically checks if a value has changed. The ID is the ID of the thing to monitor. previousThing is the last value of the thing which was returned, use this to compare if the thing has changed. previousThing will be nil in the first run.

If the thing has changed you should return true and the new thing. Else return false and the thing which was checked

And an error occurs you should return changed=false and thing=nil

type ExecutionLimiter

type ExecutionLimiter struct {
	// contains filtered or unexported fields

ExecutionLimiter is a utility which limits the concurrent execution of a function. When it is initialized it creates a channel with x capacity and fills it with x booleans. Every time the Lock() function is called a bool is removed from the channel. When the channel is empty the function will block until the Unlock function is called, which puts a new bool into the channel.

func NewExecutionLimiter

func NewExecutionLimiter(numThreads int) (el *ExecutionLimiter)

NewExecutionLimiter creates a new Exection Limiter. The numThreads parameter is how many threads can concurrently execute the function

func (*ExecutionLimiter) Drain

func (el *ExecutionLimiter) Drain()

Drain drains the execution limiter of all slots. This essentially functions as the Wait function of a WaitGroup. After Drain the ExecutionLimiter cannot be used anymore

func (*ExecutionLimiter) Exec

func (el *ExecutionLimiter) Exec(f func())

Exec obtains an execution slot, runs the provided function and then returns the slot

func (*ExecutionLimiter) Lock

func (el *ExecutionLimiter) Lock()

Lock the ExecutionLimiter

func (*ExecutionLimiter) Stop

func (el *ExecutionLimiter) Stop()

Stop the ExecutionLimiter. This destroys the channel. Calling Unlock after Stop will panic

func (*ExecutionLimiter) TryLock

func (el *ExecutionLimiter) TryLock() (ok bool)

Lock the ExecutionLimiter

func (*ExecutionLimiter) Unlock

func (el *ExecutionLimiter) Unlock()

Unlock the ExecutionLimiter

type LoadAvg

type LoadAvg struct {
	Load1Min            float64
	Load5Min            float64
	Load15Min           float64
	CurrentlyScheduling int
	TotalScheduling     int
	LastPID             int

LoadAvg contains information about the system load

func GetLoadAvg

func GetLoadAvg() (load LoadAvg, err error)

GetLoadAvg reads and parses Linux's /proc/loadavg file

type MemInfo

type MemInfo struct {
	MemTotal          int64
	MemFree           int64
	MemAvailable      int64
	Buffers           int64
	Cached            int64
	SwapCached        int64
	Active            int64
	Inactive          int64
	ActiveAnon        int64
	InactiveAnon      int64
	ActiveFile        int64
	InactiveFile      int64
	Unevictable       int64
	Mlocked           int64
	SwapTotal         int64
	SwapFree          int64
	Dirty             int64
	Writeback         int64
	AnonPages         int64
	Mapped            int64
	Shmem             int64
	KReclaimable      int64
	Slab              int64
	SReclaimable      int64
	SUnreclaim        int64
	KernelStack       int64
	PageTables        int64
	NFSUnstable       int64
	Bounce            int64
	WritebackTmp      int64
	CommitLimit       int64
	CommittedAs       int64
	VmallocTotal      int64
	VmallocUsed       int64
	VmallocChunk      int64
	Percpu            int64
	HardwareCorrupted int64
	AnonHugePages     int64
	ShmemHugePages    int64
	ShmemPmdMapped    int64
	FileHugePages     int64
	FilePmdMapped     int64
	HugePagesTotal    int64
	HugePagesFree     int64
	HugePagesRsvd     int64
	HugePagesSurp     int64
	Hugepagesize      int64
	Hugetlb           int64
	DirectMap4k       int64
	DirectMap2M       int64
	DirectMap1G       int64

MemInfo contains information about the system's random access memory

func GetMemInfo

func GetMemInfo() (mem MemInfo, err error)

GetMemInfo reads and parses Linux's /proc/meminfo file

type NetInfo

type NetInfo struct {
	Interface    string
	RXBytes      int64
	RXPackets    int64
	RXErrors     int64
	RXDropped    int64
	RXFIFO       int64
	RXFrame      int64
	RXCompressed int64
	RXMulticast  int64
	TXBytes      int64
	TXPackets    int64
	TXErrors     int64
	TXDropped    int64
	TXFIFO       int64
	TXCollisions int64
	TXCarrier    int64
	TXCompressed int64

NetInfo contains information about the system's networking interfaces

func GetNetInfo

func GetNetInfo(iface string) (inf NetInfo, err error)

GetNetInfo reads and parses Linux's /proc/net/dev file

type Number

type Number interface {
	int | int64 | uint64 | float64

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields

A Pool is a generic wrapper around a sync.Pool.

func NewPool

func NewPool[T any](newFunc func() T) *Pool[T]

New creates a new Pool with the provided new function.

The equivalent sync.Pool construct is "sync.Pool{New: fn}"

func (*Pool[T]) Get

func (p *Pool[T]) Get() T

Get is a generic wrapper around sync.Pool's Get method.

func (*Pool[T]) Put

func (p *Pool[T]) Put(x T)

Put is a generic wrapper around sync.Pool's Put method.

Jump to

Keyboard shortcuts

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