329 lines
11 KiB
Go
329 lines
11 KiB
Go
package services
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxJeannieResponseBytes = 2 << 20
|
|
|
|
var kubernetesApplicationName = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$`)
|
|
|
|
type StatusRow struct {
|
|
Status string `json:"status"`
|
|
Area string `json:"area"`
|
|
Check string `json:"check"`
|
|
Summary string `json:"summary"`
|
|
}
|
|
|
|
type ClusterIdentity struct {
|
|
Profile string `json:"profile"`
|
|
Runtime string `json:"runtime"`
|
|
}
|
|
|
|
type StatusSnapshot struct {
|
|
Title string `json:"title"`
|
|
Mode string `json:"mode"`
|
|
Rows []StatusRow `json:"rows"`
|
|
Cluster ClusterIdentity `json:"cluster"`
|
|
CollectedAt string `json:"collectedAt"`
|
|
}
|
|
|
|
type IncidentEvidence struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
Area string `json:"area"`
|
|
Check string `json:"check"`
|
|
Summary string `json:"summary"`
|
|
Output string `json:"output"`
|
|
Cause string `json:"cause"`
|
|
}
|
|
|
|
type IncidentSnapshot struct {
|
|
Scope string `json:"scope"`
|
|
Target string `json:"target"`
|
|
Title string `json:"title"`
|
|
ExecutionID string `json:"executionId"`
|
|
Evidence []IncidentEvidence `json:"evidence"`
|
|
MissingEvidence []string `json:"missingEvidence"`
|
|
NextCommand string `json:"nextCommand"`
|
|
Proposal RemediationProposal `json:"proposal"`
|
|
CollectedAt string `json:"collectedAt"`
|
|
}
|
|
|
|
type RemediationProposal struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
Summary string `json:"summary"`
|
|
Action string `json:"action"`
|
|
RiskLevel string `json:"riskLevel"`
|
|
EvidenceIDs []string `json:"evidenceIds"`
|
|
Preconditions []string `json:"preconditions"`
|
|
RiskNotes []string `json:"riskNotes"`
|
|
Rollback string `json:"rollback"`
|
|
Validation []string `json:"validation"`
|
|
ReadyForApproval bool `json:"readyForApproval"`
|
|
}
|
|
|
|
type JeannieClient struct {
|
|
BaseURL string
|
|
Token string
|
|
HTTPClient *http.Client
|
|
PollInterval time.Duration
|
|
}
|
|
|
|
func NewJeannieClient(baseURL string, token string) *JeannieClient {
|
|
return &JeannieClient{
|
|
BaseURL: strings.TrimRight(baseURL, "/"),
|
|
Token: token,
|
|
HTTPClient: &http.Client{Timeout: 10 * time.Second},
|
|
PollInterval: 250 * time.Millisecond,
|
|
}
|
|
}
|
|
|
|
func NewJeannieClientFromEnv() *JeannieClient {
|
|
return NewJeannieClient(
|
|
os.Getenv("OPSPROOF_JEANNIE_URL"),
|
|
os.Getenv("OPSPROOF_JEANNIE_TOKEN"),
|
|
)
|
|
}
|
|
|
|
func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error) {
|
|
if client.BaseURL == "" || client.Token == "" {
|
|
return StatusSnapshot{}, errors.New("Jeannie API connection is not configured")
|
|
}
|
|
|
|
completed, err := client.execute(ctx, "status", []string{"all", "--json"}, 30*time.Second)
|
|
if err != nil {
|
|
return StatusSnapshot{}, err
|
|
}
|
|
snapshot, err := decodeStatusOutput(completed.Output)
|
|
if err != nil {
|
|
return StatusSnapshot{}, err
|
|
}
|
|
snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339)
|
|
return snapshot, nil
|
|
}
|
|
|
|
func (client *JeannieClient) Doctor(ctx context.Context, scope string, target string) (IncidentSnapshot, error) {
|
|
if scope != "cluster" || !kubernetesApplicationName.MatchString(target) {
|
|
return IncidentSnapshot{}, errors.New("unsupported Doctor target")
|
|
}
|
|
if client.BaseURL == "" || client.Token == "" {
|
|
return IncidentSnapshot{}, errors.New("Jeannie API connection is not configured")
|
|
}
|
|
|
|
completed, err := client.execute(ctx, "doctor", []string{scope, target, "--json"}, 60*time.Second)
|
|
if err != nil {
|
|
return IncidentSnapshot{}, err
|
|
}
|
|
snapshot, err := decodeDoctorOutput(completed.Output)
|
|
if err != nil {
|
|
return IncidentSnapshot{}, err
|
|
}
|
|
snapshot.Scope = scope
|
|
snapshot.Target = target
|
|
snapshot.ExecutionID = completed.ID
|
|
snapshot.NextCommand = "./jeannie doctor cluster " + target + " --details"
|
|
snapshot.Proposal = buildRemediationProposal(snapshot)
|
|
snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339)
|
|
return snapshot, nil
|
|
}
|
|
|
|
func buildRemediationProposal(incident IncidentSnapshot) RemediationProposal {
|
|
proposal := RemediationProposal{
|
|
ID: "proposal-" + incident.ExecutionID,
|
|
Status: "not-needed",
|
|
Summary: "No warning or failing evidence supports a remediation proposal.",
|
|
RiskLevel: "none",
|
|
EvidenceIDs: []string{},
|
|
Preconditions: []string{},
|
|
RiskNotes: []string{},
|
|
Rollback: "No change is proposed, so no rollback is required.",
|
|
Validation: []string{incident.NextCommand, "./jeannie status cluster"},
|
|
}
|
|
for _, evidence := range incident.Evidence {
|
|
if evidence.Status == "warn" || evidence.Status == "fail" {
|
|
proposal.EvidenceIDs = append(proposal.EvidenceIDs, evidence.ID)
|
|
}
|
|
}
|
|
if len(proposal.EvidenceIDs) == 0 {
|
|
return proposal
|
|
}
|
|
|
|
proposal.Status = "blocked"
|
|
proposal.Summary = "Ask the focused Jeannie Doctor and Holmes workflow to diagnose, apply a supported targeted repair, and validate the result."
|
|
proposal.Action = "./jeannie doctor cluster " + incident.Target + " --ai"
|
|
proposal.RiskLevel = "high"
|
|
proposal.Preconditions = []string{
|
|
"Authenticate an authorized operator (not implemented in this slice).",
|
|
"Revalidate that the cited evidence execution is current.",
|
|
"Confirm Jeannie still advertises the exact Doctor command and arguments.",
|
|
"Establish a target-specific backup and rollback procedure.",
|
|
}
|
|
proposal.RiskNotes = []string{
|
|
"The Doctor/Holmes workflow can change Kubernetes runtime state.",
|
|
"AI root-cause hypotheses are not proof and may be incomplete.",
|
|
"The affected application may be temporarily unavailable during repair.",
|
|
}
|
|
proposal.Rollback = "No target-specific rollback has been established automatically. Approval remains disabled until an operator supplies and validates one."
|
|
return proposal
|
|
}
|
|
|
|
func ValidDoctorTarget(scope string, target string) bool {
|
|
return scope == "cluster" && kubernetesApplicationName.MatchString(target)
|
|
}
|
|
|
|
type execution struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
Output string `json:"output"`
|
|
}
|
|
|
|
func (client *JeannieClient) execute(ctx context.Context, command string, args []string, timeout time.Duration) (execution, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
payload, err := json.Marshal(map[string]any{"command": command, "args": args})
|
|
if err != nil {
|
|
return execution{}, fmt.Errorf("encode %s request: %w", command, err)
|
|
}
|
|
var submitted execution
|
|
if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil {
|
|
return execution{}, fmt.Errorf("submit %s request: %w", command, err)
|
|
}
|
|
if submitted.ID == "" {
|
|
return execution{}, errors.New("Jeannie API returned an empty execution ID")
|
|
}
|
|
|
|
for {
|
|
var current execution
|
|
if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, ¤t); err != nil {
|
|
return execution{}, fmt.Errorf("read %s execution: %w", command, err)
|
|
}
|
|
switch current.Status {
|
|
case "queued", "running":
|
|
timer := time.NewTimer(client.PollInterval)
|
|
select {
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return execution{}, fmt.Errorf("wait for %s execution: %w", command, ctx.Err())
|
|
case <-timer.C:
|
|
}
|
|
case "succeeded", "failed":
|
|
return current, nil
|
|
default:
|
|
return execution{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (client *JeannieClient) request(ctx context.Context, method string, path string, body io.Reader, target any) error {
|
|
request, err := http.NewRequestWithContext(ctx, method, client.BaseURL+path, body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
request.Header.Set("Authorization", "Bearer "+client.Token)
|
|
if body != nil {
|
|
request.Header.Set("Content-Type", "application/json")
|
|
}
|
|
|
|
response, err := client.HTTPClient.Do(request)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
|
return fmt.Errorf("Jeannie API returned HTTP %d", response.StatusCode)
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(response.Body, maxJeannieResponseBytes)).Decode(target); err != nil {
|
|
return fmt.Errorf("decode Jeannie API response: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func decodeStatusOutput(output string) (StatusSnapshot, error) {
|
|
start := strings.Index(output, "{")
|
|
if start < 0 {
|
|
return StatusSnapshot{}, errors.New("Jeannie status output did not contain JSON")
|
|
}
|
|
|
|
var snapshot StatusSnapshot
|
|
if err := json.Unmarshal([]byte(output[start:]), &snapshot); err != nil {
|
|
return StatusSnapshot{}, fmt.Errorf("decode Jeannie status output: %w", err)
|
|
}
|
|
if snapshot.Rows == nil {
|
|
return StatusSnapshot{}, errors.New("Jeannie status output did not contain rows")
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func decodeDoctorOutput(output string) (IncidentSnapshot, error) {
|
|
type doctorRow struct {
|
|
Status string `json:"status"`
|
|
Area string `json:"area"`
|
|
Check string `json:"check"`
|
|
Summary string `json:"summary"`
|
|
Detail string `json:"detail"`
|
|
Cause string `json:"cause"`
|
|
}
|
|
var report struct {
|
|
Title string `json:"title"`
|
|
Rows []doctorRow `json:"rows"`
|
|
}
|
|
start := strings.Index(output, "{")
|
|
if start < 0 {
|
|
return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain JSON")
|
|
}
|
|
if err := json.Unmarshal([]byte(output[start:]), &report); err != nil {
|
|
return IncidentSnapshot{}, fmt.Errorf("decode Jeannie Doctor output: %w", err)
|
|
}
|
|
if report.Rows == nil {
|
|
return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain rows")
|
|
}
|
|
|
|
snapshot := IncidentSnapshot{Title: report.Title, Evidence: make([]IncidentEvidence, 0, len(report.Rows))}
|
|
for index, row := range report.Rows {
|
|
snapshot.Evidence = append(snapshot.Evidence, IncidentEvidence{
|
|
ID: fmt.Sprintf("C%02d", index+1),
|
|
Status: row.Status,
|
|
Area: row.Area,
|
|
Check: row.Check,
|
|
Summary: cleanExcerpt(row.Summary, 800),
|
|
Output: cleanExcerpt(row.Detail, 4000),
|
|
Cause: cleanExcerpt(row.Cause, 1200),
|
|
})
|
|
if strings.TrimSpace(row.Detail) == "" {
|
|
snapshot.MissingEvidence = append(snapshot.MissingEvidence, fmt.Sprintf("C%02d has no detailed command output.", index+1))
|
|
}
|
|
}
|
|
if len(report.Rows) == 0 {
|
|
snapshot.MissingEvidence = append(snapshot.MissingEvidence, "Doctor returned no evidence rows.")
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func cleanExcerpt(value string, limit int) string {
|
|
value = strings.Map(func(character rune) rune {
|
|
if character == '\n' || character == '\t' || character >= 32 {
|
|
return character
|
|
}
|
|
return -1
|
|
}, strings.TrimSpace(value))
|
|
characters := []rune(value)
|
|
if len(characters) <= limit {
|
|
return value
|
|
}
|
|
return string(characters[:limit]) + "\n[excerpt truncated by OpsProof]"
|
|
}
|