controller

package
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

capabilityscan_controller.go implements autonomous capability scanning. This controller watches CapabilityScanConfig CRs and, when one exists, watches CRD events and triggers capability scans via the MCP server.

Key responsibilities: - Watch CapabilityScanConfig CRs to enable/disable capability scanning - On startup, check if capabilities exist; if not, trigger full scan - Watch CRD create/delete events and trigger targeted scans - Apply include/exclude filters to determine which resources to scan

capabilityscan_debounce.go implements the debounce buffer for capability scanning. The buffer collects CRD events over a configurable time window, then sends them to MCP as a batched request (comma-separated resourceList for scans).

capabilityscan_mcp.go contains the MCP client for capability scanning. This file handles HTTP communication with the MCP server's manageOrgData endpoint for listing, scanning, and deleting capabilities.

remediationpolicy_googlechat.go contains Google Chat notification types and functions for the RemediationPolicy controller. This file handles sending formatted notifications to Google Chat using Card v2 API.

remediationpolicy_mcp.go contains MCP (Model Context Protocol) client code for the RemediationPolicy controller. This file handles communication with the MCP endpoint for AI-powered remediation.

remediationpolicy_notifications.go contains shared notification helpers for the RemediationPolicy controller. This file provides common functionality used by both Slack and Google Chat notification implementations.

remediationpolicy_occurrence.go contains occurrence threshold logic for the RemediationPolicy controller. It tracks how many times a matching event has fired within a sliding time window so that transient (single-occurrence) failures can be filtered out before triggering remediation.

remediationpolicy_ratelimit.go contains rate limiting and cooldown logic for the RemediationPolicy controller. This file handles tracking event processing rates and enforcing cooldown periods.

remediationpolicy_slack.go contains Slack notification types and functions for the RemediationPolicy controller. This file handles sending formatted notifications to Slack using Block Kit.

resourcesync_controller.go implements resource visibility for semantic search. This controller watches ResourceSyncConfig CRs and, when one exists, watches all resources in the cluster and syncs metadata (labels, annotations) to the MCP server for semantic search capabilities.

Note: Status and spec are NOT synced - they are fetched on-demand from the Kubernetes API when needed. This reduces sync traffic since labels rarely change after resource creation.

Key responsibilities: - Watch ResourceSyncConfig CRs to enable/disable resource syncing - Discover all resource types via the Discovery API - Watch CRDs for immediate detection of new/removed custom resources - Create dynamic informers for each discovered GVR - Detect changes to resources (labels only - status changes are ignored) - Batch and send changes to MCP endpoint - Periodic resync for eventual consistency

resourcesync_debounce.go implements the debounce buffer for resource sync. The buffer collects changes over a configurable time window, deduplicates them (last-state-wins), and sends batched updates to the MCP endpoint.

resourcesync_mcp.go contains the MCP client for syncing resources to the MCP server. This file handles HTTP communication, request/response types, and retry logic for the resource sync endpoint.

Index

Constants

View Source
const (
	// ConditionTypeReady indicates whether the GitKnowledgeSource is ready and syncing
	ConditionTypeReady = "Ready"
	// ConditionTypeSynced indicates whether the last sync was successful
	ConditionTypeSynced = "Synced"
	// ConditionTypeScheduled indicates whether scheduling is configured correctly
	ConditionTypeScheduled = "Scheduled"

	// SyncTimeout is the maximum duration for a sync operation
	SyncTimeout = 30 * time.Minute
	// SyncInProgressRequeueAfter is how long to wait before retrying when sync is in progress
	SyncInProgressRequeueAfter = 30 * time.Second

	// GitKnowledgeSourceFinalizer is the finalizer used for cleanup on deletion
	GitKnowledgeSourceFinalizer = "dot-ai.devopstoolkit.live/finalizer"
)
View Source
const (
	// DefaultCloneDepth is used for initial syncs when no lastSyncedCommit exists
	DefaultCloneDepth = 1

	// IncrementalCloneDepth is used for subsequent syncs to increase the chance
	// of having lastSyncedCommit in history for efficient diffing.
	// For 24h sync intervals, most repos won't have more than 50 commits/day.
	IncrementalCloneDepth = 50
)
View Source
const (
	// DefaultMCPMaxRetries is the default number of retry attempts for MCP calls
	DefaultMCPMaxRetries = 3
	// DefaultMCPInitialBackoff is the default initial backoff duration
	DefaultMCPInitialBackoff = 1 * time.Second
	// DefaultMCPMaxBackoff is the default maximum backoff duration
	DefaultMCPMaxBackoff = 30 * time.Second
	// DefaultMCPTimeout is the default HTTP timeout for MCP calls
	DefaultMCPTimeout = 120 * time.Second
)
View Source
const (
	// DefaultCooldownSyncInterval is the default interval for syncing cooldown state
	DefaultCooldownSyncInterval = 60 * time.Second

	// DefaultMinPersistDuration is the minimum cooldown duration to persist
	DefaultMinPersistDuration = 1 * time.Hour

	// Environment variable names for configuration
	EnvCooldownSyncInterval = "COOLDOWN_SYNC_INTERVAL"
	EnvMinPersistDuration   = "COOLDOWN_MIN_PERSIST_DURATION"
)
View Source
const DefaultObjectCooldownMinutes = 5

DefaultObjectCooldownMinutes is the default cooldown period for object-level deduplication. Once remediation is triggered for an object, subsequent events for that object are blocked for this duration. This prevents notification storms from multiple events (e.g., Failed, ErrImagePull, ImagePullBackOff) for the same underlying issue.

View Source
const DefaultOccurrenceWindowSeconds = 300

DefaultOccurrenceWindowSeconds is the default sliding window when an effective MinOccurrences is configured but no window is specified.

View Source
const (
	// DefaultSchedule is used when no schedule is specified
	DefaultSchedule = "@every 24h"
)

Variables

This section is empty.

Functions

func BuildCloneDir added in v0.45.0

func BuildCloneDir(namespace, name, uid string) string

BuildCloneDir constructs the clone directory path for a GitKnowledgeSource. Format: /tmp/knowledge-sources/<namespace>-<name>-<uid[:8]>

func BuildDocumentURI added in v0.45.0

func BuildDocumentURI(repoURL, branch, filePath string) string

BuildDocumentURI constructs the blob URL for a file in a Git repository. Example: https://github.com/acme/platform/blob/main/docs/guide.md

func GetCooldownSyncInterval added in v0.28.0

func GetCooldownSyncInterval() time.Duration

GetCooldownSyncInterval returns the sync interval from env var or default

func GetMinPersistDuration added in v0.28.0

func GetMinPersistDuration() time.Duration

GetMinPersistDuration returns the min persist duration from env var or default

func IsAuthenticationError added in v0.45.0

func IsAuthenticationError(err error) bool

IsAuthenticationError checks if the error indicates an authentication failure.

func IsPolicyPersistenceEnabled added in v0.28.0

func IsPolicyPersistenceEnabled(policy *dotaiv1alpha1.RemediationPolicy) bool

IsPolicyPersistenceEnabled checks if persistence is enabled for a policy. Returns true if persistence is not explicitly disabled (default is enabled).

func IsRepoNotFoundError added in v0.45.0

func IsRepoNotFoundError(err error) bool

IsRepoNotFoundError checks if the error indicates the repository was not found or access was denied (common for private repos without auth).

Types

type CRDChange added in v0.38.0

type CRDChange struct {
	// ResourceID is the capability ID (Kind.group or Kind for core resources)
	ResourceID string
	// IsDelete indicates if this is a delete event
	IsDelete bool
}

CRDChange represents a CRD create/update or delete event

type CapabilityInfo added in v0.38.0

type CapabilityInfo struct {
	ID string `json:"id"`
}

CapabilityInfo represents a capability returned from MCP

type CapabilityScanBuffer added in v0.38.0

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

CapabilityScanBuffer collects CRD changes and flushes them in batches

func NewCapabilityScanBuffer added in v0.38.0

func NewCapabilityScanBuffer(cfg CapabilityScanBufferConfig) *CapabilityScanBuffer

NewCapabilityScanBuffer creates a new capability scan debounce buffer

func (*CapabilityScanBuffer) ChangeQueue added in v0.38.0

func (b *CapabilityScanBuffer) ChangeQueue() chan<- *CRDChange

ChangeQueue returns the channel to send CRD changes to

func (*CapabilityScanBuffer) PendingCount added in v0.38.0

func (b *CapabilityScanBuffer) PendingCount() int

PendingCount returns the total number of pending changes in the buffer

func (*CapabilityScanBuffer) Run added in v0.38.0

func (b *CapabilityScanBuffer) Run(ctx context.Context)

Run starts the debounce buffer processing loop It reads from the change queue and periodically flushes to MCP

type CapabilityScanBufferConfig added in v0.38.0

type CapabilityScanBufferConfig struct {
	Window    time.Duration
	MCPClient *MCPCapabilityScanClient
	OnFlush   func(scans int, deletes int, err error)
}

CapabilityScanBufferConfig holds configuration for creating a CapabilityScanBuffer

type CapabilityScanReconciler added in v0.38.0

type CapabilityScanReconciler struct {
	client.Client
	Scheme   *runtime.Scheme
	Recorder record.EventRecorder

	// RestConfig for creating discovery client
	RestConfig *rest.Config
	// contains filtered or unexported fields
}

CapabilityScanReconciler reconciles CapabilityScanConfig objects

func (*CapabilityScanReconciler) HandleCRDEvent added in v0.38.0

HandleCRDEvent processes CRD create/delete events by queuing them to the debounce buffer

func (*CapabilityScanReconciler) Reconcile added in v0.38.0

Reconcile handles CapabilityScanConfig CR changes

func (*CapabilityScanReconciler) SetupWithManager added in v0.38.0

func (r *CapabilityScanReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager

type ChangeAction added in v0.29.0

type ChangeAction int

ChangeAction represents the type of change detected for a resource

const (
	// ActionUpsert indicates a resource was added or updated
	ActionUpsert ChangeAction = iota
	// ActionDelete indicates a resource was deleted
	ActionDelete
)

type CooldownPersistence added in v0.28.0

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

CooldownPersistence handles per-CR ConfigMap-based state persistence. Each RemediationPolicy CR gets its own ConfigMap with ownerReference for automatic cleanup when the CR is deleted.

Persistence is enabled by default for all policies. Individual policies can opt out by setting spec.persistence.enabled=false.

func NewCooldownPersistence added in v0.28.0

func NewCooldownPersistence(c client.Client, scheme *runtime.Scheme) *CooldownPersistence

NewCooldownPersistence creates a new CooldownPersistence instance

func (*CooldownPersistence) GetDirtyCount added in v0.28.0

func (p *CooldownPersistence) GetDirtyCount() int

GetDirtyCount returns pending dirty entries count (for testing)

func (*CooldownPersistence) Load added in v0.28.0

Load restores cooldown state from all RemediationPolicy ConfigMaps. Only loads state for policies that have persistence enabled. Returns a map with full keys (policy-ns/policy-name/obj-ns/obj-name/reason).

func (*CooldownPersistence) MarkDirty added in v0.28.0

func (p *CooldownPersistence) MarkDirty(fullKey string, cooldownEnd time.Time)

MarkDirty flags a cooldown entry for persistence on the next sync. The caller (controller) should check IsPolicyPersistenceEnabled before calling this.

func (*CooldownPersistence) StartPeriodicSync added in v0.28.0

func (p *CooldownPersistence) StartPeriodicSync(ctx context.Context, getCooldowns func() map[string]time.Time)

StartPeriodicSync starts background periodic syncing

func (*CooldownPersistence) Stop added in v0.28.0

func (p *CooldownPersistence) Stop()

Stop stops periodic sync and performs a final sync. Uses the getCooldowns callback stored during StartPeriodicSync. Creates a fresh context with timeout since the manager context may be cancelled.

func (*CooldownPersistence) Sync added in v0.28.0

func (p *CooldownPersistence) Sync(ctx context.Context, cooldowns map[string]time.Time) error

Sync writes dirty cooldown entries to per-policy ConfigMaps. Only syncs policies that have persistence enabled.

type DebounceBuffer added in v0.29.0

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

DebounceBuffer collects resource changes and flushes them in batches

func NewDebounceBuffer added in v0.29.0

func NewDebounceBuffer(cfg DebounceBufferConfig) *DebounceBuffer

NewDebounceBuffer creates a new debounce buffer

func (*DebounceBuffer) GetMetrics added in v0.29.0

func (b *DebounceBuffer) GetMetrics() DebounceBufferMetrics

GetMetrics returns current buffer metrics

func (*DebounceBuffer) PendingCount added in v0.29.0

func (b *DebounceBuffer) PendingCount() int

PendingCount returns the number of pending changes in the buffer

func (*DebounceBuffer) Run added in v0.29.0

func (b *DebounceBuffer) Run(ctx context.Context)

Run starts the debounce buffer processing loop It reads from the change queue and periodically flushes to MCP

func (*DebounceBuffer) SetLastFlushTimeForTesting added in v0.36.0

func (b *DebounceBuffer) SetLastFlushTimeForTesting(t time.Time)

SetLastFlushTimeForTesting sets the lastFlushTime for testing purposes

func (*DebounceBuffer) SetMCPClient added in v0.29.0

func (b *DebounceBuffer) SetMCPClient(client *MCPResourceSyncClient)

SetMCPClient sets the MCP client (useful for late initialization or testing)

type DebounceBufferConfig added in v0.29.0

type DebounceBufferConfig struct {
	Window      time.Duration
	MCPClient   *MCPResourceSyncClient
	ChangeQueue <-chan *ResourceChange
}

DebounceBufferConfig holds configuration for creating a DebounceBuffer

type DebounceBufferMetrics added in v0.29.0

type DebounceBufferMetrics struct {
	TotalUpserts   int64
	TotalDeletes   int64
	TotalFlushes   int64
	TotalDropped   int64
	PendingChanges int
	LastFlushTime  time.Time
	LastFlushCount int
	// LastError contains the last sync error message (empty if last sync succeeded)
	LastError string
	// LastErrorTime is when the last error occurred
	LastErrorTime time.Time
}

DebounceBufferMetrics holds metrics about the debounce buffer

type DeleteBySourceResponse added in v0.45.0

type DeleteBySourceResponse struct {
	Success bool `json:"success"`
	Data    *struct {
		SourceIdentifier string `json:"sourceIdentifier,omitempty"`
		ChunksDeleted    int    `json:"chunksDeleted,omitempty"`
	} `json:"data,omitempty"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error,omitempty"`
}

DeleteBySourceResponse represents the response from a deleteBySource operation.

type DeleteRequest added in v0.45.0

type DeleteRequest struct {
	Operation string `json:"operation"`
	URI       string `json:"uri"`
}

DeleteRequest represents a request to delete a document from the knowledge base.

type DeleteResponse added in v0.45.0

type DeleteResponse struct {
	Success       bool   `json:"success"`
	Operation     string `json:"operation,omitempty"`
	URI           string `json:"uri,omitempty"`
	ChunksDeleted int    `json:"chunksDeleted,omitempty"`
	Message       string `json:"message,omitempty"`
	Error         *struct {
		Message   string `json:"message"`
		Operation string `json:"operation,omitempty"`
		Hint      string `json:"hint,omitempty"`
	} `json:"error,omitempty"`
}

DeleteResponse represents the response from a delete operation.

type FileChanges added in v0.48.1

type FileChanges struct {
	// Modified contains files that were added or modified
	Modified []string
	// Deleted contains files that were deleted
	Deleted []string
}

FileChanges holds the categorized file changes between two commits.

type GitClient added in v0.45.0

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

GitClient handles Git operations for a repository. It uses a clone-fresh approach: clone, sync, then delete.

func NewGitClient added in v0.45.0

func NewGitClient(cfg GitClientConfig) *GitClient

NewGitClient creates a new GitClient with the given configuration.

func (*GitClient) Cleanup added in v0.45.0

func (g *GitClient) Cleanup() error

Cleanup removes the clone directory and all its contents. This should always be called after sync operations complete.

func (*GitClient) Clone added in v0.45.0

func (g *GitClient) Clone(ctx context.Context) error

Clone clones the repository to the configured directory. This is the primary operation - always clone fresh, never reuse existing clones.

func (*GitClient) GetAllFiles added in v0.45.0

func (g *GitClient) GetAllFiles(ctx context.Context) ([]string, error)

GetAllFiles returns all files in the repository at HEAD. Used for first sync or when change detection falls back.

func (*GitClient) GetChangedFiles added in v0.45.0

func (g *GitClient) GetChangedFiles(ctx context.Context) (*FileChanges, bool, error)

GetChangedFiles returns the categorized file changes between lastSyncedCommit and HEAD. If lastSyncedCommit is empty or not found in history, returns nil indicating that all matching files should be processed (first sync or fallback).

func (*GitClient) GetCloneDir added in v0.45.0

func (g *GitClient) GetCloneDir() string

GetCloneDir returns the directory where the repository is cloned.

func (*GitClient) GetFileContent added in v0.45.0

func (g *GitClient) GetFileContent(ctx context.Context, path string) ([]byte, error)

GetFileContent returns the content of a file at HEAD.

func (*GitClient) GetFileSize added in v0.45.0

func (g *GitClient) GetFileSize(ctx context.Context, path string) (int64, error)

GetFileSize returns the size of a file at HEAD in bytes.

func (*GitClient) GetHeadCommit added in v0.45.0

func (g *GitClient) GetHeadCommit(ctx context.Context) (string, error)

GetHeadCommit returns the SHA of the HEAD commit.

type GitClientConfig added in v0.45.0

type GitClientConfig struct {
	// URL is the HTTPS URL of the Git repository
	URL string
	// Branch is the branch to clone (default: "main")
	Branch string
	// Depth is the shallow clone depth (0 means use default based on sync type)
	Depth int
	// AuthToken is the authentication token for private repositories
	AuthToken string
	// CloneDir is the directory to clone the repository into
	CloneDir string
	// LastSyncedCommit is the commit SHA from the previous sync (empty for first sync)
	LastSyncedCommit string
}

GitClientConfig holds the configuration for creating a GitClient.

type GitKnowledgeSourceReconciler added in v0.45.0

type GitKnowledgeSourceReconciler struct {
	client.Client
	Scheme         *runtime.Scheme
	Recorder       record.EventRecorder
	ScheduleParser *ScheduleParser
}

GitKnowledgeSourceReconciler reconciles a GitKnowledgeSource object. It clones Git repositories, syncs matching documents to MCP, and handles cleanup.

func (*GitKnowledgeSourceReconciler) Reconcile added in v0.45.0

Reconcile handles GitKnowledgeSource reconciliation. For each GitKnowledgeSource, it: 1. Acquires lock to prevent concurrent syncs on same CR 2. Clones the specified Git repository (fresh clone each time) 3. Filters files by path patterns (include/exclude) 4. Detects changed files since last sync using git diff (full sync if spec changed) 5. Syncs changed documents to MCP via manageKnowledge API 6. Updates status with sync results 7. Cleans up clone directory after sync 8. Schedules next sync using RequeueAfter

func (*GitKnowledgeSourceReconciler) SetupWithManager added in v0.45.0

func (r *GitKnowledgeSourceReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

type GoogleChatCard added in v0.18.0

type GoogleChatCard struct {
	Header   *GoogleChatCardHeader `json:"header,omitempty"`
	Sections []GoogleChatSection   `json:"sections,omitempty"`
}

GoogleChatCard represents the card content

type GoogleChatCardHeader added in v0.18.0

type GoogleChatCardHeader struct {
	Title     string `json:"title,omitempty"`
	Subtitle  string `json:"subtitle,omitempty"`
	ImageUrl  string `json:"imageUrl,omitempty"`
	ImageType string `json:"imageType,omitempty"`
}

GoogleChatCardHeader represents the card header

type GoogleChatCardV2 added in v0.18.0

type GoogleChatCardV2 struct {
	CardId string         `json:"cardId,omitempty"`
	Card   GoogleChatCard `json:"card,omitempty"`
}

GoogleChatCardV2 represents a Card v2 structure

type GoogleChatDecoratedText added in v0.18.0

type GoogleChatDecoratedText struct {
	TopLabel string          `json:"topLabel,omitempty"`
	Text     string          `json:"text,omitempty"`
	Icon     *GoogleChatIcon `json:"icon,omitempty"`
}

GoogleChatDecoratedText represents decorated text widget

type GoogleChatDivider added in v0.18.0

type GoogleChatDivider struct{}

GoogleChatDivider represents a divider widget

type GoogleChatIcon added in v0.18.0

type GoogleChatIcon struct {
	KnownIcon string `json:"knownIcon,omitempty"`
}

GoogleChatIcon represents an icon

type GoogleChatMessage added in v0.18.0

type GoogleChatMessage struct {
	CardsV2 []GoogleChatCardV2 `json:"cardsV2,omitempty"`
}

GoogleChatMessage represents the structure of a Google Chat webhook message using Card v2 API

type GoogleChatSection added in v0.18.0

type GoogleChatSection struct {
	Header  string             `json:"header,omitempty"`
	Widgets []GoogleChatWidget `json:"widgets,omitempty"`
}

GoogleChatSection represents a section in the card

type GoogleChatTextParagraph added in v0.18.0

type GoogleChatTextParagraph struct {
	Text string `json:"text,omitempty"`
}

GoogleChatTextParagraph represents a text paragraph widget

type GoogleChatWidget added in v0.18.0

type GoogleChatWidget struct {
	DecoratedText *GoogleChatDecoratedText `json:"decoratedText,omitempty"`
	TextParagraph *GoogleChatTextParagraph `json:"textParagraph,omitempty"`
	Divider       *GoogleChatDivider       `json:"divider,omitempty"`
}

GoogleChatWidget represents a widget in a section

type IngestRequest added in v0.45.0

type IngestRequest struct {
	Operation string            `json:"operation"`
	URI       string            `json:"uri"`
	Content   string            `json:"content"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

IngestRequest represents a request to ingest a document into the knowledge base.

type IngestResponse added in v0.45.0

type IngestResponse struct {
	Success       bool     `json:"success"`
	Operation     string   `json:"operation,omitempty"`
	ChunksCreated int      `json:"chunksCreated,omitempty"`
	ChunkIDs      []string `json:"chunkIds,omitempty"`
	URI           string   `json:"uri,omitempty"`
	Message       string   `json:"message,omitempty"`
	Error         *struct {
		Message   string `json:"message"`
		Operation string `json:"operation,omitempty"`
		Hint      string `json:"hint,omitempty"`
	} `json:"error,omitempty"`
}

IngestResponse represents the response from an ingest operation.

type MCPCapabilityScanClient added in v0.38.0

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

MCPCapabilityScanClient handles HTTP communication with the MCP capability scan endpoint

func NewMCPCapabilityScanClient added in v0.38.0

func NewMCPCapabilityScanClient(cfg MCPCapabilityScanClientConfig) *MCPCapabilityScanClient

NewMCPCapabilityScanClient creates a new MCP capability scan client

func (*MCPCapabilityScanClient) DeleteCapability added in v0.38.0

func (c *MCPCapabilityScanClient) DeleteCapability(ctx context.Context, id string) error

DeleteCapability deletes a capability by ID

func (*MCPCapabilityScanClient) ListCapabilities added in v0.38.0

func (c *MCPCapabilityScanClient) ListCapabilities(ctx context.Context) (int, error)

ListCapabilities checks how many capabilities exist in the database

func (*MCPCapabilityScanClient) ListCapabilityIDs added in v0.38.0

func (c *MCPCapabilityScanClient) ListCapabilityIDs(ctx context.Context) ([]string, error)

ListCapabilityIDs returns all capability IDs from the database

func (*MCPCapabilityScanClient) TriggerFullScan added in v0.38.0

func (c *MCPCapabilityScanClient) TriggerFullScan(ctx context.Context) error

TriggerFullScan triggers a full cluster capability scan

func (*MCPCapabilityScanClient) TriggerScan added in v0.38.0

func (c *MCPCapabilityScanClient) TriggerScan(ctx context.Context, resourceList string) error

TriggerScan triggers a targeted scan for specific resources

type MCPCapabilityScanClientConfig added in v0.38.0

type MCPCapabilityScanClientConfig struct {
	Endpoint            string
	Collection          string
	HTTPClient          *http.Client
	K8sClient           client.Client
	AuthSecretRef       dotaiv1alpha1.SecretReference
	AuthSecretNamespace string
	MaxRetries          *int // Pointer to distinguish "not set" (nil->default 3) from "set to 0"
	InitialBackoff      time.Duration
	MaxBackoff          time.Duration
}

MCPCapabilityScanClientConfig holds configuration for creating an MCPCapabilityScanClient

type MCPKnowledgeClient added in v0.45.0

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

MCPKnowledgeClient handles communication with the MCP manageKnowledge API.

func NewMCPKnowledgeClient added in v0.45.0

func NewMCPKnowledgeClient(cfg MCPKnowledgeClientConfig) *MCPKnowledgeClient

NewMCPKnowledgeClient creates a new MCPKnowledgeClient with the given configuration.

func (*MCPKnowledgeClient) DeleteBySource added in v0.45.0

func (c *MCPKnowledgeClient) DeleteBySource(ctx context.Context, deleteURL string) (*DeleteBySourceResponse, error)

DeleteBySource removes all documents with a given sourceIdentifier from MCP. The deleteURL should be the full URL including the encoded sourceIdentifier. Example: http://mcp-server:3456/api/v1/knowledge/source/default%2Fplatform-docs This is idempotent - deleting non-existent source succeeds with chunksDeleted=0.

func (*MCPKnowledgeClient) DeleteDocument added in v0.45.0

func (c *MCPKnowledgeClient) DeleteDocument(ctx context.Context, uri string) (*DeleteResponse, error)

DeleteDocument removes a document from the MCP knowledge base by URI. It returns the response and any error encountered. The operation is idempotent - deleting a non-existent document succeeds with chunksDeleted=0.

func (*MCPKnowledgeClient) IngestDocument added in v0.45.0

func (c *MCPKnowledgeClient) IngestDocument(ctx context.Context, uri, content string, metadata map[string]string) (*IngestResponse, error)

IngestDocument sends a document to the MCP knowledge base. It returns the response and any error encountered. The operation is retried with exponential backoff on transient failures.

type MCPKnowledgeClientConfig added in v0.45.0

type MCPKnowledgeClientConfig struct {
	// Endpoint is the full URL for the manageKnowledge API
	// Example: http://mcp-server.dot-ai.svc:3456/api/v1/tools/manageKnowledge
	Endpoint string
	// AuthToken is the bearer token for authentication (optional)
	AuthToken string
	// HTTPClient is the HTTP client to use (optional, uses default if nil)
	HTTPClient *http.Client
	// MaxRetries is the maximum number of retry attempts (optional, default: 3)
	MaxRetries *int
	// InitialBackoff is the initial backoff duration (optional, default: 1s)
	InitialBackoff time.Duration
	// MaxBackoff is the maximum backoff duration (optional, default: 30s)
	MaxBackoff time.Duration
	// Timeout is the HTTP timeout duration (optional, default: 120s)
	Timeout time.Duration
}

MCPKnowledgeClientConfig holds the configuration for creating an MCPKnowledgeClient.

type MCPResourceSyncClient added in v0.29.0

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

MCPResourceSyncClient handles HTTP communication with the MCP resource sync endpoint

func NewMCPResourceSyncClient added in v0.29.0

func NewMCPResourceSyncClient(cfg MCPResourceSyncClientConfig) *MCPResourceSyncClient

NewMCPResourceSyncClient creates a new MCP resource sync client

func (*MCPResourceSyncClient) Resync added in v0.29.0

func (c *MCPResourceSyncClient) Resync(ctx context.Context, allResources []*ResourceData) (*SyncResponse, error)

Resync sends a full resync request to the MCP endpoint MCP will diff against Qdrant and handle deletions of orphaned records

func (*MCPResourceSyncClient) SyncResources added in v0.29.0

func (c *MCPResourceSyncClient) SyncResources(ctx context.Context, upserts []*ResourceData, deletes []*ResourceIdentifier) (*SyncResponse, error)

SyncResources sends upserts and deletes to the MCP endpoint

type MCPResourceSyncClientConfig added in v0.29.0

type MCPResourceSyncClientConfig struct {
	Endpoint            string
	HTTPClient          *http.Client
	K8sClient           client.Client
	AuthSecretRef       dotaiv1alpha1.SecretReference
	AuthSecretNamespace string
	MaxRetries          *int // Pointer to distinguish "not set" (nil->default 3) from "set to 0"
	InitialBackoff      time.Duration
	MaxBackoff          time.Duration
}

MCPResourceSyncClientConfig holds configuration for creating an MCPResourceSyncClient

type ManageOrgDataRequest added in v0.38.0

type ManageOrgDataRequest struct {
	DataType     string `json:"dataType"`
	Operation    string `json:"operation"`
	Collection   string `json:"collection,omitempty"`
	Mode         string `json:"mode,omitempty"`         // For scan operation: "full"
	ResourceList string `json:"resourceList,omitempty"` // For targeted scan
	ID           string `json:"id,omitempty"`           // For get/delete operations
	Limit        int    `json:"limit,omitempty"`        // For list operation
}

ManageOrgDataRequest is the request body for POST /api/v1/tools/manageOrgData

type ManageOrgDataResponse added in v0.38.0

type ManageOrgDataResponse struct {
	Success bool `json:"success"`
	Data    *struct {
		Result *struct {
			Success      bool             `json:"success"`
			Status       string           `json:"status,omitempty"`
			Message      string           `json:"message,omitempty"`
			Capabilities []CapabilityInfo `json:"capabilities,omitempty"`
			TotalCount   int              `json:"totalCount,omitempty"`
			Operation    string           `json:"operation,omitempty"`
		} `json:"result,omitempty"`
	} `json:"data,omitempty"`
	Error *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error,omitempty"`
}

ManageOrgDataResponse is the response from POST /api/v1/tools/manageOrgData

func (*ManageOrgDataResponse) GetCapabilityIDs added in v0.38.0

func (r *ManageOrgDataResponse) GetCapabilityIDs() []string

GetCapabilityIDs returns the IDs of capabilities from a list response

func (*ManageOrgDataResponse) GetErrorMessage added in v0.38.0

func (r *ManageOrgDataResponse) GetErrorMessage() string

GetErrorMessage extracts error message from the response

func (*ManageOrgDataResponse) GetTotalCount added in v0.38.0

func (r *ManageOrgDataResponse) GetTotalCount() int

GetTotalCount returns the total count of capabilities from a list response

type McpResponse

type McpResponse struct {
	Success bool `json:"success"`
	Data    *struct {
		Result        map[string]interface{} `json:"result"`
		Tool          string                 `json:"tool"`
		ExecutionTime float64                `json:"executionTime"`
	} `json:"data,omitempty"`
	Error *struct {
		Code    string                 `json:"code"`
		Message string                 `json:"message"`
		Details map[string]interface{} `json:"details,omitempty"`
	} `json:"error,omitempty"`
	Meta *struct {
		Timestamp string `json:"timestamp"`
		RequestId string `json:"requestId"`
		Version   string `json:"version"`
	} `json:"meta,omitempty"`
}

McpResponse represents the response from MCP remediate endpoint Based on the actual OpenAPI schema: RestApiResponse + ToolExecutionResponse

func (*McpResponse) GetErrorMessage

func (r *McpResponse) GetErrorMessage() string

GetErrorMessage extracts error message from the MCP response

func (*McpResponse) GetResultMessage

func (r *McpResponse) GetResultMessage() string

GetResultMessage extracts a meaningful message from the MCP response

type PatternMatcher added in v0.45.0

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

PatternMatcher handles file path matching using glob patterns. It supports include patterns (files to sync) and exclude patterns (files to skip even if they match include patterns).

func NewPatternMatcher added in v0.45.0

func NewPatternMatcher(includes, excludes []string) *PatternMatcher

NewPatternMatcher creates a new PatternMatcher with the given include and exclude patterns. Patterns use doublestar syntax:

  • "*" matches any sequence of non-separator characters
  • "**" matches any sequence of characters including separators
  • "?" matches any single non-separator character

Examples:

  • "docs/**/*.md" matches all .md files under docs/
  • "README.md" matches only README.md at the root
  • "*.go" matches all .go files at the root level only

func (*PatternMatcher) FilterFiles added in v0.45.0

func (p *PatternMatcher) FilterFiles(files []string) []string

FilterFiles returns a new slice containing only the paths that match the include patterns and do not match any exclude patterns.

func (*PatternMatcher) Matches added in v0.45.0

func (p *PatternMatcher) Matches(path string) bool

Matches returns true if the path matches any include pattern and does not match any exclude pattern. Paths should use forward slashes as separators (Unix-style).

func (*PatternMatcher) MatchingFiles added in v0.45.0

func (p *PatternMatcher) MatchingFiles(basePath string) ([]string, error)

MatchingFiles walks a directory tree and returns all file paths that match the include patterns and do not match any exclude patterns. The basePath is stripped from the returned paths.

type RemediationPolicyReconciler

type RemediationPolicyReconciler struct {
	client.Client
	Scheme     *runtime.Scheme
	Recorder   record.EventRecorder
	HttpClient *http.Client

	// CooldownPersistence handles persisting cooldown state to ConfigMaps
	// to survive pod restarts
	CooldownPersistence *CooldownPersistence
	// contains filtered or unexported fields
}

RemediationPolicyReconciler reconciles a RemediationPolicy object

func (*RemediationPolicyReconciler) Reconcile

Reconcile processes both Events and RemediationPolicies. For Events: checks them against RemediationPolicy filters and processes matches. For RemediationPolicies: initializes/updates their status and conditions.

For more details, check Reconcile and its Result here: - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/reconcile

func (*RemediationPolicyReconciler) SetupWithManager

func (r *RemediationPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

type ResourceChange added in v0.29.0

type ResourceChange struct {
	// Action is either ActionUpsert or ActionDelete
	Action ChangeAction
	// Data contains the resource data (nil for deletes)
	Data *ResourceData
	// ID is the internal resource identifier used for debounce buffer deduplication
	// Format: namespace:apiVersion:kind:name (or _cluster:apiVersion:kind:name for cluster-scoped)
	ID string
	// DeleteIdentifier contains the fields MCP needs to construct the ID for delete operations
	// Only populated for ActionDelete
	DeleteIdentifier *ResourceIdentifier
}

ResourceChange represents a change to be synced to MCP

type ResourceData added in v0.29.0

type ResourceData struct {
	// Namespace of the resource ("_cluster" for cluster-scoped resources)
	Namespace string `json:"namespace"`
	// Name of the resource
	Name string `json:"name"`
	// Kind of the resource (e.g., "Deployment", "Pod")
	Kind string `json:"kind"`
	// APIVersion including group (e.g., "apps/v1", "v1")
	APIVersion string `json:"apiVersion"`
	// Labels from the resource
	Labels map[string]string `json:"labels,omitempty"`
	// Annotations from the resource (selected ones, not all)
	Annotations map[string]string `json:"annotations,omitempty"`
	// CreatedAt is when the resource was created
	CreatedAt time.Time `json:"createdAt"`
	// UpdatedAt is when this data was last updated (now)
	UpdatedAt time.Time `json:"updatedAt"`
}

ResourceData contains the data extracted from a Kubernetes resource for syncing to MCP Note: ID is not included - MCP constructs it from namespace/apiVersion/kind/name

type ResourceIdentifier added in v0.31.0

type ResourceIdentifier struct {
	// Namespace of the resource ("_cluster" for cluster-scoped resources)
	Namespace string `json:"namespace"`
	// Name of the resource
	Name string `json:"name"`
	// Kind of the resource (e.g., "Deployment", "Pod")
	Kind string `json:"kind"`
	// APIVersion including group (e.g., "apps/v1", "v1")
	APIVersion string `json:"apiVersion"`
}

ResourceIdentifier contains the fields needed to identify a resource for deletion MCP uses these fields to construct the ID for the delete operation

type ResourceSyncReconciler added in v0.29.0

type ResourceSyncReconciler struct {
	client.Client
	Scheme     *runtime.Scheme
	Recorder   record.EventRecorder
	RestConfig *rest.Config

	// HttpClient for MCP communication
	HttpClient *http.Client
	// contains filtered or unexported fields
}

ResourceSyncReconciler reconciles ResourceSyncConfig objects and manages dynamic resource watching based on their configuration

func (*ResourceSyncReconciler) GetActiveConfigCount added in v0.29.0

func (r *ResourceSyncReconciler) GetActiveConfigCount() int

GetActiveConfigCount returns the number of active configs (for testing)

func (*ResourceSyncReconciler) GetWatchedGVRs added in v0.29.0

func (r *ResourceSyncReconciler) GetWatchedGVRs(configName string) []schema.GroupVersionResource

GetWatchedGVRs returns the list of watched GVRs for a config (for testing)

func (*ResourceSyncReconciler) Reconcile added in v0.29.0

func (r *ResourceSyncReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile handles ResourceSyncConfig CR changes

func (*ResourceSyncReconciler) SetupWithManager added in v0.29.0

func (r *ResourceSyncReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager

type ScheduleParser added in v0.45.0

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

ScheduleParser parses cron and interval expressions for GitKnowledgeSource scheduling.

func NewScheduleParser added in v0.45.0

func NewScheduleParser() *ScheduleParser

NewScheduleParser creates a new ScheduleParser with support for standard cron expressions and @every intervals.

func (*ScheduleParser) NextSyncDuration added in v0.45.0

func (p *ScheduleParser) NextSyncDuration(schedule string, lastSync time.Time) (time.Duration, time.Time, error)

NextSyncDuration calculates the duration until the next sync based on the schedule and the last sync time. Returns: - duration: time until next sync (for RequeueAfter) - nextTime: the absolute time of the next sync (for status.NextScheduledSync) - error: if schedule parsing fails

If lastSync is zero (first sync), uses current time as the reference.

func (*ScheduleParser) ParseSchedule added in v0.45.0

func (p *ScheduleParser) ParseSchedule(schedule string) (cron.Schedule, error)

ParseSchedule parses a schedule expression and returns a cron.Schedule. Supports standard cron expressions (e.g., "0 3 * * *") and intervals (e.g., "@every 24h"). Returns an error if the schedule is invalid.

func (*ScheduleParser) ValidateSchedule added in v0.45.0

func (p *ScheduleParser) ValidateSchedule(schedule string) error

ValidateSchedule checks if a schedule expression is valid without calculating next time. Returns nil if valid, error with details if invalid.

type SlackAttachment

type SlackAttachment struct {
	Color     string       `json:"color,omitempty"`
	Title     string       `json:"title,omitempty"`
	Text      string       `json:"text,omitempty"`
	Fields    []SlackField `json:"fields,omitempty"`
	Footer    string       `json:"footer,omitempty"`
	Timestamp int64        `json:"ts,omitempty"`
	Blocks    []SlackBlock `json:"blocks,omitempty"`
}

SlackAttachment represents a Slack message attachment for rich formatting (legacy)

type SlackBlock

type SlackBlock struct {
	Type      string              `json:"type"`
	Text      *SlackBlockText     `json:"text,omitempty"`
	Elements  []SlackBlockElement `json:"elements,omitempty"`
	Fields    []SlackBlockText    `json:"fields,omitempty"`
	Accessory interface{}         `json:"accessory,omitempty"`
}

SlackBlock represents a Slack Block Kit block

type SlackBlockElement

type SlackBlockElement struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

SlackBlockElement represents an element in a Block Kit block

type SlackBlockText

type SlackBlockText struct {
	Type  string `json:"type"` // "plain_text" or "mrkdwn"
	Text  string `json:"text"`
	Emoji *bool  `json:"emoji,omitempty"`
}

SlackBlockText represents text in a Block Kit block

type SlackField

type SlackField struct {
	Title string `json:"title"`
	Value string `json:"value"`
	Short bool   `json:"short"`
}

SlackField represents a field in a Slack attachment (legacy)

type SlackMessage

type SlackMessage struct {
	Channel     string            `json:"channel,omitempty"`
	Username    string            `json:"username,omitempty"`
	IconEmoji   string            `json:"icon_emoji,omitempty"`
	Attachments []SlackAttachment `json:"attachments,omitempty"` // Attachments with Block Kit blocks
}

SlackMessage represents the structure of a Slack webhook message

type SolutionReconciler

type SolutionReconciler struct {
	client.Client
	Scheme   *runtime.Scheme
	Recorder record.EventRecorder
}

SolutionReconciler reconciles a Solution object

func (*SolutionReconciler) Reconcile

func (r *SolutionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile reconciles a Solution custom resource It updates the status based on the current state of child resources

For more details, check Reconcile and its Result here: - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/reconcile

func (*SolutionReconciler) SetupWithManager

func (r *SolutionReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

type SyncFailure added in v0.29.0

type SyncFailure struct {
	ID    string `json:"id"`
	Error string `json:"error"`
}

SyncFailure represents a single resource that failed to sync

type SyncRequest added in v0.29.0

type SyncRequest struct {
	// Upserts contains resources to create or update
	Upserts []*ResourceData `json:"upserts,omitempty"`
	// Deletes contains resource identifiers to delete
	// MCP constructs the ID from namespace/apiVersion/kind/name
	Deletes []*ResourceIdentifier `json:"deletes,omitempty"`
	// IsResync indicates this is a full resync (MCP should diff against Qdrant)
	IsResync bool `json:"isResync,omitempty"`
}

SyncRequest is the request body for POST /api/v1/resources/sync

type SyncResponse added in v0.29.0

type SyncResponse struct {
	Success bool `json:"success"`
	Data    *struct {
		Upserted int `json:"upserted"`
		Deleted  int `json:"deleted"`
	} `json:"data,omitempty"`
	Error *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
		Details *struct {
			Upserted int           `json:"upserted,omitempty"`
			Deleted  int           `json:"deleted,omitempty"`
			Failures []SyncFailure `json:"failures,omitempty"`
		} `json:"details,omitempty"`
	} `json:"error,omitempty"`
	Meta *struct {
		Timestamp string `json:"timestamp"`
		RequestId string `json:"requestId"`
		Version   string `json:"version"`
	} `json:"meta,omitempty"`
}

SyncResponse is the response from POST /api/v1/resources/sync Follows MCP's RestApiResponse pattern

func (*SyncResponse) GetErrorMessage added in v0.29.0

func (r *SyncResponse) GetErrorMessage() string

GetErrorMessage extracts error message from the response

func (*SyncResponse) GetFailures added in v0.29.0

func (r *SyncResponse) GetFailures() []SyncFailure

GetFailures returns the list of individual resource failures

func (*SyncResponse) GetSuccessCounts added in v0.29.0

func (r *SyncResponse) GetSuccessCounts() (upserted, deleted int)

GetSuccessCounts returns the number of upserted and deleted resources

Jump to

Keyboard shortcuts

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