miaopanel
1package appstore
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12 "sync"
13 "time"
14)
15
16// ErrTaskRunning is returned when another installation is still running.
17var ErrTaskRunning = errors.New("已有安装任务在执行,请等待完成")
18
19const (
20 // Long apt/build runs can emit tens of thousands of lines. The UI only
21 // needs the recent tail; keeping the full output in RAM multiplies across
22 // finished tasks and is the largest avoidable allocation in the panel.
23 maxTaskLogLines = 1000
24 maxTaskHistory = 30
25)
26
27// TaskView is the JSON payload polled by the UI.
28type TaskView struct {
29 ID string `json:"id"`
30 App string `json:"app"`
31 AppName string `json:"app_name"`
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 line == "" {
50 return
51 }
52 t.mu.Lock()
53 defer t.mu.Unlock()
54 // Keep the payload bounded; long builds can emit thousands of lines.
55 if len(t.view.Log) < maxTaskLogLines {
56 t.view.Log = append(t.view.Log, line)
57 } else if len(t.view.Log) == maxTaskLogLines {
58 t.view.Log = append(t.view.Log, "…(日志过长,后续输出已省略)")
59 }
60}
61
62func (t *task) snapshot() TaskView {
63 t.mu.Lock()
64 defer t.mu.Unlock()
65 out := t.view
66 out.Log = append([]string(nil), t.view.Log...)
67 return out
68}
69
70func (t *task) finish(err error) {
71 t.mu.Lock()
72 if err != nil {
73 t.view.Status = "failed"
74 t.view.Error = err.Error()
75 if len(t.view.Log) < maxTaskLogLines {
76 t.view.Log = append(t.view.Log, "安装失败: "+err.Error())
77 }
78 } else {
79 t.view.Status = "ok"
80 t.view.Log = append(t.view.Log, "完成")
81 }
82 t.view.EndedAt = time.Now().Unix()
83 logPath := t.logPath
84 logText := strings.Join(t.view.Log, "\n") + "\n"
85 t.mu.Unlock()
86 if logPath != "" {
87 _ = os.MkdirAll(filepath.Dir(logPath), 0o700)
88 _ = os.WriteFile(logPath, []byte(logText), 0o600)
89 }
90}
91
92type runnerFunc func(ctx context.Context, t *task, script string) error
93
94type taskManager struct {
95 mu sync.Mutex
96 tasks map[string]*task
97 order []string
98 running bool
99 logDir string
100}
101
102func newTaskManager(logDir string) *taskManager {
103 return &taskManager{tasks: map[string]*task{}, logDir: logDir}
104}
105
106func (m *taskManager) start(def AppDef, ver Version, action, script string, run runnerFunc) (TaskView, error) {
107 m.mu.Lock()
108 if m.running {
109 m.mu.Unlock()
110 return TaskView{}, ErrTaskRunning
111 }
112 id := randomID()
113 t := &task{
114 view: TaskView{
115 ID: id, App: def.ID, AppName: def.Name, Version: ver.Version,
116 Action: action, Status: "running", StartedAt: time.Now().Unix(),
117 },
118 logPath: filepath.Join(m.logDir, id+".log"),
119 }
120 m.tasks[id] = t
121 m.order = append(m.order, id)
122 m.running = true
123 if len(m.order) > maxTaskHistory {
124 for _, old := range m.order[:len(m.order)-maxTaskHistory] {
125 delete(m.tasks, old)
126 }
127 m.order = m.order[len(m.order)-maxTaskHistory:]
128 }
129 m.mu.Unlock()
130
131 t.append(fmt.Sprintf("==> %s %s %s", action, def.Name, ver.Version))
132 ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
133 go func() {
134 defer cancel()
135 defer func() {
136 m.mu.Lock()
137 m.running = false
138 m.mu.Unlock()
139 }()
140 var err error
141 func() {
142 defer func() {
143 if rec := recover(); rec != nil {
144 err = fmt.Errorf("安装器内部错误: %v", rec)
145 }
146 }()
147 err = run(ctx, t, script)
148 }()
149 t.finish(err)
150 }()
151 return t.snapshot(), nil
152}
153
154func (m *taskManager) get(id string) (TaskView, bool) {
155 m.mu.Lock()
156 t, ok := m.tasks[id]
157 m.mu.Unlock()
158 if !ok {
159 return TaskView{}, false
160 }
161 return t.snapshot(), true
162}
163
164func (m *taskManager) list(limit int) []TaskView {
165 if limit <= 0 || limit > 50 {
166 limit = 20
167 }
168 m.mu.Lock()
169 ids := append([]string(nil), m.order...)
170 tasks := make(map[string]*task, len(m.tasks))
171 for k, v := range m.tasks {
172 tasks[k] = v
173 }
174 m.mu.Unlock()
175 out := make([]TaskView, 0, limit)
176 for i := len(ids) - 1; i >= 0 && len(out) < limit; i-- {
177 if t, ok := tasks[ids[i]]; ok {
178 out = append(out, t.snapshot())
179 }
180 }
181 return out
182}
183
184func randomID() string {
185 b := make([]byte, 6)
186 if _, err := rand.Read(b); err != nil {
187 return fmt.Sprintf("%d", time.Now().UnixNano())
188 }
189 return hex.EncodeToString(b)
190}