Documentation
¶
Index ¶
- Constants
- func Alloc(size int) []byte
- func AllocAlignedBuf(size int) []byte
- func AllocMemory() int64
- func BufAligned(buf []byte) bool
- func ContainsAll(sliceA, sliceB []string) (bool, string)
- func DisableLogColor()
- func Duration(s string) time.Duration
- func Exists(path string) bool
- func FindAvailablePort(ip string, port int) (net.Listener, error)
- func FormatBytes(n uint64) string
- func FormatBytesShort(n uint64) string
- func Free(b []byte)
- func GetBlockCount(length uint64, blockSize uint32) uint32
- func GetBlockSize(blockSize uint32, length uint64, blk uint32) uint64
- func GetDefaultIp() (string, error)
- func GetEnvBool(name string, def bool) bool
- func GetEnvInt(name string, def, min int) int
- func GetFileInode(path string) (uint64, error)
- func GetIPsFromInterfaces(nicNames []string) ([]string, error)
- func GetInterfaceIp(interfaceName string) (string, error)
- func GetLocalIp(address string) (string, error)
- func GetRangeBlockBytes(fileSize, start, length uint64, blockSize uint32) (int64, error)
- func GetThpPolicy() (string, error)
- func GetThpShmemPolicy() (string, error)
- func InitLoggers(logToSyslog bool)
- func IsPowerOfTwo(n int) bool
- func LastNBytes(s string, n int) string
- func ListenWithRandomPort(ip string) (net.Listener, int, error)
- func LivenessProbe(rawAddr string, randPort bool) error
- func Malloc(size int) ([]byte, error)
- func MemoryUsage() (virt, rss uint64)
- func Mfree(b []byte) error
- func Min(a, b int) int
- func OpenDirect(path string, flag int, perm os.FileMode) (*os.File, error)
- func ParsePathsFromReader(r io.Reader) ([]string, error)
- func ReadPathsFromCmd(name, cmdStr string, timeout time.Duration) ([]string, string, time.Duration, error)
- func ReadPathsFromFile(fname string) ([]string, error)
- func RemovePassword(uri string) string
- func ReorderOptions(app *cli.App, args []string) []string
- func SetLogID(id string)
- func SetLogLevel(lvl logrus.Level)
- func SetOutFile(name string)
- func SetOutput(w io.Writer)
- func SetThpPolicy(policy string) error
- func SetThpShmemPolicy(policy string) error
- func SetupBlockPool(conf *BlockPoolConfig)
- func SetupGoGc(conf GoGcConfig, defaultLimit int64)
- func SetupMadvise()
- func SetupShmThp(policy string)
- func SetupThp(policy string)
- func SleepWithJitter(d time.Duration)
- func SleepWithJitterOrStop(d time.Duration, stopCh <-chan struct{}) (stopped bool)
- func SplitDir(d string) []string
- func StringContains(s []string, e string) bool
- func StringSetEqual(a, b map[string]struct{}) bool
- func SupportANSIColor(fd uintptr) bool
- func TidInPid(tid, pid int) bool
- func ToStringSet(paths []string) map[string]struct{}
- func Unmount(mp string, force bool) error
- func WithTimeout(f func() error, timeout time.Duration) error
- type BlockPoolConfig
- type BlockPoolStats
- type Buffer
- func (b *Buffer) Buffer() []byte
- func (b *Buffer) Bytes() []byte
- func (b *Buffer) Get(l int) []byte
- func (b *Buffer) Get8() uint8
- func (b *Buffer) Get16() uint16
- func (b *Buffer) Get32() uint32
- func (b *Buffer) Get64() uint64
- func (b *Buffer) HasMore() bool
- func (b *Buffer) Left() int
- func (b *Buffer) Len() int
- func (b *Buffer) Put(v []byte)
- func (b *Buffer) Put8(v uint8)
- func (b *Buffer) Put16(v uint16)
- func (b *Buffer) Put32(v uint32)
- func (b *Buffer) Put64(v uint64)
- func (b *Buffer) Seek(p int)
- func (b *Buffer) SetBytes(buf []byte)
- type Cond
- type DioGate
- type GoGcConfig
- type LogHandle
- type Memfd
- type PendingOpsManager
- type Rusage
- type SyslogHook
- type Token
Constants ¶
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 AllocAlignedBuf ¶
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 ¶
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 ¶
Check if `sliceB` contains all elements in `sliceA`, and returns the first not found element in `sliceA`
func DisableLogColor ¶
func DisableLogColor()
func FindAvailablePort ¶
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 FormatBytesShort ¶
Format n as a compact human-readable size (e.g. "4.10GiB") without the raw byte count, keeping tabular output aligned.
func GetBlockCount ¶
Return block count given total length and block size
func GetBlockSize ¶
Get size of given block
func GetEnvBool ¶
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 ¶
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 GetIPsFromInterfaces ¶
func GetInterfaceIp ¶
GetInterfaceIp retrieves the first valid IPv4 address of the given network interface.
func GetLocalIp ¶
GetLocalIp get the local ip used to access remote address.
func GetRangeBlockBytes ¶
GetRangeBlockBytes returns the bytes of complete blocks intersecting [start, start+length).
func GetThpPolicy ¶
func GetThpShmemPolicy ¶
func InitLoggers ¶
func InitLoggers(logToSyslog bool)
func IsPowerOfTwo ¶
func LastNBytes ¶
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 LivenessProbe ¶
func Malloc ¶
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 OpenDirect ¶
OpenDirect opens the file with O_DIRECT in addition to the given flags.
func ParsePathsFromReader ¶
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 ¶
Reads a path list from a file, one per line. Empty lines and '#' comment lines are skipped.
func RemovePassword ¶
func ReorderOptions ¶
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 SetLogLevel ¶
SetLogLevel sets Level to all the loggers in the map
func SetOutFile ¶
func SetOutFile(name string)
func SetThpPolicy ¶
func SetThpShmemPolicy ¶
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 SleepWithJitter ¶
func SleepWithJitterOrStop ¶
Same as SleepWithJitter, but returns early if stopCh is closed. Returns true if the sleep was interrupted by stopCh, false otherwise.
func StringContains ¶
func StringSetEqual ¶
Return true if two string sets contain the same elements.
func SupportANSIColor ¶
func ToStringSet ¶
Convert a string slice to a set (map[string]struct{}), deduplicating entries.
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 ReadBuffer ¶
ReadBuffer utility to create *Buffer from slice of bytes
type Cond ¶
Cond is similar to sync.Cond, but you can wait with a timeout.
func (*Cond) Broadcast ¶
func (c *Cond) Broadcast()
Broadcast wake up all the waiters. It's required for the caller to hold L.
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 ¶
NewDioGate returns a gate whose warning message identifies the given subsystem.
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 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 ¶
MemfdAlloc allocates a block from memfd, reusing a pooled one when available.
func (*Memfd) ExportFd ¶
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 ¶
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 SyslogHook ¶
type SyslogHook struct {
*logrus_syslog.SyslogHook
}