miaopanel
1package plugins
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "os"
9 "path/filepath"
10 "strings"
11 "sync"
12 "time"
13)
14
15// ErrTaskRunning is returned when another plugin task is still executing.
16var ErrTaskRunning = errTaskRunning{}
17
18type errTaskRunning struct{}
19
20func (errTaskRunning) Error() string { return "已有插件任务在执行,请等待完成" }
21
22const (
23 maxTaskLogLines = 1500
24 maxTaskHistory = 30
25)
26
27// TaskView is polled by the UI.
28type TaskView struct {
29 ID string `json:"id"`
30 Plugin string `json:"plugin"`
31 Slug string `json:"slug"`
32 Version string `json:"version"`
33 Action string `json:"action"`
34 Status string `json:"status"` // running | ok | failed
35 Log []string `json:"log"`
36 Error string `json:"error,omitempty"`
37 StartedAt int64 `json:"started_at"`
38 EndedAt int64 `json:"ended_at,omitempty"`
39}
40
41type task struct {
42 mu sync.Mutex
43 view TaskView
44 logPath string
45}
46
47func (t *task) append(line string) {
48 line = strings.TrimRight(line, "\r\n")
49 if strings.TrimSpace(line) == "" {
50 return
51 }
52 // Plugin logs can be long; keep both the beginning and a sliding tail.
53 t.mu.Lock()
54 defer t.mu.Unlock()
55 if len(t.view.Log) < maxTaskLogLines {
56 t.view.Log = append(t.view.Log, line)
57 } else {
58 t.view.Log = append(t.view.Log[:maxTaskLogLines/2], t.view.Log[maxTaskLogLines/2+1:]...)
59 t.view.Log = append(t.view.Log, line)
60 }
61}
62
63func (t *task) snapshot() TaskView {
64 t.mu.Lock()
65 defer t.mu.Unlock()
66 out := t.view
67 out.Log = append([]string(nil), t.view.Log...)
68 return out
69}
70
71func (t *task) finish(err error) {
72 t.mu.Lock()
73 if err != nil {
74 t.view.Status = "failed"
75 t.view.Error = err.Error()
76 if len(t.view.Log) < maxTaskLogLines {
77 t.view.Log = append(t.view.Log, "失败: "+err.Error())
78 }
79 } else {
80 t.view.Status = "ok"
81 if len(t.view.Log) < maxTaskLogLines {
82 t.view.Log = append(t.view.Log, "完成")
83 }
84 }
85 t.view.EndedAt = time.Now().Unix()
86 logPath := t.logPath
87 logText := strings.Join(t.view.Log, "\n") + "\n"
88 t.mu.Unlock()
89 if logPath != "" {
90 _ = os.MkdirAll(filepath.Dir(logPath), 0o700)
91 _ = os.WriteFile(logPath, []byte(logText), 0o600)
92 }
93}
94
95type taskManager struct {
96 mu sync.Mutex
97 tasks map[string]*task
98 order []string
99 running bool
100 logDir string
101}
102
103func newTaskManager(logDir string) *taskManager {
104 return &taskManager{tasks: map[string]*task{}, logDir: logDir}
105}
106
107func (m *taskManager) start(slug, name, version, action string, run func(ctx context.Context, t *task) error) (TaskView, error) {
108 m.mu.Lock()
109 if m.running {
110 m.mu.Unlock()
111 return TaskView{}, ErrTaskRunning
112 }
113 id := newID()
114 t := &task{
115 view: TaskView{
116 ID: id, Slug: slug, Plugin: name, Version: version, Action: action,
117 Status: "running", StartedAt: time.Now().Unix(),
118 },
119 logPath: filepath.Join(m.logDir, id+".log"),
120 }
121 m.tasks[id] = t
122 m.order = append(m.order, id)
123 m.running = true
124 if len(m.order) > maxTaskHistory {
125 for _, old := range m.order[:len(m.order)-maxTaskHistory] {
126 delete(m.tasks, old)
127 }
128 m.order = m.order[len(m.order)-maxTaskHistory:]
129 }
130 m.mu.Unlock()
131
132 // Plugin hooks may legitimately take the full manifest timeout; give the
133 // context some headroom and let the hook enforce its own limit.
134 ctx, cancel := context.WithTimeout(context.Background(), 65*time.Minute)
135 go func() {
136 defer cancel()
137 defer func() {
138 m.mu.Lock()
139 m.running = false
140 m.mu.Unlock()
141 }()
142 var err error
143 func() {
144 defer func() {
145 if rec := recover(); rec != nil {
146 err = fmt.Errorf("插件任务内部错误: %v", rec)
147 }
148 }()
149 err = run(ctx, t)
150 }()
151 t.finish(err)
152 }()
153 return t.snapshot(), nil
154}
155
156func (m *taskManager) get(id string) (TaskView, bool) {
157 m.mu.Lock()
158 t, ok := m.tasks[id]
159 m.mu.Unlock()
160 if !ok {
161 return TaskView{}, false
162 }
163 return t.snapshot(), true
164}
165
166func (m *taskManager) list(limit int) []TaskView {
167 if limit <= 0 || limit > 50 {
168 limit = 20
169 }
170 m.mu.Lock()
171 ids := append([]string(nil), m.order...)
172 tasks := make(map[string]*task, len(m.tasks))
173 for k, v := range m.tasks {
174 tasks[k] = v
175 }
176 m.mu.Unlock()
177 out := make([]TaskView, 0, limit)
178 for i := len(ids) - 1; i >= 0 && len(out) < limit; i-- {
179 if t, ok := tasks[ids[i]]; ok {
180 out = append(out, t.snapshot())
181 }
182 }
183 return out
184}
185
186func newID() string {
187 b := make([]byte, 6)
188 if _, err := rand.Read(b); err != nil {
189 return fmt.Sprintf("%d", time.Now().UnixNano())
190 }
191 return hex.EncodeToString(b)
192}