discovery

package
v0.0.0-...-df0d7b6 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package discovery provides network discovery functionality for solidping.

Index

Constants

View Source
const (
	HealthHealthy   = "healthy"
	HealthUnhealthy = "unhealthy"
	HealthStarting  = "starting"
)

Container health-status words recognized in a container's Status string.

View Source
const (
	// MaxAddresses is the maximum number of addresses that can be scanned in a single job.
	// This corresponds to a /20 IPv4 network. It stays the per-chunk cap for child
	// network_discovery jobs.
	MaxAddresses = 4096

	// MaxScanChunks is the fixed overall ceiling on how many ≤MaxAddresses chunks a single
	// fan-out scan may be split into. 4096 chunks × 4096 addresses = 16,777,216 addresses
	// (exactly one /8). A /7 (8192 chunks) exceeds the ceiling and is rejected.
	MaxScanChunks = 4096

	// ErrCodeRangeTooLarge is the error code returned when the CIDRs expand to more than MaxAddresses.
	ErrCodeRangeTooLarge = "DISCOVERY_RANGE_TOO_LARGE"
)

Variables

View Source
var ErrRangeTooLarge = errors.New("discovery range too large")

ErrRangeTooLarge is returned when the total address count across all CIDRs exceeds MaxAddresses.

Functions

func AddressCount

func AddressCount(cidrs []string) (int, error)

AddressCount returns how many addresses the CIDRs cover, overlaps counted twice: the figure the agents' daily discovery quota is charged with.

func DefaultPortList

func DefaultPortList() []int

DefaultPortList returns the default set of ports to scan when none are specified, derived from the authoritative defaultPorts table.

func SplitCIDRs

func SplitCIDRs(cidrs []string, maxPerChunk int) ([][]string, error)

SplitCIDRs subdivides each input CIDR into ≤ /20 (MaxAddresses) blocks and packs those blocks into chunks whose combined address count does not exceed maxPerChunk. Every returned chunk is itself a valid set of CIDR strings that ValidateCIDRs accepts, so each can drive an independent bounded network_discovery child job. CIDRs larger than maxPerChunk are split; smaller CIDRs are packed together.

func UpsertDiscoveredChecks

func UpsertDiscoveredChecks(
	ctx context.Context,
	db *bun.DB,
	orgUID, jobUID, region string,
	source models.DiscoverySource,
	rows []SuggestedCheck,
	log *slog.Logger,
) error

UpsertDiscoveredChecks inserts or updates the given suggested-check rows for a scan, one DiscoveredCheck per SuggestedCheck. It upserts on (organization_uid, source, group_key, slug, region) so a re-scan updates rows in place rather than duplicating them. region is the scan's private region ("@slug"), or "" when the server itself scanned: the same IP in two networks stays two rows.

It preserves the per-item log-and-continue resilience contract: a single bad row is logged and skipped, never aborting the whole run. It returns an error only for a failure that is not row-specific.

func ValidateCIDRs

func ValidateCIDRs(cidrs []string) error

ValidateCIDRs validates that the given CIDRs are valid and that the total address count does not exceed MaxAddresses.

func ValidatePlanCIDRs

func ValidatePlanCIDRs(cidrs []string) error

ValidatePlanCIDRs validates the CIDRs for a fan-out scan plan. Each CIDR must be a valid IPv4 network, and the total number of ≤MaxAddresses chunks the scan would split into must not exceed MaxScanChunks. It returns ErrRangeTooLarge (wrapped, with an updated message) when the chunk count exceeds the ceiling.

Types

type Config

type Config struct {
	CIDRs       []string `json:"cidrs"`
	Ports       []int    `json:"ports,omitempty"`
	Concurrency int      `json:"concurrency,omitempty"`
	Timeout     string   `json:"timeout,omitempty"`
	// ParentJobUID, when set on a child network_discovery job, is the UID of the
	// network_discovery_plan job that scheduled it. Discovered hosts roll up under
	// the parent so the scan-detail page sees them all under one UID. The
	// synchronous Scan ignores it.
	ParentJobUID string `json:"parentJobUid,omitempty"`
	// SkipSuggestions leaves DiscoveredHost.SuggestedChecks empty: an agent
	// reports raw facts only, the server builds the suggestions itself (spec
	// 2026-10-22-04). Never part of a stored config.
	SkipSuggestions bool `json:"-"`
}

Config is the configuration for a discovery scan.

type ContainerPort

type ContainerPort struct {
	PrivatePort uint16 // container-side port (decides the scheme)
	PublicPort  uint16 // host-published port (what a worker connects to); 0 = not published
	Type        string // "tcp" | "udp"
}

ContainerPort is one port mapping of a discovered container, mirroring the Docker SDK's container.Port. Only ports with PublicPort != 0 (published to the host) are worker-reachable and become HTTP/TCP suggestions.

type ContainerSuggestInput

type ContainerSuggestInput struct {
	ContainerID  string // group_key; the stable upsert identity
	Name         string // group_label; the container name (no leading slash)
	Image        string // metadata
	State        string // metadata (e.g. "running")
	HealthStatus string // metadata (from the status string, may be empty)
	DockerHost   string // the endpoint; the promoted docker check needs it
	HostAddress  string // host IP/hostname a worker reaches published ports on
	Ports        []ContainerPort
}

ContainerSuggestInput carries the fields a container contributes to its suggested-check group.

type DiscoveredContainer

type DiscoveredContainer struct {
	ID           string          // full container ID — the group identity
	Name         string          // container name, leading slash stripped
	Image        string          // image reference
	State        string          // e.g. "running"
	Status       string          // human status, e.g. "Up 2 hours (healthy)"
	HealthStatus string          // parsed from Status when present, else ""
	Ports        []ContainerPort // published + exposed ports
}

DiscoveredContainer is one running container enumerated from a configured Docker-compatible endpoint. It is the engine's output, independent of the job plumbing and of the suggested-check shape, so it can be unit-tested against a fake Docker API.

func ListContainers

func ListContainers(ctx context.Context, endpoint string, timeout time.Duration) ([]DiscoveredContainer, error)

ListContainers connects to one Docker-compatible endpoint and returns its running containers. It builds the client exactly as the docker checker does (host + API-version negotiation), so it works against Docker and Podman sockets and tcp:// endpoints unchanged. The caller is responsible for per-endpoint error handling (log-and-continue).

type DiscoveredHost

type DiscoveredHost struct {
	IP              string           `json:"ip"`
	Hostname        string           `json:"hostname,omitempty"`
	ICMPReachable   bool             `json:"icmpReachable"`
	OpenPorts       []int            `json:"openPorts"`
	SuggestedChecks []SuggestedCheck `json:"suggestedChecks"`
}

DiscoveredHost is a host discovered during a scan.

type DiscoveredWorkload

type DiscoveredWorkload struct {
	UID               string // metadata.uid — the stable group identity
	Kind              string // "Deployment" | "ReplicaSet"
	Namespace         string
	Name              string
	Images            []string
	DesiredReplicas   int32
	ReadyReplicas     int32
	AvailableReplicas int32
	Conditions        []WorkloadCondition

	Endpoints []WorkloadEndpoint
	// contains filtered or unexported fields
}

DiscoveredWorkload is one Deployment or bare ReplicaSet enumerated from a cluster. It is the engine's output, independent of the job plumbing and of the suggested-check shape, so it can be unit-tested against a fake clientset.

func ListWorkloads

func ListWorkloads(
	ctx context.Context,
	client kubernetes.Interface,
	namespaces []string,
	timeout time.Duration,
	log *slog.Logger,
) ([]DiscoveredWorkload, error)

ListWorkloads connects to a cluster (via the provided clientset) and returns its Deployments and bare ReplicaSets, each annotated with any externally reachable endpoints matched from NodePort/LoadBalancer Services and Ingresses.

It is read-only (list/get) and resilient: a per-namespace or per-resource list error is logged and skipped (an RBAC gap on one namespace must not abort the whole scan), so a partial result still surfaces what is visible. When namespaces is empty every visible namespace is scanned (cluster-wide list).

type HostInput

type HostInput struct {
	IP           net.IP
	HostnameHint string // preserved over reverse-DNS if non-empty
}

HostInput is one host to probe, with an optional pre-resolved name. It lets callers (e.g. the Freebox job) feed a fixed host list through the same engine the CIDR scan uses, preserving a known hostname over reverse DNS.

type KubernetesCondition

type KubernetesCondition struct {
	Type   string `json:"type"`
	Status string `json:"status"`
	Reason string `json:"reason,omitempty"`
}

KubernetesCondition is a compact workload status condition (a group-display hint), mirroring discovery.WorkloadCondition.

type KubernetesEndpoint

type KubernetesEndpoint struct {
	Address string // worker-reachable host
	Port    int    // worker-reachable port
	Scheme  string // "http" | "https" | "tcp"
	Source  string // "LoadBalancer" | "NodePort" | "Ingress" (display hint)
}

KubernetesEndpoint is one externally-reachable address discovered for a workload (mirrors discovery.WorkloadEndpoint, decoupled so the suggester is independent of the engine's struct). Address may be empty for a NodePort whose node IP is unknown out-of-cluster — such an endpoint yields no suggestion.

type KubernetesSuggestInput

type KubernetesSuggestInput struct {
	UID               string // group_key; the workload metadata.uid
	ClusterUID        string // the cluster connection the promoted check references
	Kind              string // "Deployment" | "ReplicaSet"
	Namespace         string
	Name              string
	Images            []string
	DesiredReplicas   int32
	ReadyReplicas     int32
	AvailableReplicas int32
	Conditions        []KubernetesCondition
	Endpoints         []KubernetesEndpoint
}

KubernetesSuggestInput carries the fields one workload contributes to its suggested-check group.

type ScanResult

type ScanResult struct {
	Hosts         []DiscoveredHost
	ICMPAvailable bool
}

ScanResult is the outcome of a scan. ICMPAvailable is false when no ICMP socket could be opened and liveness fell back to TCP only.

func Scan

func Scan(ctx context.Context, cfg *Config) (*ScanResult, error)

Scan performs a network discovery scan based on the given configuration. It expands all CIDRs, probes each address with ICMP and TCP, and returns a list of responsive hosts.

func ScanHosts

func ScanHosts(ctx context.Context, hosts []HostInput, cfg *Config) (*ScanResult, error)

ScanHosts probes a fixed list of IPs through the same engine as Scan. cfg.Ports defaults to DefaultPortList(); cfg.CIDRs is ignored. Each result's Hostname comes from the matching HostInput.HostnameHint when non-empty, else from reverse DNS. Only responsive hosts are returned (same semantics as Scan).

type SuggestedCheck

type SuggestedCheck struct {
	GroupKey   string          `json:"groupKey"`
	GroupLabel string          `json:"groupLabel"`
	Name       string          `json:"name"`
	Slug       string          `json:"slug"`
	Type       string          `json:"type"`
	Config     json.RawMessage `json:"config"`
	Metadata   json.RawMessage `json:"metadata,omitempty"` // group hints (denormalized)
}

SuggestedCheck is one fully-formed suggested check within a group. A suggester emits these so promotion is "create these checks" rather than "pick from a host's suggestions". GroupKey/GroupLabel/Metadata are identical across every SuggestedCheck of the same group (the group is a render-time concern).

func SuggestChecks

func SuggestChecks(ip, hostname string, icmpReachable bool, openPorts []int) []SuggestedCheck

SuggestChecks returns suggested checks for one LAN host as grouped rows. Every row shares groupKey=ip, groupLabel=hostname||ip, and metadata={openPorts, icmpReachable}. An ICMP check is emitted when reachable; one check is emitted per open port that maps to a known scheme (via defaultPorts). Slugs are deduped within the group.

func SuggestContainerChecks

func SuggestContainerChecks(input *ContainerSuggestInput) []SuggestedCheck

SuggestContainerChecks returns the grouped suggested checks for one discovered container. Every row shares group_key=containerID, group_label=name, and metadata={image, state, healthStatus, dockerHost}. A `docker` check is always emitted (the HEALTHCHECK mirror); each PUBLISHED port additionally yields an http/https/tcp check on the host-published port. Slugs are deduped within the group.

func SuggestKubernetesChecks

func SuggestKubernetesChecks(input *KubernetesSuggestInput) []SuggestedCheck

SuggestKubernetesChecks returns the grouped suggested checks for one discovered workload. Every row shares group_key=workload uid, group_label="namespace/name", and the denormalized metadata. A primary `kubernetes` replica-health check is always emitted (it covers a workload that exposes nothing externally — the common ClusterIP case); each externally reachable endpoint additionally yields an http/https/tcp check. Slugs are deduped within the group.

type WorkloadCondition

type WorkloadCondition struct {
	Type   string `json:"type"`
	Status string `json:"status"`
	Reason string `json:"reason,omitempty"`
}

WorkloadCondition is a compact, JSON-friendly view of a workload status condition (a group-display hint denormalized onto the suggested-check rows).

type WorkloadEndpoint

type WorkloadEndpoint struct {
	// Address is the worker-reachable host (LB ingress IP/hostname, a node IP,
	// or an Ingress host).
	Address string
	// Port is the port a worker connects to (service port for LB, allocated
	// nodePort for NodePort, 80/443 for an Ingress host).
	Port int
	// Scheme is "http", "https", or "tcp", decided by the port via defaultPorts.
	Scheme string
	// Source describes where the endpoint came from ("LoadBalancer", "NodePort",
	// "Ingress") for display/debugging.
	Source string
}

WorkloadEndpoint is one externally-reachable address discovered for a workload (a NodePort/LoadBalancer Service port or an Ingress host). Pod IPs and ClusterIP services are deliberately excluded — they are not reachable from an out-of-cluster worker.

Directories

Path Synopsis
Package scantypes is the discovery-type registry.
Package scantypes is the discovery-type registry.

Jump to

Keyboard shortcuts

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