detector

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2026 License: MIT Imports: 18 Imported by: 0

README

设备检测模块 (Device Detector)

概述

设备检测模块采用MVP(最小可行产品)设计思路,实现了完全配置驱动的设备自动检测机制。所有检测能力都基于配置文件,实现了高度的模块化和可扩展性。

架构设计

MVP模块化结构
DeviceDetector (主控制器)
├── ConnectivityChecker  (连接检测模块)
├── InfoCollector       (信息采集模块)
├── RuleLoader          (规则匹配模块)
├── VersionExtractor    (版本提取模块)
├── ConfigMatcher       (配置匹配模块)
└── DetectionCache      (缓存模块)
配置驱动

所有检测能力都通过配置文件定义:

  1. 连接检测配置: detect/connectivity_check.yaml

    • 定义支持的协议(SNMP、SSH、TELNET)
    • 定义检测方式和超时设置
  2. 信息采集配置: detect/device_info_collect.yaml

    • 定义采集策略和优先级
    • 定义采集项(OID、命令、超时等)
    • 支持fallback机制
  3. 规则匹配配置: detect/rules/*.yaml

    • 厂商规则:manufacturer_rules.yaml
    • 平台规则:platform_rules.yaml
    • 版本提取规则:内嵌在平台规则中
  4. 配置匹配配置: detect/config_matcher.yaml

    • 定义设备配置匹配策略

模块说明

1. ConnectivityChecker (连接检测模块)

职责: 基于配置文件检测设备支持的协议类型

配置: detect/connectivity_check.yaml

功能:

  • 按优先级检测协议可用性
  • 支持SNMP、SSH、TELNET协议检测
  • 配置驱动的超时和重试设置

示例配置:

protocols:
  - name: SNMP
    enabled: true
    check:
      type: SNMP
      timeout: 5s
    priority: 1
2. InfoCollector (信息采集模块)

职责: 基于配置文件采集设备信息

配置: detect/device_info_collect.yaml

功能:

  • 支持多策略采集(按优先级)
  • 支持SNMP、SSH、TELNET采集
  • 支持fallback机制
  • 支持批量采集(一次采集多个字段)

示例配置:

strategies:
  - name: snmpFirst
    priority: 1
    conditions:
      - protocol: SNMP
        available: true
    collect:
      - name: sysInfo
        method: SNMP
        target: 1.3.6.1.2.1.1
        output: sysDescr, sysName
        snmpConfig:
          indexPositions: [1]
          prefixMap:
            "1": sysDescr
            "5": sysName
3. RuleLoader (规则匹配模块)

职责: 加载和匹配检测规则

配置: detect/rules/manufacturer_rules.yaml, detect/rules/platform_rules.yaml

功能:

  • 加载厂商和平台规则
  • 按优先级和置信度匹配规则
  • 支持正则表达式匹配
  • 支持必填字段验证
4. VersionExtractor (版本提取模块)

职责: 基于规则配置提取版本信息

功能:

  • 从匹配的规则中提取版本
  • 支持多个捕获组
  • 优先返回完整版本格式
5. ConfigMatcher (配置匹配模块)

职责: 匹配设备配置

配置: detect/config_matcher.yaml

功能:

  • 根据检测结果匹配设备配置
  • 支持版本映射
  • 支持fallback策略

使用示例

基本使用
// 创建设备检测器
detector, err := detector.NewDeviceDetector(templatePath)
if err != nil {
    log.Fatal(err)
}

// 执行检测
req := &detector.DetectionRequest{
    IP:            "192.168.1.1",
    SNMPCommunity: "public",
    SSHCredentials: &detector.SSHCredentials{
        Username: "admin",
        Password: "password",
        Port:     22,
    },
}

result, err := detector.Detect(req)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Detected: %s %s %s\n", 
    result.Manufacturer, 
    result.Platform, 
    result.Version)

配置扩展

添加新的采集项

device_info_collect.yaml 中添加新的采集项:

collect:
  - name: customInfo
    method: SNMP
    target: 1.3.6.1.4.1.xxx
    output: customField
    snmpConfig:
      indexPositions: [1]
      prefixMap:
        "1": customField
添加新的检测规则

platform_rules.yaml 中添加新规则:

rules:
  - name: vendor_platform_snmp
    manufacturer: Vendor
    platform: Platform
    priority: 20
    patterns:
      - source: sysDescr
        regex: "(?i)vendor.*platform"
        confidence: 0.9
        required: true
    versionExtract:
      source: sysDescr
      regex: "Version\\s+(\\S+)"

MVP设计原则

  1. 最小可行: 先实现核心功能,保持简单
  2. 配置驱动: 所有能力都通过配置定义,无需修改代码
  3. 模块化: 每个模块职责单一,易于测试和扩展
  4. 可扩展: 通过配置文件轻松添加新设备类型和采集项

未来扩展

  • 支持更多协议(API、Redfish等)
  • 支持自定义采集器插件
  • 支持采集结果验证和校验
  • 支持采集结果缓存策略配置
  • 支持分布式检测

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CachedDetectionResult

type CachedDetectionResult struct {
	Result     *DetectionResult
	DetectedAt time.Time
	ExpiresAt  time.Time
}

CachedDetectionResult 缓存的检测结果

type CatalogDefault

type CatalogDefault struct {
	Manufacturer string `yaml:"manufacturer"`
	Platform     string `yaml:"platform"`
}

CatalogDefault 分类默认值

type CheckConfig

type CheckConfig struct {
	Type    string `yaml:"type"`
	OID     string `yaml:"oid,omitempty"`
	Port    int    `yaml:"port,omitempty"`
	Timeout string `yaml:"timeout"`
	Retries int    `yaml:"retries"`
}

CheckConfig 检测配置

type CollectItem

type CollectItem struct {
	Name       string          `yaml:"name"`
	Type       string          `yaml:"type"`
	Method     string          `yaml:"method"`
	Target     string          `yaml:"target"`
	Timeout    string          `yaml:"timeout"`
	Output     string          `yaml:"output"` // 可以是单个字段或多个字段(逗号分隔)
	Required   bool            `yaml:"required"`
	Fallback   []FallbackItem  `yaml:"fallback,omitempty"`
	SNMPConfig *SNMPItemConfig `yaml:"snmpConfig,omitempty"` // SNMP特定配置
	SSHConfig  *SSHItemConfig  `yaml:"sshConfig,omitempty"`  // SSH特定配置
}

CollectItem 采集项

type CollectStrategy

type CollectStrategy struct {
	Name       string        `yaml:"name"`
	Priority   int           `yaml:"priority"`
	Conditions []Condition   `yaml:"conditions"`
	Collect    []CollectItem `yaml:"collect"`
}

CollectStrategy 采集策略

type CollectedData

type CollectedData map[string]string

CollectedData 采集的数据

type Condition

type Condition struct {
	Protocol  string `yaml:"protocol"`
	Available bool   `yaml:"available"`
}

Condition 条件

type ConfigMatcher

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

ConfigMatcher 配置匹配器

func NewConfigMatcher

func NewConfigMatcher(templatePath string, pipelineService *ps.PipelineService) (*ConfigMatcher, error)

NewConfigMatcher 创建配置匹配器

func (*ConfigMatcher) Match

func (cm *ConfigMatcher) Match(manufacturer, platform, version, catalog string) (*structs.DeviceConfig, error)

Match 匹配设备配置

type ConfigMatcherConfig

type ConfigMatcherConfig struct {
	Name            string             `yaml:"name"`
	Strategies      []MatchingStrategy `yaml:"strategies"`
	VersionMappings []VersionMapping   `yaml:"versionMappings,omitempty"`
	DefaultConfigs  map[string]string  `yaml:"defaultConfigs,omitempty"`
}

ConfigMatcherConfig 配置匹配器配置

type ConnectivityCheckConfig

type ConnectivityCheckConfig struct {
	Name      string           `yaml:"name"`
	Timeout   string           `yaml:"timeout"`
	Protocols []ProtocolConfig `yaml:"protocols"`
}

ConnectivityCheckConfig 连接检测配置

type ConnectivityChecker

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

ConnectivityChecker 连接检测器 MVP: 基于配置文件的连接检测模块

func NewConnectivityChecker

func NewConnectivityChecker(templatePath string) (*ConnectivityChecker, error)

NewConnectivityChecker 创建连接检测器

func (*ConnectivityChecker) Check

func (cc *ConnectivityChecker) Check(req *DetectionRequest) (map[string]bool, error)

Check 检测设备连接性 基于配置文件中的协议配置进行检测

type DetectionCache

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

DetectionCache 检测结果缓存

func NewDetectionCache

func NewDetectionCache(ttl time.Duration) *DetectionCache

NewDetectionCache 创建检测缓存

func (*DetectionCache) CleanExpired

func (dc *DetectionCache) CleanExpired()

CleanExpired 清理过期的缓存项

func (*DetectionCache) Clear

func (dc *DetectionCache) Clear()

Clear 清空缓存

func (*DetectionCache) Get

func (dc *DetectionCache) Get(ip string) (*DetectionResult, bool)

Get 获取缓存的检测结果

func (*DetectionCache) Remove

func (dc *DetectionCache) Remove(ip string)

Remove 移除指定IP的缓存

func (*DetectionCache) Set

func (dc *DetectionCache) Set(ip string, result *DetectionResult)

Set 设置缓存的检测结果

type DetectionRequest

type DetectionRequest struct {
	IP                string
	SNMPCommunity     string
	SSHCredentials    *SSHCredentials
	TelnetCredentials *TelnetCredentials
}

DetectionRequest 检测请求

type DetectionResult

type DetectionResult struct {
	Manufacturer string                `json:"manufacturer"`
	Platform     string                `json:"platform"`
	Version      string                `json:"version"`
	Catalog      string                `json:"catalog"`
	Confidence   float64               `json:"confidence"`
	DeviceConfig *structs.DeviceConfig `json:"device_config,omitempty"`
	Errors       []error               `json:"errors,omitempty"`
	DetectedAt   time.Time             `json:"detected_at"`
}

DetectionResult 检测结果

type DetectionRule

type DetectionRule struct {
	Name           string              `yaml:"name"`
	Manufacturer   string              `yaml:"manufacturer"`
	Platform       string              `yaml:"platform"`
	Catalog        string              `yaml:"catalog"`
	Priority       int                 `yaml:"priority"`
	Patterns       []Pattern           `yaml:"patterns"`
	VersionExtract *VersionExtractRule `yaml:"versionExtract,omitempty"`
	Score          float64             // 运行时计算的匹配分数
}

DetectionRule 检测规则

type DeviceDetector

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

DeviceDetector 设备检测器 MVP: 模块化设计,配置驱动

func NewDeviceDetector

func NewDeviceDetector(templatePath string) (*DeviceDetector, error)

NewDeviceDetector 创建设备检测器 MVP: 初始化所有模块化组件

func (*DeviceDetector) Detect

Detect 执行设备检测 MVP: 使用模块化组件,配置驱动的检测流程

func (*DeviceDetector) VerifyDetection

func (dd *DeviceDetector) VerifyDetection(req *DetectionRequest, result *DetectionResult) error

VerifyDetection 验证检测结果

type DeviceInfoCollectConfig

type DeviceInfoCollectConfig struct {
	Name       string            `yaml:"name"`
	Timeout    string            `yaml:"timeout"`
	Retries    int               `yaml:"retries"`
	Strategies []CollectStrategy `yaml:"strategies"`
}

DeviceInfoCollectConfig 设备信息采集配置

type FallbackItem

type FallbackItem struct {
	Target string `yaml:"target"`
}

FallbackItem 备选采集项

type FallbackPath

type FallbackPath struct {
	PathTemplate string `yaml:"pathTemplate"`
}

FallbackPath 备选路径

type InfoCollector

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

InfoCollector 信息采集器 MVP: 基于配置文件的信息采集模块

func NewInfoCollector

func NewInfoCollector(templatePath string) (*InfoCollector, error)

NewInfoCollector 创建信息采集器

func (*InfoCollector) Collect

func (ic *InfoCollector) Collect(req *DetectionRequest, protocols map[string]bool) (CollectedData, error)

Collect 采集设备信息 基于配置文件中的策略和采集项进行采集

type MatchConfig

type MatchConfig struct {
	Manufacturer string `yaml:"manufacturer"`
	Platform     string `yaml:"platform"`
	Version      string `yaml:"version"`
	Catalog      string `yaml:"catalog"`
}

MatchConfig 匹配配置

type MatchingStrategy

type MatchingStrategy struct {
	Name             string                    `yaml:"name"`
	Priority         int                       `yaml:"priority"`
	Match            MatchConfig               `yaml:"match"`
	PathTemplate     string                    `yaml:"pathTemplate"`
	Fallback         []FallbackPath            `yaml:"fallback,omitempty"`
	DefaultPlatforms map[string]string         `yaml:"defaultPlatforms,omitempty"`
	CatalogDefaults  map[string]CatalogDefault `yaml:"catalogDefaults,omitempty"`
}

MatchingStrategy 匹配策略

type Pattern

type Pattern struct {
	Source     string  `yaml:"source"`
	Regex      string  `yaml:"regex"`
	Confidence float64 `yaml:"confidence"`
	Required   bool    `yaml:"required"`
}

Pattern 匹配模式

type ProtocolConfig

type ProtocolConfig struct {
	Name     string      `yaml:"name"`
	Enabled  bool        `yaml:"enabled"`
	Check    CheckConfig `yaml:"check"`
	Priority int         `yaml:"priority"`
}

ProtocolConfig 协议配置

type ProtocolResult

type ProtocolResult struct {
	Protocol  string
	Available bool
	Error     error
}

ProtocolResult 协议检测结果

type RuleLoader

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

RuleLoader 规则加载器

func NewRuleLoader

func NewRuleLoader(templatePath string) (*RuleLoader, error)

NewRuleLoader 创建规则加载器

func (*RuleLoader) GetMatchedRule

func (rl *RuleLoader) GetMatchedRule(collectedData CollectedData) *DetectionRule

GetMatchedRule 获取匹配的规则(用于版本提取)

func (*RuleLoader) GetRules

func (rl *RuleLoader) GetRules() []DetectionRule

GetRules 获取所有规则

func (*RuleLoader) LoadRules

func (rl *RuleLoader) LoadRules() error

LoadRules 加载所有规则

func (*RuleLoader) MatchRules

func (rl *RuleLoader) MatchRules(collectedData CollectedData) (*DetectionResult, error)

MatchRules 匹配规则

type SNMPItemConfig

type SNMPItemConfig struct {
	IndexPositions      []int             `yaml:"indexPositions"`
	ClassifierPositions []int             `yaml:"classifierPositions"`
	PrefixMap           map[string]string `yaml:"prefixMap"`
}

SNMPItemConfig SNMP采集项配置

type SSHCredentials

type SSHCredentials struct {
	Username   string
	Password   string
	Port       int
	PrivateKey string
}

SSHCredentials SSH凭证

type SSHItemConfig

type SSHItemConfig struct {
	Port    int    `yaml:"port,omitempty"`
	Timeout string `yaml:"timeout,omitempty"`
}

SSHItemConfig SSH采集项配置

type TelnetCredentials

type TelnetCredentials struct {
	Username string
	Password string
	Port     int
}

TelnetCredentials TELNET凭证

type VersionExtractRule

type VersionExtractRule struct {
	Source string   `yaml:"source"`
	Regex  string   `yaml:"regex"`
	Groups []string `yaml:"groups"`
}

VersionExtractRule 版本提取规则

type VersionExtractor

type VersionExtractor struct {
}

VersionExtractor 版本提取器 MVP: 基于规则的版本提取模块

func NewVersionExtractor

func NewVersionExtractor() *VersionExtractor

NewVersionExtractor 创建版本提取器

func (*VersionExtractor) Extract

func (ve *VersionExtractor) Extract(collectedData CollectedData, rule *DetectionRule) string

Extract 提取版本信息 基于规则中的versionExtract配置提取版本

type VersionMapping

type VersionMapping struct {
	Pattern  string `yaml:"pattern"`
	Template string `yaml:"template"`
}

VersionMapping 版本映射

Jump to

Keyboard shortcuts

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