utils

package
v0.0.0-...-d260292 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 29 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

Index

Constants

View Source
const DirectIOAlignSize = 4096

DirectIOAlignSize is the alignment (in bytes) O_DIRECT requires for file offset, IO length and the memory buffer address. 4096 covers the logical block size of virtually all block devices (512 or 4096). Cache/source block size is always a power of 2 >= 4MiB, so full-block offsets and lengths are always multiples of it.

Variables

This section is empty.

Functions

func Alloc

func Alloc(size int) []byte

Alloc returns size bytes memory from Go heap.

func AllocAlignedBuf

func AllocAlignedBuf(size int) []byte

AllocAlignedBuf returns a heap-backed byte slice of the given size whose start address is aligned to DirectIOAlignSize; combined with a size that is a multiple of DirectIOAlignSize the result satisfies BufAligned. It over-allocates and reslices to the first aligned offset (Go's GC does not move heap objects, so the address stays stable for the slice's lifetime). It returns nil for a non-positive size. This is mainly a helper for exercising O_DIRECT paths without mmap/memfd page allocation.

func AllocMemory

func AllocMemory() int64

AllocMemory returns the allocated memory. Pooled blocks are still counted: they are genuinely resident, since the pool never drops their pages.

func BufAligned

func BufAligned(buf []byte) bool

BufAligned reports whether buf can back a full O_DIRECT transfer: both its start address and its length must be aligned to DirectIOAlignSize (an empty buffer is never eligible). The remaining O_DIRECT requirement, file offset alignment, is a property of the IO call site and must be checked there.

func ContainsAll

func ContainsAll(sliceA, sliceB []string) (bool, string)

Check if `sliceB` contains all elements in `sliceA`, and returns the first not found element in `sliceA`

func DisableLogColor

func DisableLogColor()

func Duration

func Duration(s string) time.Duration

func Exists

func Exists(path string) bool

Exists checks if the file/folder in given path exists

func FindAvailablePort

func FindAvailablePort(ip string, port int) (net.Listener, error)

Attempts to listen on a TCP port at the specified IP. It first tries to use the specified port. If that port is not available (e.g. already in use), it will then attempt to listen on any available port by specifying IP with an empty port, which lets the system choose a random available port.

func FormatBytes

func FormatBytes(n uint64) string

func FormatBytesShort

func FormatBytesShort(n uint64) string

Format n as a compact human-readable size (e.g. "4.10GiB") without the raw byte count, keeping tabular output aligned.

func Free

func Free(b []byte)

Free returns memory to Go heap.

func GetBlockCount

func GetBlockCount(length uint64, blockSize uint32) uint32

Return block count given total length and block size

func GetBlockSize

func GetBlockSize(blockSize uint32, length uint64, blk uint32) uint64

Get size of given block

func GetDefaultIp

func GetDefaultIp() (string, error)

Get IP address of device with default route

func GetEnvBool

func GetEnvBool(name string, def bool) bool

GetEnvBool reads environment variable `name` as a bool. It returns `def` silently when the variable is unset or blank. Everything strconv.ParseBool takes is accepted ("1", "0", "t", "f", "true", "false" and their upper and title case spellings), plus "yes"/"y"/"on" and "no"/"n"/"off" case insensitively. Any other value logs a warning and returns `def`. On a valid override it logs an info line and returns the value.

func GetEnvInt

func GetEnvInt(name string, def, min int) int

GetEnvInt reads environment variable `name` as an int. It returns `def` silently when the variable is unset or empty. When the value is non-numeric or below `min` (the inclusive lower bound), it logs a warning and returns `def`. On a valid override it logs an info line and returns the value. Use min=1 to require a positive value, or min=0 to also allow zero.

func GetFileInode

func GetFileInode(path string) (uint64, error)

func GetIPsFromInterfaces

func GetIPsFromInterfaces(nicNames []string) ([]string, error)

func GetInterfaceIp

func GetInterfaceIp(interfaceName string) (string, error)

GetInterfaceIp retrieves the first valid IPv4 address of the given network interface.

func GetLocalIp

func GetLocalIp(address string) (string, error)

GetLocalIp get the local ip used to access remote address.

func GetRangeBlockBytes

func GetRangeBlockBytes(fileSize, start, length uint64, blockSize uint32) (int64, error)

GetRangeBlockBytes returns the bytes of complete blocks intersecting [start, start+length).

func GetThpPolicy

func GetThpPolicy() (string, error)

func GetThpShmemPolicy

func GetThpShmemPolicy() (string, error)

func InitLoggers

func InitLoggers(logToSyslog bool)

func IsPowerOfTwo

func IsPowerOfTwo(n int) bool

func LastNBytes

func LastNBytes(s string, n int) string

LastNBytes returns the last n bytes of s. If n <= 0, it returns an empty string. If n >= len(s), it returns the entire string.

func ListenWithRandomPort

func ListenWithRandomPort(ip string) (net.Listener, int, error)

func LivenessProbe

func LivenessProbe(rawAddr string, randPort bool) error

func Malloc

func Malloc(size int) ([]byte, error)

Malloc returns size bytes memory from private & anonymous mmap, doesn't allocate from go heap and put less pressure on GC. Block-sized allocations are served from the block pool when it holds a free block.

func MemoryUsage

func MemoryUsage() (virt, rss uint64)

func Mfree

func Mfree(b []byte) error

Mfree returns memory to the block pool if it fits and has room, otherwise to the OS.

func Min

func Min(a, b int) int

Min returns min of 2 int

func OpenDirect

func OpenDirect(path string, flag int, perm os.FileMode) (*os.File, error)

OpenDirect opens the file with O_DIRECT in addition to the given flags.

func ParsePathsFromReader

func ParsePathsFromReader(r io.Reader) ([]string, error)

Parses paths from r, one per line. Empty lines and lines starting with '#' are skipped.

func ReadPathsFromCmd

func ReadPathsFromCmd(name, cmdStr string, timeout time.Duration) ([]string, string, time.Duration, error)

Executes cmdStr and parses its stdout as a path list (one per line, '#' comments and empty lines skipped). The command string is split on whitespace into program and arguments. A positive timeout limits the command's execution time; zero or negative means no timeout. name is a human-readable label (e.g. "Pin cache") used to prefix log messages.

On success it also returns the command's stdout (trailing newlines trimmed, or "<empty>" when there is none) and how long the command took.

func ReadPathsFromFile

func ReadPathsFromFile(fname string) ([]string, error)

Reads a path list from a file, one per line. Empty lines and '#' comment lines are skipped.

func RemovePassword

func RemovePassword(uri string) string

func ReorderOptions

func ReorderOptions(app *cli.App, args []string) []string

ReorderOptions reorders args so that global flags appear before the subcommand name and subcommand flags appear directly after it. This allows users to intermix global and command-level options in any order on the command line.

func SetLogID

func SetLogID(id string)

func SetLogLevel

func SetLogLevel(lvl logrus.Level)

SetLogLevel sets Level to all the loggers in the map

func SetOutFile

func SetOutFile(name string)

func SetOutput

func SetOutput(w io.Writer)

func SetThpPolicy

func SetThpPolicy(policy string) error

func SetThpShmemPolicy

func SetThpShmemPolicy(policy string) error

func SetupBlockPool

func SetupBlockPool(conf *BlockPoolConfig)

SetupBlockPool installs the process-global block pool at startup. Slots caps the shared ready-block capacity across mmap and memfd.

A nil config, non-positive BlockSize or Slots, or both capabilities disabled leaves the current pool unchanged. SetupBlockPool must be called once.

func SetupGoGc

func SetupGoGc(conf GoGcConfig, defaultLimit int64)

SetupGoGc applies conf as if it were given via GOGC and GOMEMLIMIT at startup. The Go runtime reads these variables only at startup, so a setting from conf is applied explicitly, and only if the corresponding variable is not set.

If neither the variables nor conf is set, disable GC and set memory limit to defaultLimit. This is to reduce GC frequency, as go heap is low when allocating memory via mmap or memfd, which triggers frequent GC and puts more load on CPU.

func SetupMadvise

func SetupMadvise()

Detect THP policy and check if they're madvise, so we could do madvise only if policy is madvise

func SetupShmThp

func SetupShmThp(policy string)

func SetupThp

func SetupThp(policy string)

func SleepWithJitter

func SleepWithJitter(d time.Duration)

func SleepWithJitterOrStop

func SleepWithJitterOrStop(d time.Duration, stopCh <-chan struct{}) (stopped bool)

Same as SleepWithJitter, but returns early if stopCh is closed. Returns true if the sleep was interrupted by stopCh, false otherwise.

func SplitDir

func SplitDir(d string) []string

SplitDir splits a path with default path list separator or comma.

func StringContains

func StringContains(s []string, e string) bool

func StringSetEqual

func StringSetEqual(a, b map[string]struct{}) bool

Return true if two string sets contain the same elements.

func SupportANSIColor

func SupportANSIColor(fd uintptr) bool

func TidInPid

func TidInPid(tid, pid int) bool

func ToStringSet

func ToStringSet(paths []string) map[string]struct{}

Convert a string slice to a set (map[string]struct{}), deduplicating entries.

func Unmount

func Unmount(mp string, force bool) error

func WithTimeout

func WithTimeout(f func() error, timeout time.Duration) error

Types

type BlockPoolConfig

type BlockPoolConfig struct {
	BlockSize int
	Slots     int
	Timeout   time.Duration
	Reuse     bool
	Prefault  bool
	Memfd     bool
}

BlockPoolConfig configures the process-global block pool.

type BlockPoolStats

type BlockPoolStats struct {
	Enabled               bool
	BlockSize             int
	Slots                 int
	Cached                int   // resident warm blocks currently held
	CachedBytes           int64 // resident warm bytes currently held
	ReuseCount            int64
	ReuseBytes            int64
	ReallocCount          int64
	ReallocBytes          int64
	PrefaultBlocks        int64
	PrefaultBytes         int64
	PrefaultFail          int64
	PrefaultSkipBlocks    int64
	PrefaultSkipBytes     int64
	PrefaultDiscardBlocks int64
	PrefaultDiscardBytes  int64
}

BlockPoolStats reports the block-pool state for metrics. Enabled is false when the pool is disabled, in which case every other field is zero.

func GetBlockPoolStats

func GetBlockPoolStats() BlockPoolStats

GetBlockPoolStats returns one mutex-consistent snapshot of the pool counters.

type Buffer

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

Buffer is a buffer to read/write integers.

func FromBuffer

func FromBuffer(buf []byte) *Buffer

FromBuffer utility to create *Buffer

func NewBuffer

func NewBuffer(sz uint32) *Buffer

NewBuffer returns a buffer with sz number of bytes.

func ReadBuffer

func ReadBuffer(buf []byte) *Buffer

ReadBuffer utility to create *Buffer from slice of bytes

func (*Buffer) Buffer

func (b *Buffer) Buffer() []byte

Buffer returns

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Bytes returns the bytes

func (*Buffer) Get

func (b *Buffer) Get(l int) []byte

Get returns `l` bytes from offset

func (*Buffer) Get8

func (b *Buffer) Get8() uint8

Get8 returns uint8

func (*Buffer) Get16

func (b *Buffer) Get16() uint16

Get16 returns uint16

func (*Buffer) Get32

func (b *Buffer) Get32() uint32

Get32 returns uint32

func (*Buffer) Get64

func (b *Buffer) Get64() uint64

Get64 returns uint64

func (*Buffer) HasMore

func (b *Buffer) HasMore() bool

HasMore checks if offset is less than length

func (*Buffer) Left

func (b *Buffer) Left() int

Left returns number of bytes after offset

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns length of buffer

func (*Buffer) Put

func (b *Buffer) Put(v []byte)

Put appends slice of byte to Buffer

func (*Buffer) Put8

func (b *Buffer) Put8(v uint8)

Put8 appends uint8 to Buffer

func (*Buffer) Put16

func (b *Buffer) Put16(v uint16)

Put16 appends uint16 to Buffer

func (*Buffer) Put32

func (b *Buffer) Put32(v uint32)

Put32 appends uint32 to Buffer

func (*Buffer) Put64

func (b *Buffer) Put64(v uint64)

Put64 appends uint64 to Buffer

func (*Buffer) Seek

func (b *Buffer) Seek(p int)

Seek seeks or sets offset to `p`

func (*Buffer) SetBytes

func (b *Buffer) SetBytes(buf []byte)

SetBytes initilizes the Buffer with BigEndian ordering

type Cond

type Cond struct {
	L sync.Locker
	// contains filtered or unexported fields
}

Cond is similar to sync.Cond, but you can wait with a timeout.

func NewCond

func NewCond(lock sync.Locker) *Cond

NewCond creates a Cond.

func (*Cond) Broadcast

func (c *Cond) Broadcast()

Broadcast wake up all the waiters. It's required for the caller to hold L.

func (*Cond) Signal

func (c *Cond) Signal()

Signal wakes up a waiter. It's required for the caller to hold L.

func (*Cond) Wait

func (c *Cond) Wait()

Wait until Signal() or Broadcast() is called.

func (*Cond) WaitWithTimeout

func (c *Cond) WaitWithTimeout(d time.Duration) bool

WaitWithTimeout wait for a signal or a period of timeout eclipsed. returns true in case of timeout else false

type DioGate

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

DioGate is a one-way latch that permanently disables O_DIRECT for a subsystem once the underlying filesystem rejects it (EINVAL), logging exactly once. It is metric-agnostic: callers expose the effective state via their own gauge by polling Disabled(). It contains an atomic and must not be copied after use.

func NewDioGate

func NewDioGate(label string) *DioGate

NewDioGate returns a gate whose warning message identifies the given subsystem.

func (*DioGate) Disable

func (g *DioGate) Disable(cause error)

Disable permanently falls back to buffered IO. The compare-and-swap guarantees the warning is logged exactly once even under concurrent first failures, and uses no lock to avoid ordering issues with the caller's mutexes.

func (*DioGate) Disabled

func (g *DioGate) Disabled() bool

Disabled reports whether O_DIRECT has been permanently disabled.

type GoGcConfig

type GoGcConfig struct {
	GCPercent    int
	GCPercentSet bool
	MemLimit     int64 // in bytes, 0 means not set
}

GoGcConfig holds GC settings given on the command line as an alternative to the GOGC and GOMEMLIMIT environment variables, which take precedence.

type LogHandle

type LogHandle struct {
	logrus.Logger
	// contains filtered or unexported fields
}

func GetLogger

func GetLogger(name string) *LogHandle

GetLogger returns a logger mapped to `name`

func (*LogHandle) Format

func (l *LogHandle) Format(e *logrus.Entry) ([]byte, error)

func (*LogHandle) Log

func (l *LogHandle) Log(args ...interface{})

for aws.Logger

type Memfd

type Memfd struct {
	Name string // per-allocation name, Go side only; the kernel name is memfdName
	Fd   int
	// contains filtered or unexported fields
}

Memfd is a memfd-backed block: an fd and the MAP_SHARED mapping over it, freed together by Free.

A memfd's inode identity can leave this process - the fd is dup'd and handed to another process, which mmaps it and holds the mapping for an arbitrary time. For such a block "free" and "recycle" are not equivalent: a real free (close + munmap) leaves the foreign fd holding the last reference to the tmpfs object, so its contents are frozen and safe, while a pool push keeps the same inode alive and later rewrites it, and any still-live foreign mapping then observes foreign data.

exportCount is what separates the two. It counts exported copies whose disappearance is not proven, and a block is pooled only at zero. See ExportFd/UnexportFd.

func MemfdAlloc

func MemfdAlloc(name string, size int) (*Memfd, error)

MemfdAlloc allocates a block from memfd, reusing a pooled one when available.

func (*Memfd) Data

func (m *Memfd) Data() []byte

Data returns the mmap'd buffer.

func (*Memfd) ExportFd

func (m *Memfd) ExportFd() (int, error)

ExportFd hands out an fd that will leave this process's control, and counts it. Dup and count are fused so a raw memfd fd can never be exported uncounted.

func (*Memfd) Free

func (m *Memfd) Free() error

Free releases the block. It pools the block only when no exported copy may still be alive, otherwise it really closes the fd and unmaps the buffer.

Free must not run concurrently with ExportFd on the same block: it reads the count and pushes as two steps, so an export landing in between would be handed out for a block already back in the pool. The count cannot close that window on its own - the caller has to keep the block alive for as long as it may still export it, which is what a refcount on the owning object does. Free is the point where that ownership ends, so by then no exporter can be left.

func (*Memfd) UnexportFd

func (m *Memfd) UnexportFd()

UnexportFd records that one fd handed out by ExportFd is gone. It closes nothing: that fd is out of this process's control, so all this does is update the count Free consults before reusing the block.

Only call it once the copy is provably gone, meaning the receiver has confirmed that it unmapped the memory and closed the fd, or the exported fd never actually left this process. A receiver that merely disconnected or died proves nothing: its mapping can outlive whatever channel it was reached through, and reusing the block would rewrite memory it is still reading.

A copy whose fate cannot be established is therefore never subtracted: the count never returns to zero and the block is never reused again. An unaccountable export costs reuse, not correctness.

Subtracting one copy twice is a bug, and driving the count below zero is not a safe place to leave it: a later legitimate export would cancel the deficit back to zero, which is exactly the value that permits pooling, so the block would be reused with a live copy outstanding. A count that has gone negative is therefore not repaired but abandoned - the block is poisoned and can never be pooled again.

type PendingOpsManager

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

PendingOpsManager manages pending operations to avoid duplicate work. It provides a mechanism to wait for ongoing operations to complete before starting duplicate operations.

func NewPendingOpsManager

func NewPendingOpsManager(timeout time.Duration) *PendingOpsManager

NewPendingOpsManager creates a new pending operations manager with the given timeout

func (*PendingOpsManager) Add

func (p *PendingOpsManager) Add(key string) bool

Add registers a pending operation for the given key. It returns true only for the caller that created the operation.

func (*PendingOpsManager) Clear

func (p *PendingOpsManager) Clear()

Clear removes all pending operations without notifying waiters This should only be used during cleanup/shutdown

func (*PendingOpsManager) Count

func (p *PendingOpsManager) Count() int

Count returns the number of currently pending operations

func (*PendingOpsManager) Exists

func (p *PendingOpsManager) Exists(key string) bool

Exists checks if an operation is currently pending for the given key

func (*PendingOpsManager) Remove

func (p *PendingOpsManager) Remove(key string)

Remove unregisters a pending operation and notifies all waiters

func (*PendingOpsManager) Wait

func (p *PendingOpsManager) Wait(key string) bool

Wait checks if an operation is pending for the given key. If pending, it waits for the operation to complete or times out. Returns true if the operation completed successfully, false if not pending or timed out.

type Rusage

type Rusage struct {
	syscall.Rusage
}

func GetRusage

func GetRusage() *Rusage

GetRusage returns CPU usage of current process.

func (*Rusage) GetStime

func (ru *Rusage) GetStime() float64

GetStime returns the system time in seconds.

func (*Rusage) GetUtime

func (ru *Rusage) GetUtime() float64

GetUtime returns the user time in seconds.

type SyslogHook

type SyslogHook struct {
	*logrus_syslog.SyslogHook
}

func (*SyslogHook) Fire

func (hook *SyslogHook) Fire(entry *logrus.Entry) error

type Token

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

func NewToken

func NewToken(size int) *Token

func (*Token) Get

func (t *Token) Get()

func (*Token) Put

func (t *Token) Put()

Jump to

Keyboard shortcuts

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