Files
Reims-Go/internal/app/diagnostics_flow.go
T

537 lines
17 KiB
Go

package app
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
type DiagnosticsExportResult struct {
Path string `json:"path"`
FileName string `json:"file_name"`
SizeBytes int64 `json:"size_bytes"`
TargetLabel string `json:"target_label"`
IncludedFiles []string `json:"included_files"`
SummaryText string `json:"summary_text"`
Findings []host.DiagnosticFinding `json:"findings"`
CanCopyFile bool `json:"can_copy_file"`
}
type diagnosticsBundle struct {
HostReport host.Report
Optimizations []host.Optimization
Runtime *rt.Installed
VMDetail any // legacy test/export payload; production uses VMInfo
VMInfo *driver.VMInfo
SerialLog string
SerialTruncated bool
QEMULog string
QEMUTruncated bool
AppLogs []string
PluginDiagnostics []plugin.DiagnosticsEntry
}
func writeDiagnosticsZip(reportsDir, label string, generatedAt time.Time, b diagnosticsBundle) (_ DiagnosticsExportResult, err error) {
if err := os.MkdirAll(reportsDir, 0o755); err != nil {
return DiagnosticsExportResult{}, err
}
f, err := os.CreateTemp(reportsDir, fmt.Sprintf("reims-go-diag-%s-%s-*.zip", label, generatedAt.Local().Format("20060102-150405")))
if err != nil {
return DiagnosticsExportResult{}, err
}
defer func() {
if err != nil {
err = errors.Join(err, os.Remove(f.Name()))
}
}()
zw := zip.NewWriter(f)
result, writeErr := writeDiagnosticsEntries(zw, label, generatedAt, b)
if err := errors.Join(writeErr, zw.Close(), f.Close()); err != nil {
return DiagnosticsExportResult{}, err
}
info, err := os.Stat(f.Name())
if err != nil {
return DiagnosticsExportResult{}, err
}
result.Path = f.Name()
result.FileName = info.Name()
result.SizeBytes = info.Size()
result.CanCopyFile = host.CanCopyFileToClipboard()
return result, nil
}
func writeDiagnosticsEntries(zw *zip.Writer, label string, generatedAt time.Time, b diagnosticsBundle) (DiagnosticsExportResult, error) {
appLogs := b.AppLogs
if b.VMInfo != nil {
appLogs = filterAppLogsForVM(appLogs, b.VMInfo.Ref())
}
result := DiagnosticsExportResult{
TargetLabel: label,
IncludedFiles: []string{},
Findings: host.AnalyzeDiagnostics(b.HostReport, b.QEMULog, b.SerialLog, appLogs),
}
redact := diagnosticsRedactor(b)
for i := range result.Findings {
result.Findings[i].Detail = redact(result.Findings[i].Detail)
}
addFile := func(name, content string) error {
w, err := zw.Create(name)
if err != nil {
return err
}
if _, err := w.Write([]byte(content)); err != nil {
return err
}
result.IncludedFiles = append(result.IncludedFiles, name)
return nil
}
addJSON := func(name string, v any) error {
raw, err := json.Marshal(v)
if err != nil {
return err
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return err
}
raw, err = json.MarshalIndent(redactDiagnosticsJSON(value, redact), "", " ")
if err != nil {
return err
}
return addFile(name, string(raw)+"\n")
}
rep := b.HostReport
rep.GPUs = slices.Clone(rep.GPUs)
for i := range rep.GPUs {
if rep.GPUs[i].VulkanICD != "" {
rep.GPUs[i].VulkanICD = "[redacted]"
}
}
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD != "" {
gpu := *rep.RecommendedGPU
gpu.VulkanICD = "[redacted]"
rep.RecommendedGPU = &gpu
}
hostSummary := map[string]any{
"generated_at": generatedAt.UTC().Format(time.RFC3339),
"host": rep,
"optimizations": b.Optimizations,
}
if code, detail := host.DiagnoseGPULog(b.QEMULog); code != "" {
hostSummary["gpu_diagnosis"] = map[string]string{
"code": code,
"detail": detail,
}
}
if err := addJSON("host-report.json", hostSummary); err != nil {
return DiagnosticsExportResult{}, err
}
if b.Runtime != nil {
if err := addJSON("runtime-manifest.json", b.Runtime.Manifest); err != nil {
return DiagnosticsExportResult{}, err
}
}
if b.VMDetail != nil {
if err := addJSON("vm-detail.json", b.VMDetail); err != nil {
return DiagnosticsExportResult{}, err
}
}
if b.VMInfo != nil {
if err := addJSON("vm-info.json", b.VMInfo); err != nil {
return DiagnosticsExportResult{}, err
}
}
if strings.TrimSpace(b.SerialLog) != "" {
if err := addFile("serial.log", redact(b.SerialLog)); err != nil {
return DiagnosticsExportResult{}, err
}
}
if strings.TrimSpace(b.QEMULog) != "" {
if err := addFile("qemu.log", redact(b.QEMULog)); err != nil {
return DiagnosticsExportResult{}, err
}
}
if len(b.AppLogs) > 0 {
if err := addFile("app-logs.txt", redact(strings.Join(b.AppLogs, "\n"))+"\n"); err != nil {
return DiagnosticsExportResult{}, err
}
}
if len(b.PluginDiagnostics) > 0 {
if err := addJSON("plugin-diagnostics.json", b.PluginDiagnostics); err != nil {
return DiagnosticsExportResult{}, err
}
}
result.SummaryText = redact(diagnosticsSummary(b, generatedAt, result, append(result.IncludedFiles, "summary.txt")))
if err := addFile("summary.txt", result.SummaryText); err != nil {
return DiagnosticsExportResult{}, err
}
return result, nil
}
func redactDiagnosticsJSON(value any, redact func(string) string) any {
switch v := value.(type) {
case string:
return redact(v)
case []any:
for i, item := range v {
v[i] = redactDiagnosticsJSON(item, redact)
}
case map[string]any:
return redactJSONMap(v, redact)
}
return value
}
func redactJSONMap(data map[string]any, redact func(string) string) map[string]any {
redacted := make(map[string]any, len(data))
nextSuffix := make(map[string]int)
for _, key := range slices.Sorted(maps.Keys(data)) {
base := redact(key)
name := base
if _, exists := redacted[base]; exists {
suffix := max(2, nextSuffix[base])
for {
name = fmt.Sprintf("%s #%d", base, suffix)
suffix++
if _, exists := redacted[name]; !exists {
break
}
}
nextSuffix[base] = suffix
}
if item, ok := data[key].(string); ok && item != "" && isDiagnosticsSensitiveField(key) {
redacted[name] = "[redacted]"
continue
}
redacted[name] = redactDiagnosticsJSON(data[key], redact)
}
return redacted
}
func isDiagnosticsSensitiveField(key string) bool {
switch strings.ToLower(key) {
case "mac", "mac_address", "macaddress", "osk", "smc_osk", "serial", "serial_number", "serialnumber",
"system_serial", "system_serial_number", "systemserial", "systemserialnumber", "systemserial_number",
"mlb", "rom", "smuuid", "system_uuid", "systemuuid", "uuid",
"reims_token", "github_token", "token", "access_token", "refresh_token", "auth_token",
"api_key", "apikey", "password", "passwd", "secret", "authorization", "cookie":
return true
}
return false
}
var (
diagnosticsPathStart = regexp.MustCompile(`(?i)(?:^|[\s"'=(,\[])([a-z]:[/\\]|(?:\\\\|//)[^/\\\s"'=,;()\[\]]+[/\\]|\[redacted\][/\\])`)
diagnosticsPathEnd = regexp.MustCompile(`(?i)["'\r\n;,)\]]|:[ \t]|[ \t]+(?:-|Authorization:|[a-z][a-z0-9+.-]*://)`)
diagnosticsSingleQuotedPathEnd = regexp.MustCompile(`[\r\n]|'(?:$|[\s:;,)\]"])`)
)
func redactDiagnosticsWindowsPaths(content string) string {
matches := diagnosticsPathStart.FindAllStringSubmatchIndex(content, -1)
if len(matches) == 0 {
return content
}
var out strings.Builder
end := 0
for _, match := range matches {
start := match[2]
if start < end {
continue
}
out.WriteString(content[end:start])
out.WriteString("[redacted]")
end = diagnosticsWindowsPathEnd(content, start, match[3])
}
out.WriteString(content[end:])
return out.String()
}
func diagnosticsWindowsPathEnd(content string, start, prefixEnd int) int {
rest := content[prefixEnd:]
if start > 0 && content[start-1] == '\'' {
if stop := diagnosticsSingleQuotedPathEnd.FindStringIndex(rest); stop != nil {
return prefixEnd + stop[0]
}
return len(content)
}
if start > 0 && content[start-1] == '"' {
if close := strings.IndexByte(rest, '"'); close >= 0 && !strings.ContainsAny(rest[:close], "\r\n") {
return prefixEnd + close
}
}
if stop := diagnosticsPathEnd.FindStringIndex(rest); stop != nil {
rest = rest[:stop[0]]
}
return prefixEnd + len(strings.TrimRight(rest, " \t"))
}
func diagnosticsRedactor(b diagnosticsBundle) func(string) string {
home, _ := os.UserHomeDir()
paths := []string{b.HostReport.DataRoot, home}
if b.VMInfo != nil {
paths = append(paths, b.VMInfo.Directory, b.VMInfo.DiskPath)
}
if b.Runtime != nil {
paths = append(paths, b.Runtime.Dir)
}
var roots []*regexp.Regexp
// Match VM files and runtime directories before their enclosing data root.
slices.SortFunc(paths, func(a, b string) int { return len(b) - len(a) })
for _, path := range paths {
if !filepath.IsAbs(path) || filepath.Dir(path) == path {
continue
}
pattern := regexp.QuoteMeta(path)
if filepath.Separator == '\\' {
parts := strings.Split(filepath.ToSlash(path), "/")
for i, part := range parts {
parts[i] = regexp.QuoteMeta(part)
}
pattern = "(?i)" + strings.Join(parts, `[/\\]`)
}
roots = append(roots, regexp.MustCompile(pattern+`($|[/\\\r\n"'<>|:*?])`))
}
return func(content string) string {
// A known root may contain punctuation that terminates an unquoted path.
for _, root := range roots {
content = root.ReplaceAllString(content, "[redacted]${1}")
}
return host.RedactText(redactDiagnosticsWindowsPaths(content))
}
}
func filterAppLogsForVM(logs []string, ref driver.VMRef) []string {
target := ref.Key()
var filtered []string
for _, line := range logs {
_, entry, ok := strings.Cut(line, " [")
if !ok {
continue
}
if strings.HasPrefix(entry, target+"] ") {
filtered = append(filtered, line)
continue
}
source, _, _ := strings.Cut(entry, "] ")
switch source {
case "app", "host", "runtime", "installer", "network", "ui":
filtered = append(filtered, line)
}
}
return filtered
}
func diagnosticsSummary(b diagnosticsBundle, generatedAt time.Time, result DiagnosticsExportResult, files []string) string {
var summary strings.Builder
rep := b.HostReport
fmt.Fprintf(&summary, "Reims-Go diagnostics\nGenerated (UTC): %s\nApplication version: %s\nTarget: %s\n",
generatedAt.UTC().Format(time.RFC3339), version.Version, result.TargetLabel)
fmt.Fprintf(&summary, "\nHost\nSystem: %s %s\nCPU: %d logical, %d physical\nMemory: %.1f GB available / %.1f GB total\nData disk: %.1f GB free (%s)\nWHPX: %s\n",
rep.OS, rep.Arch, rep.LogicalCPUs, rep.PhysicalCores, rep.AvailRAMGB, rep.TotalRAMGB, rep.FreeDiskGB, rep.DataRootDriveType, rep.WHPX)
if len(rep.GPUs) == 0 {
summary.WriteString("GPU: unavailable\n")
}
for _, gpu := range rep.GPUs {
fmt.Fprintf(&summary, "GPU: %s (driver %s, Vulkan %s)\n", gpu.Name, gpu.DriverVersion, gpu.VulkanVersion)
}
summary.WriteString("\nActive runtime\n")
if b.Runtime == nil {
summary.WriteString("None\n")
} else {
m := b.Runtime.Manifest
fmt.Fprintf(&summary, "%s (commit %s, channel %s, QEMU %s)\n", m.Name, b.Runtime.Commit, m.Channel, m.QemuVersion)
}
if vm := b.VMInfo; vm != nil {
fmt.Fprintf(&summary, "\nVirtual machine\nName: %s\nDriver: %s\nState: %s\nCPU: %d vCPUs\nMemory: %s\nDisk: %s\n",
vm.Name, vm.DriverID, vm.State, vm.CPUs, vm.Memory, vm.DiskSummary)
}
summary.WriteString("\nAutomatic checks\n")
if len(result.Findings) == 0 {
summary.WriteString("No known issues found\n")
}
for _, finding := range result.Findings {
fmt.Fprintf(&summary, "- %s: %s", finding.Severity, finding.Code)
if finding.Detail != "" {
fmt.Fprintf(&summary, " (%s)", finding.Detail)
}
summary.WriteByte('\n')
}
fmt.Fprintf(&summary, "\nIncluded files\n- %s\n", strings.Join(files, "\n- "))
if b.SerialTruncated {
summary.WriteString("serial.log truncated: first 1 MiB and last 4 MiB retained\n")
}
if b.QEMUTruncated {
summary.WriteString("qemu.log truncated: first 1 MiB and last 4 MiB retained\n")
}
return summary.String()
}
// ExportDiagnostics collects a redacted troubleshooting zip bundle through the owning driver.
func (a *App) ExportDiagnostics(driverID, name string) (DiagnosticsExportResult, error) {
if err := a.requireWritableDataRoot(); err != nil {
return DiagnosticsExportResult{}, err
}
var vm driver.VMInfo
var err error
if strings.TrimSpace(name) != "" {
vm, err = a.resolveVMInfo(driverID, name)
if err != nil {
return DiagnosticsExportResult{}, err
}
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
appLogs := append([]string(nil), a.recentLogs...)
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
active, _ := rt.ResolveActive(&cfgCopy)
bundle := diagnosticsBundle{}
label := "host"
pluginKey := ""
var info *driver.VMInfo
if vm.Name != "" {
info = &vm
label = vm.Name
ref := vm.Ref()
pluginKey = ref.Key()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
label = sshHostAlias(ref.DriverID, vm.Name)
}
bundle.SerialLog, bundle.SerialTruncated = a.readDiagnosticsLog(vm, true)
bundle.QEMULog, bundle.QEMUTruncated = a.readDiagnosticsLog(vm, false)
}
bundle.HostReport, bundle.Optimizations, bundle.Runtime, bundle.AppLogs = rep, a.evaluateOptimizations(rep), active, appLogs
bundle.VMInfo, bundle.PluginDiagnostics = info, a.collectPluginDiagnostics(context.Background(), pluginKey)
reportsDir, err := filepath.Abs(filepath.Join(cfgCopy.DataRoot, "reports"))
if err != nil {
return DiagnosticsExportResult{}, err
}
result, err := writeDiagnosticsZip(reportsDir, label, time.Now(), bundle)
if err != nil {
return DiagnosticsExportResult{}, err
}
a.emitLog(label, "Diagnostics exported: "+result.Path)
return result, nil
}
func (a *App) readDiagnosticsLog(vm driver.VMInfo, serial bool) (string, bool) {
ref := vm.Ref()
if ref.DriverID != driver.BuiltinReimsMacOSDriverID || vm.Directory == "" {
log, err := a.ReadVMLogs(ref.DriverID, ref.Name, serial)
if err != nil {
return "", false
}
return log, false
}
name := "qemu.log"
if serial {
name = "serial.log"
}
f, err := host.OpenFileSharedRead(filepath.Join(vm.Directory, "logs", name))
if err != nil {
return "", false
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return "", false
}
const (
maxLogBytes = 16 << 20
headLogBytes = 1 << 20
tailLogBytes = 4 << 20
)
if info.Size() <= maxLogBytes {
log, _ := io.ReadAll(io.NewSectionReader(f, 0, info.Size()))
return string(log), false
}
head, _ := io.ReadAll(io.NewSectionReader(f, 0, headLogBytes))
head = head[:bytes.LastIndexByte(head, '\n')+1]
// Include the byte before the tail to detect an exact line boundary.
tail, _ := io.ReadAll(io.NewSectionReader(f, info.Size()-tailLogBytes-1, tailLogBytes+1))
_, tail, _ = bytes.Cut(tail, []byte("\n"))
return string(head) + "\n[log truncated: middle omitted]\n" + string(tail), true
}
func (a *App) RevealDiagnosticsFile(path string) error {
resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path)
if err != nil {
return err
}
return host.RevealFile(resolved)
}
func (a *App) CopyDiagnosticsFile(path string) error {
resolved, err := resolveDiagnosticsZipPath(a.currentDataRoot(), path)
if err != nil {
return err
}
return host.CopyFileToClipboard(resolved)
}
func resolveDiagnosticsZipPath(dataRoot, rawPath string) (string, error) {
if dataRoot == "" || !strings.EqualFold(filepath.Ext(rawPath), ".zip") {
return "", fmt.Errorf("expected a diagnostics .zip file in the reports directory")
}
reportsDir, err := filepath.Abs(filepath.Join(dataRoot, "reports"))
if err != nil {
return "", err
}
path, err := filepath.Abs(rawPath)
if err != nil {
return "", err
}
rel, err := filepath.Rel(reportsDir, filepath.Dir(path))
if err != nil || rel != "." {
return "", fmt.Errorf("the diagnostics file is outside the reports directory")
}
reportsDir, err = filepath.EvalSymlinks(reportsDir)
if err != nil {
return "", err
}
path, err = filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
reportsInfo, err := os.Stat(reportsDir)
if err != nil {
return "", err
}
parentInfo, err := os.Stat(filepath.Dir(path))
if err != nil {
return "", err
}
if !os.SameFile(reportsInfo, parentInfo) {
return "", fmt.Errorf("the diagnostics file is outside the reports directory")
}
info, err := os.Stat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() || !strings.EqualFold(filepath.Ext(path), ".zip") {
return "", fmt.Errorf("expected a regular diagnostics .zip file")
}
return path, nil
}