util

package
v1.5.5 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DebugPrefix = "[DEBUG] "
	InfoPrefix  = "[INFO_]  "
	WarnPrefix  = "[WARN_]  "
	ErrorPrefix = "[ERROR] "
)
View Source
const Colorful = true

Variables

View Source
var (
	RedBold    = color.New(color.FgRed).Add(color.Bold)
	GreenBold  = color.New(color.FgGreen).Add(color.Bold)
	YellowBold = color.New(color.FgYellow).Add(color.Bold)
	BlueBold   = color.New(color.FgBlue).Add(color.Bold)
)

Colorful Bold use like `GreenBold.Sprint(str)`

View Source
var (
	ColorDebugPrefix = GreenBold.Sprint(DebugPrefix)
	ColorInfoPrefix  = BlueBold.Sprint(InfoPrefix)
	ColorWarnPrefix  = YellowBold.Sprint(WarnPrefix)
	ColorErrorPrefix = RedBold.Sprint(ErrorPrefix)
)
View Source
var DefaultLevel = INFO

Functions

func ByteToString

func ByteToString(orig []byte) string

func CheckUnpriUserNS added in v1.0.6

func CheckUnpriUserNS() error

CheckUnpriUserNS checks if the current host enable unprivileged user namespace. reference:

https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/
https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/

exceptional case:

the sysctl files(/proc/sys/kernel/unprivileged_userns_clone) only exist in Debian, Ubuntu.
We can not check the sysctl file in other distros, test in CentOS Linux release 8.4.2105 (Core).

func DistinctStrArr added in v1.5.4

func DistinctStrArr(s []string) []string

DistinctArr distinct

func FileExist added in v1.0.3

func FileExist(path string) bool

func FindTargetDeviceID

func FindTargetDeviceID(mi *MountInfo) bool

find block device id

func GetAllCGroupSubSystem added in v1.0.6

func GetAllCGroupSubSystem() ([]string, error)

func GetCgroupVersion added in v1.0.6

func GetCgroupVersion() (int, error)

get cgroup version V1/V2 hybrid mode will not work in container

func GetGateway added in v1.3.0

func GetGateway() (string, error)

GetGateway returns the default gateway for the system.

func GetKernelVersion added in v1.0.6

func GetKernelVersion() ([]int, error)

get kernel version

func HttpSendJson added in v0.1.10

func HttpSendJson(method string, url string, data string) (string, error)

func IntContains added in v1.0.4

func IntContains(s []int, e int) bool

IntContains check string array contains a int number

func IsDir

func IsDir(FilePath string) bool

func IsDirectory added in v1.0.2

func IsDirectory(path string) bool
func IsSoftLink(FilePath string) bool

func MakeDev

func MakeDev(major, minor string) int

func PrintH2 added in v1.4.1

func PrintH2(title string)

fmt.Printf(util.GreenBold.Sprint("\n[Information Gathering - System Info]\n"))

func PrintItemKey added in v1.4.1

func PrintItemKey(key string, color bool)

func PrintItemValue added in v1.4.1

func PrintItemValue(value string, color bool)

func PrintItemValueWithKeyOneLine added in v1.5.0

func PrintItemValueWithKeyOneLine(key, value string, color bool)

func PrintOrignal added in v1.5.0

func PrintOrignal(out string)

func RandString

func RandString(n int) string

func ReadLines added in v1.0.3

func ReadLines(path string) ([]string, error)

ReadLines reads a whole file into memory and returns a slice of its lines. from https://stackoverflow.com/questions/5884154/read-text-file-into-string-array-and-write

func RemoveDuplicateElement

func RemoveDuplicateElement(addrs []string) []string

func RewriteFile

func RewriteFile(path string, content string, perm os.FileMode)

func RunKubectlCmd added in v1.5.4

func RunKubectlCmd(args ...string) (string, error)

func SetBlockAccessible

func SetBlockAccessible(path string) error

set all block device accessible

func ShellExec

func ShellExec(shellPath string) error

ShellExec run shell script by bash

func StringContains added in v1.0.4

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

StringContains check string array contains a string

func UnixHttpSend

func UnixHttpSend(method string, unixPath string, uri string, data string) (string, error)

ref https://docs.docker.com/engine/api/v1.24/

func WriteFile

func WriteFile(path string, content string) error

func WriteFileAdd added in v1.0.1

func WriteFileAdd(path string, content string) error

func WriteShellcodeToCrontab added in v1.0.1

func WriteShellcodeToCrontab(header string, filePath string, shellcode string) error

Types

type Affinity added in v1.5.4

type Affinity struct {
	NodeAffinity NodeAffinity `json:"nodeAffinity"`
}

type CgroupInfo added in v1.0.6

type CgroupInfo struct {
	HierarchyID   int
	ControllerLst string // split by "," but should not be split
	CgroupPath    string
	OriginalInfo  string
}

func GetAllCGroup added in v1.0.6

func GetAllCGroup() ([]CgroupInfo, error)

func GetCgroup added in v1.1.0

func GetCgroup(pid int) ([]CgroupInfo, error)

GetCgroup returns the cgroup info of the process param pid: 0 = self, 1 = container main process

type Cluster added in v1.5.4

type Cluster struct {
	Cluster ClusterInfo `yaml:"cluster"`
	Name    string      `yaml:"name"`
}

type ClusterInfo added in v1.5.4

type ClusterInfo struct {
	CertificateAuthorityData string `yaml:"certificate-authority-data"`
	Server                   string `yaml:"server"`
}

type Condition added in v1.5.4

type Condition struct {
	Type               string    `json:"type"`
	Status             string    `json:"status"`
	LastProbeTime      time.Time `json:"lastProbeTime"`
	LastTransitionTime time.Time `json:"lastTransitionTime"`
}

type Container added in v1.5.4

type Container struct {
	Name            string          `json:"name"`
	Image           string          `json:"image"`
	Ports           []Port          `json:"ports"`
	Env             []EnvVar        `json:"env"`
	Resources       Resources       `json:"resources"`
	SecurityContext SecurityContext `json:"securityContext"`
}

type ContainerState added in v1.5.4

type ContainerState struct {
	Running    *ContainerStateRunning    `json:"running,omitempty"`
	Terminated *ContainerStateTerminated `json:"terminated,omitempty"`
	Waiting    *ContainerStateWaiting    `json:"waiting,omitempty"`
}

type ContainerStateRunning added in v1.5.4

type ContainerStateRunning struct {
	StartedAt time.Time `json:"startedAt"`
}

type ContainerStateTerminated added in v1.5.4

type ContainerStateTerminated struct {
	ExitCode int    `json:"exitCode"`
	Reason   string `json:"reason"`
}

type ContainerStateWaiting added in v1.5.4

type ContainerStateWaiting struct {
	Reason string `json:"reason"`
}

type ContainerStatus added in v1.5.4

type ContainerStatus struct {
	Name         string         `json:"name"`
	State        ContainerState `json:"state"`
	LastState    ContainerState `json:"lastState"`
	Ready        bool           `json:"ready"`
	RestartCount int            `json:"restartCount"`
	Image        string         `json:"image"`
	ImageID      string         `json:"imageID"`
	ContainerID  string         `json:"containerID"`
	Started      bool           `json:"started"`
}

type Context added in v1.5.4

type Context struct {
	Context ContextInfo `yaml:"context"`
	Name    string      `yaml:"name"`
}

type ContextInfo added in v1.5.4

type ContextInfo struct {
	Cluster string `yaml:"cluster"`
	User    string `yaml:"user"`
}

type EnvVar added in v1.5.4

type EnvVar struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type FieldsV1 added in v1.5.4

type FieldsV1 struct {
	Metadata struct {
		GenerateName string            `json:"generateName"`
		Labels       map[string]string `json:"labels"`
		OwnerRefs    map[string]string `json:"ownerReferences"`
	} `json:"metadata"`
	Spec struct {
		Affinity        map[string]interface{} `json:"affinity"`
		Containers      map[string]interface{} `json:"containers"`
		RestartPolicy   string                 `json:"restartPolicy"`
		SchedulerName   string                 `json:"schedulerName"`
		SecurityContext struct {
			Sysctls []Sysctl `json:"sysctls"`
		} `json:"securityContext"`
	} `json:"spec"`
}

type K8sContainer added in v1.5.4

type K8sContainer struct {
	Name    string             `yaml:"name"`
	Image   string             `yaml:"image"`
	Ports   []K8sContainerPort `yaml:"ports,omitempty"`
	Command []string           `yaml:"command,omitempty"`
}

type K8sContainerPort added in v1.5.4

type K8sContainerPort struct {
	ContainerPort int `yaml:"containerPort"`
}

type K8sObjectMeta added in v1.5.4

type K8sObjectMeta struct {
	Name      string            `yaml:"name"`
	Namespace string            `yaml:"namespace,omitempty"`
	Labels    map[string]string `yaml:"labels,omitempty"`
}

type K8sPod added in v1.5.4

type K8sPod struct {
	APIVersion string        `yaml:"apiVersion"`
	Kind       string        `yaml:"kind"`
	Metadata   K8sObjectMeta `yaml:"metadata"`
	Spec       K8sPodSpec    `yaml:"spec"`
}

type K8sPodSpec added in v1.5.4

type K8sPodSpec struct {
	Containers []K8sContainer `yaml:"containers"`
}

type KubeConfig added in v1.5.4

type KubeConfig struct {
	APIVersion     string    `yaml:"apiVersion"`
	Clusters       []Cluster `yaml:"clusters"`
	Contexts       []Context `yaml:"contexts"`
	CurrentContext string    `yaml:"current-context"`
	Kind           string    `yaml:"kind"`
	Preferences    struct{}  `yaml:"preferences"`
	Users          []User    `yaml:"users"`
}

type Level added in v1.1.0

type Level uint8
const (
	ERROR Level = iota
	WARNNING
	INFO
	DEBUG
)

type LevelLogger added in v1.1.0

type LevelLogger struct {
	Level Level
	Color bool

	PrintFunc func(format string, v ...interface{})
}

func (*LevelLogger) Close added in v1.1.0

func (l *LevelLogger) Close()

func (*LevelLogger) Debug added in v1.1.0

func (l *LevelLogger) Debug(format string, v ...interface{})

func (*LevelLogger) Error added in v1.1.0

func (l *LevelLogger) Error(format string, v ...interface{})

func (*LevelLogger) Info added in v1.1.0

func (l *LevelLogger) Info(format string, v ...interface{})

func (*LevelLogger) Warn added in v1.1.0

func (l *LevelLogger) Warn(format string, v ...interface{})

type ManagedField added in v1.5.4

type ManagedField struct {
	Manager    string    `json:"manager"`
	Operation  string    `json:"operation"`
	APIVersion string    `json:"apiVersion"`
	Time       time.Time `json:"time"`
	FieldsType string    `json:"fieldsType"`
	FieldsV1   FieldsV1  `json:"fieldsV1"`
}

type MatchField added in v1.5.4

type MatchField struct {
	Key      string   `json:"key"`
	Operator string   `json:"operator"`
	Values   []string `json:"values"`
}

type Metadata added in v1.5.4

type Metadata struct {
	Name              string            `json:"name,omitempty"`
	GenerateName      string            `json:"generateName,omitempty"`
	Namespace         string            `json:"namespace,omitempty"`
	UID               string            `json:"uid,omitempty"`
	ResourceVersion   string            `json:"resourceVersion,omitempty"`
	CreationTimestamp time.Time         `json:"creationTimestamp,omitempty"`
	Labels            map[string]string `json:"labels,omitempty"`
	Annotations       map[string]string `json:"annotations,omitempty"`
}

type MountInfo

type MountInfo struct {
	Device            string
	Fstype            string
	Root              string
	MountPoint        string
	Opts              []string
	Major             string
	Minor             string
	SuperBlockOptions []string
}

MountInfo Sample: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue Sample2: 1659 1605 253:1 /var/lib/kubelet/pods/cc76265f-d44d-4624-91c8-6f6812f85c7e/etc-hosts /etc/hosts rw,noatime - ext4 /dev/vda1 rw Sample3: 52 36 0:47 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:26 - cgroup cgroup rw,memory format: mountID parentID major:minor root mountPoint opts - Fstype device SuperBlockOptions

func GetMountInfo

func GetMountInfo() ([]MountInfo, error)

func (MountInfo) String added in v1.4.0

func (mi MountInfo) String() string

String format: major:minor root mountPoint opts - Fstype device SuperBlockOptions

type NodeAffinity added in v1.5.4

type NodeAffinity struct {
	RequiredDuringSchedulingIgnoredDuringExecution struct {
		NodeSelectorTerms []NodeSelectorTerm `json:"nodeSelectorTerms"`
	} `json:"requiredDuringSchedulingIgnoredDuringExecution"`
}

type NodeSelectorTerm added in v1.5.4

type NodeSelectorTerm struct {
	MatchFields []MatchField `json:"matchFields"`
}

type OwnerReference added in v1.5.4

type OwnerReference struct {
	APIVersion         string `json:"apiVersion"`
	Kind               string `json:"kind"`
	Name               string `json:"name"`
	UID                string `json:"uid"`
	Controller         bool   `json:"controller"`
	BlockOwnerDeletion bool   `json:"blockOwnerDeletion"`
}

type Pod added in v1.5.4

type Pod struct {
	Metadata      Metadata       `json:"metadata"`
	Spec          PodSpec        `json:"spec"`
	Status        PodStatus      `json:"status"`
	ManagedFields []ManagedField `json:"managedFields"`
}

type PodIP added in v1.5.4

type PodIP struct {
	IP string `json:"ip"`
}

type PodList added in v1.5.4

type PodList struct {
	Kind       string   `json:"kind"`
	APIVersion string   `json:"apiVersion"`
	Metadata   Metadata `json:"metadata"`
	Items      []Pod    `json:"items"`
}

type PodSpec added in v1.5.4

type PodSpec struct {
	Containers                    []Container     `json:"containers"`
	RestartPolicy                 string          `json:"restartPolicy"`
	TerminationGracePeriodSeconds int             `json:"terminationGracePeriodSeconds"`
	DNSPolicy                     string          `json:"dnsPolicy"`
	ServiceAccountName            string          `json:"serviceAccountName"`
	NodeName                      string          `json:"nodeName"`
	SecurityContext               SecurityContext `json:"securityContext"`
	Affinity                      Affinity        `json:"affinity"`
	Tolerations                   []Toleration    `json:"tolerations"`
	SchedulerName                 string          `json:"schedulerName"`
}

type PodStatus added in v1.5.4

type PodStatus struct {
	Phase             string            `json:"phase"`
	Conditions        []Condition       `json:"conditions"`
	HostIP            string            `json:"hostIP"`
	PodIP             string            `json:"podIP"`
	PodIPs            []PodIP           `json:"podIPs"`
	StartTime         time.Time         `json:"startTime"`
	ContainerStatuses []ContainerStatus `json:"containerStatuses"`
	QOSClass          string            `json:"qosClass"`
}

type Port added in v1.5.4

type Port struct {
	Name          string `json:"name"`
	HostPort      int    `json:"hostPort"`
	ContainerPort int    `json:"containerPort"`
	Protocol      string `json:"protocol"`
}

type Resources added in v1.5.4

type Resources struct{}

type SecurityContext added in v1.5.4

type SecurityContext struct {
	Sysctls []Sysctl `json:"sysctls"`
}

type Sysctl added in v1.5.4

type Sysctl struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type Toleration added in v1.5.4

type Toleration struct {
	Key               string `json:"key"`
	Operator          string `json:"operator"`
	Effect            string `json:"effect"`
	TolerationSeconds *int64 `json:"tolerationSeconds,omitempty"`
}

type User added in v1.5.4

type User struct {
	Name string   `yaml:"name"`
	User UserInfo `yaml:"user"`
}

type UserInfo added in v1.5.4

type UserInfo struct {
	ClientCertificateData string `yaml:"client-certificate-data"`
	ClientKeyData         string `yaml:"client-key-data"`
}

type Wrapper added in v1.1.0

type Wrapper struct {
	LevelLogger
	// contains filtered or unexported fields
}

func NewStdoutWrapper added in v1.1.0

func NewStdoutWrapper() *Wrapper

func NewWrapper added in v1.1.0

func NewWrapper(writer io.Writer, colorful bool) *Wrapper

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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