static

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NewOperType    = "add"
	UpdateOperType = "update"
)

CMDB自定义的上报类型

View Source
const VERSION = "v1.0"

Variables

View Source
var GetCPUStatus = func(ctx context.Context) (*CPU, error) {
	infos, err := cpu.InfoWithContext(ctx)
	if err != nil {
		return nil, err
	}

	total := len(infos)
	model := ""
	if total == 0 {
		model = "unknown"
	} else {
		model = infos[0].ModelName
	}

	if runtime.GOOS == "windows" {
		n := 0
		for _, info := range infos {
			n += int(info.Cores)
		}
		total = n
	}
	return &CPU{Total: total, Model: model}, nil
}

GetCPUStatus :

View Source
var GetData = func(ctx context.Context, cfg *configs.StaticTaskConfig) (*Report, error) {
	cpu, err := GetCPUStatus(ctx)
	if err != nil {
		logger.Errorf("failed to get cpu status: %v", err)
	}

	mem, err := GetMemoryStatus(ctx)
	if err != nil {
		logger.Errorf("failed to get mem status: %v", err)
	}

	disk, err := GetDiskStatus(ctx)
	if err != nil {
		logger.Errorf("failed to get disk status: %v", err)
	}

	net, err := GetNetStatus(ctx, cfg)
	if err != nil {
		logger.Errorf("failed to get net status: %v", err)
	}

	system, err := GetSystemStatus(ctx)
	if err != nil {
		logger.Errorf("failed to get system status: %v", err)
	}
	logger.Debug("collect report data success")
	return NewReport(cpu, mem, disk, net, system), nil
}

GetData 采集全部静态数据

View Source
var GetDiskStatus = func(ctx context.Context) (*Disk, error) {
	infos, err := disk.PartitionsWithContext(ctx, true)
	if err != nil {
		return nil, err
	}

	diskSet := GetDisks()
	var total uint64 = 0
	repeatMap := make(map[string]bool)
	for _, info := range infos {

		if !diskSet.Exist(info.Device) {

			if !strings.Contains(info.Device, "/dev/mapper") {
				continue
			}

			infoSymlink, err := filepath.EvalSymlinks(info.Device)
			if err != nil {
				logger.Warnf("failed to get file symlink info for: %s", err)
				continue
			}

			infoSymlink = strings.Replace(infoSymlink, "..", "/dev", 1)
			if !diskSet.Exist(infoSymlink) {
				continue
			}
		}

		if _, ok := repeatMap[info.Device]; ok {
			logger.Debugf("get repeat device:%s with mountpoint:%s,skip", info.Device, info.Mountpoint)
			continue
		}
		repeatMap[info.Device] = true

		usage, err := disk.UsageWithContext(ctx, info.Mountpoint)
		if err != nil {
			logger.Warnf("failed to get usage info for: %s", err)
			continue
		}
		total = total + usage.Total

	}
	return &Disk{
		Total: total,
	}, nil
}

GetDiskStatus linux相比windows,多了去除虚拟挂载的逻辑

View Source
var GetDisks = func() common.Set {
	set := common.NewSet()
	path := "/proc/partitions"
	data, err := os.ReadFile(path)
	if err != nil {

		if os.IsNotExist(err) {
			partitions, err := disk.Partitions(true)
			if err != nil {
				return set
			}
			for _, partition := range partitions {
				set.Insert(partition.Device)
			}
			return set
		}
		logger.Errorf("read file:%s,failed,error:%s", path, err)
		return set
	}
	lines := bytes.Split(data, []byte("\n"))
	for idx, line := range lines {

		if len(line) == 0 || idx == 0 {
			continue
		}

		fields := bytes.Fields(line)
		if len(fields) == 4 {
			set.Insert("/dev/" + string(fields[3]))
		}
	}
	return set
}

GetDisks :

View Source
var GetMemoryStatus = func(ctx context.Context) (*Memory, error) {
	info, err := mem.VirtualMemoryWithContext(ctx)
	if err != nil {
		return nil, err
	}
	return &Memory{Total: info.Total}, nil
}

GetMemoryStatus :

View Source
var GetNetStatus = func(ctx context.Context, cfg *configs.StaticTaskConfig) (*Net, error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	virtualInterfaces, err := GetVirtualInterfaceSet()
	if err != nil {
		return nil, err
	}

	whiteList := make(map[string]struct{})
	if cfg != nil && len(cfg.VirtualIfaceWhitelist) > 0 {
		for _, iface := range cfg.VirtualIfaceWhitelist {
			whiteList[iface] = struct{}{}
		}
	}

	items := make([]Interface, 0, len(interfaces))
	for _, inter := range interfaces {

		if virtualInterfaces.Exist(inter.Name) {
			if _, ok := whiteList[inter.Name]; !ok {
				continue
			}
		}

		addrs, err := inter.Addrs()
		if err != nil {
			logger.Warnf("failed to get net addr info for: %s", err)
			continue
		}
		addrList := make([]string, 0, len(addrs))
		for _, addr := range addrs {
			addrList = append(addrList, addr.String())
		}
		item := Interface{
			Addrs: addrList,
			Mac:   inter.HardwareAddr.String(),
			Name:  inter.Name,
		}
		items = append(items, item)
	}
	return &Net{Interface: items}, nil
}

GetNetStatus :

View Source
var GetRandomDuration = func() time.Duration {
	randomSecond := rand.Intn(3600)
	return time.Duration(randomSecond) * time.Second
}

GetRandomDuration 获取一个0~3600秒之间的数字

View Source
var GetSystemStatus = func(ctx context.Context) (*System, error) {
	info, err := host.InfoWithContext(ctx)
	if err != nil {
		return nil, err
	}

	if osSystemType == "" {
		osSystemType = tasks.GetSystemType()
	}

	bkAgentID := GetBKAgentID()
	return &System{
		HostName:  info.Hostname,
		SysType:   osSystemType,
		OS:        info.OS,
		Platform:  info.Platform,
		PlatVer:   info.PlatformVersion,
		BKAgentID: bkAgentID,
		Arch:      info.KernelArch,
	}, nil
}

GetSystemStatus :

Functions

func GetBKAgentID

func GetBKAgentID() string

GetBKAgentID 从gse获取bk_agent_id

func GetVirtualInterfaceSet

func GetVirtualInterfaceSet() (common.Set, error)

GetVirtualInterfaceSet 获取虚拟网卡列表

func New

func New(globalConfig define.Config, taskConfig define.TaskConfig) define.Task

New :

Types

type CPU

type CPU struct {
	Total int
	Model string
}

CPU :

type Disk

type Disk struct {
	Total uint64
}

Disk :

type Event

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

Event :

func NewStaticEvent

func NewStaticEvent(dataid int32, time int64, version string, report *Report, operType string) *Event

NewStaticEvent :

func (*Event) AsMapStr

func (e *Event) AsMapStr() common.MapStr

AsMapStr :

func (*Event) GetType

func (e *Event) GetType() string

func (*Event) IgnoreCMDBLevel

func (e *Event) IgnoreCMDBLevel() bool

IgnoreCMDBLevel :

type Gather

type Gather struct {
	tasks.BaseTask
	// contains filtered or unexported fields
}

Gather :

func (*Gather) Report

func (g *Gather) Report(dataid int32, timestamp int64, e chan<- define.Event, data *Report)

Report 将report转换为event并上报

func (*Gather) Run

func (g *Gather) Run(ctx context.Context, e chan<- define.Event)

Run :

type Interface

type Interface struct {
	Addrs []string
	Mac   string
	Name  string
}

Interface :

type Memory

type Memory struct {
	Total uint64
}

Memory :

type Net

type Net struct {
	Interface []Interface
}

Net :

type Report

type Report struct {
	CPU    *CPU
	Memory *Memory
	Disk   *Disk
	Net    *Net
	System *System
}

Report 主机静态数据集合

func NewReport

func NewReport(cpu *CPU, mem *Memory, disk *Disk, net *Net, system *System) *Report

NewReport :

func (*Report) AsMapStr

func (r *Report) AsMapStr() common.MapStr

AsMapStr :

type Status

type Status struct {
	FirstReport bool
	// contains filtered or unexported fields
}

Status 控制任务状态,负责对任务启动的执行逻辑进行控制

func NewStatus

func NewStatus(checkPeriod, reportPeriod time.Duration) *Status

NewStatus :

func (*Status) ShouldCheck

func (s *Status) ShouldCheck() bool

ShouldCheck :

func (*Status) ShouldReport

func (s *Status) ShouldReport() bool

ShouldReport 周期上报判断

func (*Status) UpdateCheckTime

func (s *Status) UpdateCheckTime(timestamp int64)

UpdateCheckTime :

func (*Status) UpdateReportTime

func (s *Status) UpdateReportTime(timestamp int64)

UpdateReportTime :

type System

type System struct {
	HostName  string
	OS        string
	Platform  string
	PlatVer   string
	SysType   string
	BKAgentID string
	Arch      string
}

System :

Jump to

Keyboard shortcuts

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