| 1 | package vm |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | |
| 19 | func vmStartError(cause error, instanceDir string, since time.Time) error { |
| 20 | if cause == nil || errors.Is(cause, context.Canceled) { |
| 21 | return cause |
| 22 | } |
| 23 | f, err := os.Open(filepath.Join(instanceDir, "ha.stderr.log")) |
| 24 | if err != nil { |
| 25 | return cause |
| 26 | } |
| 27 | defer f.Close() |
| 28 | info, err := f.Stat() |
| 29 | if err != nil || info.ModTime().Before(since) { |
| 30 | return cause |
| 31 | } |
| 32 | if info.Size() > 64<<10 { |
| 33 | _, _ = f.Seek(info.Size()-(64<<10), io.SeekStart) |
| 34 | } |
| 35 | b, err := io.ReadAll(io.LimitReader(f, 64<<10)) |
| 36 | if err != nil { |
| 37 | return cause |
| 38 | } |
| 39 | if info.Size() > 64<<10 { |
| 40 | |
| 41 | if next := strings.IndexByte(string(b), '\n'); next >= 0 { |
| 42 | b = b[next+1:] |
| 43 | } else { |
| 44 | b = nil |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | |
| 49 | stream := diagnostics.NewStream(diagnostics.Default(), "vm/start", "error", nil) |
| 50 | _, _ = stream.Write(b) |
| 51 | _ = stream.Close() |
| 52 | var messages []string |
| 53 | for _, line := range strings.Split(string(b), "\n") { |
| 54 | var record struct { |
| 55 | Message string `json:"msg"` |
| 56 | } |
| 57 | if json.Unmarshal([]byte(line), &record) == nil && record.Message != "" { |
| 58 | line = record.Message |
| 59 | } |
| 60 | _, message, ok := strings.Cut(line, "qemu[stderr]") |
| 61 | if !ok { |
| 62 | continue |
| 63 | } |
| 64 | message = strings.TrimSpace(strings.TrimLeft(message, "]: \"")) |
| 65 | if message == "" || strings.Contains(strings.ToLower(message), "warning:") { |
| 66 | continue |
| 67 | } |
| 68 | messages = append(messages, diagnostics.Redact(message)) |
| 69 | if len(messages) == 6 { |
| 70 | break |
| 71 | } |
| 72 | } |
| 73 | if len(messages) == 0 { |
| 74 | return cause |
| 75 | } |
| 76 | summary := strings.Join(messages, ";") |
| 77 | if len(summary) > 2048 { |
| 78 | summary = strings.ToValidUTF8(summary[:2048], "") |
| 79 | } |
| 80 | return fmt.Errorf("QEMU 启动失败:%s;%w", summary, cause) |
| 81 | } |