仰望星辰工作室

miaopanel

miaopanel/ internal/appstore/service.go 14.4 KB · 476 行 原始文件
1package appstore
2
3import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "runtime"
11 "sort"
12 "strconv"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/miaopanel/miaopanel/internal/config"
18 "github.com/miaopanel/miaopanel/internal/site"
19 "github.com/miaopanel/miaopanel/internal/system"
20)
21
22const (
23 goRoot = "/www/server/go"
24 nodeRoot = "/www/server/node"
25 pythonRoot = "/www/server/python"
26 phpRoot = "/www/server/php"
27 mysqlRoot = "/www/server/mysql"
28)
29
30// Service detects installed applications and starts installation tasks.
31type Service struct {
32 cfg *config.Config
33 tasks *taskManager
34
35 sites *site.Service
36 runner *system.Runner
37
38 mu sync.Mutex
39 cache []App
40 cacheAt time.Time
41 hook func(context.Context)
42}
43
44// New builds the app store service.
45func New(cfg *config.Config) *Service {
46 logDir := "./data/appstore"
47 if cfg != nil && cfg.DataDir != "" {
48 logDir = filepath.Join(cfg.DataDir, "appstore")
49 }
50 return &Service{cfg: cfg, tasks: newTaskManager(logDir), runner: system.NewRunner()}
51}
52
53// SetSiteService lets the app store create companion sites (phpMyAdmin).
54func (s *Service) SetSiteService(sites *site.Service) { s.sites = sites }
55
56// List returns the catalog joined with local detection results. Results are
57// cached briefly because every detection spawns a few version commands.
58func (s *Service) List(ctx context.Context, refresh bool) []App {
59 s.mu.Lock()
60 defer s.mu.Unlock()
61 if !refresh && !s.cacheAt.IsZero() && time.Since(s.cacheAt) < 15*time.Second {
62 return append([]App(nil), s.cache...)
63 }
64 out := make([]App, 0, len(catalog))
65 distro := system.Detect()
66 for _, def := range catalog {
67 app := App{AppDef: def, Supported: supportedOn(def, distro)}
68 if runtime.GOOS == "linux" {
69 app.Installed, app.Running = s.detect(ctx, def.ID)
70 }
71 out = append(out, app)
72 }
73 s.cache, s.cacheAt = out, time.Now()
74 return append([]App(nil), out...)
75}
76
77// SetInstallHook runs after nginx is installed, so the panel can inject its
78// includes into a freshly created nginx.conf.
79func (s *Service) SetInstallHook(fn func(context.Context)) { s.hook = fn }
80
81// Tasks returns the newest tasks, newest first.
82func (s *Service) Tasks(limit int) []TaskView { return s.tasks.list(limit) }
83
84// Task returns one task snapshot.
85func (s *Service) Task(id string) (TaskView, bool) { return s.tasks.get(id) }
86
87// Install validates the request and starts a background installation.
88func (s *Service) Install(ctx context.Context, appID, version string) (TaskView, error) {
89 def, ver, err := s.resolve(appID, version)
90 if err != nil {
91 return TaskView{}, err
92 }
93 if !supportedOn(def, system.Detect()) {
94 return TaskView{}, errors.New("该应用不支持当前系统")
95 }
96 if def.ID == "phpmyadmin" && len(system.DetectRuntimes().PHP) == 0 {
97 return TaskView{}, errors.New("请先在应用商店安装 PHP(phpMyAdmin 需要 PHP-FPM)")
98 }
99 if err := s.checkDatabaseConflict(ctx, def.ID, ver.Version); err != nil {
100 return TaskView{}, err
101 }
102 script, err := s.installScript(ctx, def, ver)
103 if err != nil {
104 return TaskView{}, err
105 }
106 runner := s.runScript
107 switch def.ID {
108 case "nginx":
109 if s.hook != nil {
110 hook := s.hook
111 runner = func(runCtx context.Context, t *task, script string) error {
112 if err := s.runScript(runCtx, t, script); err != nil {
113 return err
114 }
115 hook(runCtx)
116 return nil
117 }
118 }
119 case "phpmyadmin":
120 runner = func(runCtx context.Context, t *task, script string) error {
121 if err := s.runScript(runCtx, t, script); err != nil {
122 return err
123 }
124 return s.ensurePhpMyAdminSite(runCtx, t)
125 }
126 }
127 task, err := s.tasks.start(def, ver, "install", script, runner)
128 return task, err
129}
130
131// Uninstall removes one installed version. Database packages are removed but
132// their data directories are kept.
133func (s *Service) Uninstall(ctx context.Context, appID, version string) (TaskView, error) {
134 def, ok := lookupApp(appID)
135 if !ok {
136 return TaskView{}, os.ErrNotExist
137 }
138 ver := Version{Version: version}
139 if v, ok := lookupVersion(def, version); ok {
140 ver = v
141 } else if !versionRe.MatchString(version) {
142 return TaskView{}, os.ErrInvalid
143 }
144 if runtime.GOOS != "linux" || os.Geteuid() != 0 {
145 return TaskView{}, os.ErrPermission
146 }
147 script, err := s.uninstallScript(def, ver)
148 if err != nil {
149 return TaskView{}, err
150 }
151 runner := s.runScript
152 if def.ID == "phpmyadmin" {
153 // The installer creates a site as a side effect; removing only the
154 // files used to leave a broken vhost pointing at a deleted directory.
155 runner = func(runCtx context.Context, t *task, script string) error {
156 if err := s.runScript(runCtx, t, script); err != nil {
157 return err
158 }
159 return s.removePhpMyAdminSite(runCtx, t)
160 }
161 }
162 return s.tasks.start(def, ver, "uninstall", script, runner)
163}
164
165// checkDatabaseConflict prevents installing MySQL on top of a running MariaDB
166// (or the reverse): both bind 3306 and share /var/lib/mysql. The app store's
167// legacy 5.x tree lives outside the package manager, so it is detected by its
168// "current" symlink instead.
169func (s *Service) checkDatabaseConflict(ctx context.Context, appID, version string) error {
170 if st, err := os.Stat(filepath.Join(mysqlRoot, "current")); err == nil && st.IsDir() {
171 if appID == "mariadb" || (appID == "mysql" && !isLegacyMySQL(version)) {
172 return errors.New("检测到应用商店安装的 MySQL 5.x(/www/server/mysql),请先备份并卸载旧版 MySQL")
173 }
174 }
175 switch appID {
176 case "mysql":
177 if serviceActive(ctx, "mariadb") || packageInstalled(ctx, "mariadb-server") {
178 return errors.New("检测到已安装 MariaDB,请先在应用商店卸载 MariaDB(数据目录保留)再安装 MySQL")
179 }
180 case "mariadb":
181 if serviceActive(ctx, "mysql") || serviceActive(ctx, "mysqld") ||
182 packageInstalled(ctx, "mysql-community-server") {
183 return errors.New("检测到已安装 MySQL,请先在应用商店卸载 MySQL(数据目录保留)再安装 MariaDB")
184 }
185 }
186 return nil
187}
188
189func packageInstalled(ctx context.Context, name string) bool {
190 if _, err := exec.LookPath("dpkg"); err == nil {
191 out, err := command(ctx, 4*time.Second, "dpkg", "-s", name)
192 return err == nil && strings.Contains(out, "Status: install ok installed")
193 }
194 if _, err := exec.LookPath("rpm"); err == nil {
195 _, err := command(ctx, 4*time.Second, "rpm", "-q", name)
196 return err == nil
197 }
198 return false
199}
200
201func (s *Service) resolve(appID, version string) (AppDef, Version, error) {
202 def, ok := lookupApp(appID)
203 if !ok {
204 return AppDef{}, Version{}, os.ErrNotExist
205 }
206 ver, ok := lookupVersion(def, version)
207 if !ok {
208 return AppDef{}, Version{}, os.ErrInvalid
209 }
210 if runtime.GOOS != "linux" {
211 return AppDef{}, Version{}, os.ErrPermission
212 }
213 if os.Geteuid() != 0 {
214 return AppDef{}, Version{}, os.ErrPermission
215 }
216 return def, ver, nil
217}
218
219// supportedOn reports whether the catalog entry can be installed on the host.
220// Tarball based apps work on every glibc Linux; package based ones declare the
221// family they support.
222func supportedOn(def AppDef, distro system.Distro) bool {
223 if runtime.GOOS != "linux" {
224 return false
225 }
226 return familySupported(def.Family, distro.Family)
227}
228
229func familySupported(appFamily, distroFamily string) bool {
230 if distroFamily != "debian" && distroFamily != "rhel" {
231 return false
232 }
233 switch appFamily {
234 case "", "any":
235 return true
236 default:
237 return appFamily == distroFamily
238 }
239}
240
241func (s *Service) detect(ctx context.Context, appID string) ([]Installed, bool) {
242 switch appID {
243 case "nginx":
244 return detectBinary(ctx, "nginx", []string{"-v"}, nginxVersion, true), serviceActive(ctx, "nginx")
245 case "mariadb":
246 out, _ := command(ctx, 3*time.Second, "mariadb", "--version")
247 if out == "" {
248 out, _ = command(ctx, 3*time.Second, "mysqld", "--version")
249 }
250 if !strings.Contains(strings.ToLower(out), "mariadb") {
251 return nil, false
252 }
253 return installedFromOutput(out, mysqlVersion, true), serviceActive(ctx, "mariadb")
254 case "mysql":
255 out, _ := command(ctx, 3*time.Second, "mysqld", "--version")
256 if out == "" {
257 out, _ = command(ctx, 3*time.Second, "mysql", "--version")
258 }
259 list := detectDir(mysqlRoot, "bin/mysqld")
260 if !strings.Contains(strings.ToLower(out), "mariadb") {
261 list = mergeInstalled(list, installedFromOutput(out, mysqlVersion, true))
262 }
263 return list, serviceActive(ctx, "mysql")
264 case "go":
265 list := detectDir(goRoot, "bin/go")
266 list = mergeInstalled(list, detectBinary(ctx, "go", []string{"version"}, goVersion, false))
267 return list, false
268 case "node":
269 list := detectDir(nodeRoot, "bin/node")
270 list = mergeInstalled(list, detectBinary(ctx, "node", []string{"-v"}, nodeVersion, false))
271 return list, false
272 case "python":
273 list := detectDir(pythonRoot, "bin/python3")
274 list = mergeInstalled(list, detectBinary(ctx, "python3", []string{"-V"}, pythonVersion, false))
275 return list, false
276 case "php":
277 return detectPHP(ctx), false
278 case "phpmyadmin":
279 return detectDirs(s.webRoot(), "phpmyadmin", "index.php"), false
280 case "git":
281 return detectBinary(ctx, "git", []string{"--version"}, gitVersion, true), false
282 case "docker":
283 return detectBinary(ctx, "docker", []string{"--version"}, dockerVersion, true), serviceActive(ctx, "docker")
284 }
285 return nil, false
286}
287
288func (s *Service) webRoot() string {
289 if s.cfg != nil && s.cfg.WebRoot != "" {
290 return s.cfg.WebRoot
291 }
292 return "/www/wwwroot"
293}
294
295func detectBinary(ctx context.Context, name string, args []string, parse func(string) string, managed bool) []Installed {
296 out, err := command(ctx, 4*time.Second, name, args...)
297 if err != nil || out == "" {
298 return nil
299 }
300 ver := parse(out)
301 if ver == "" {
302 return nil
303 }
304 path, _ := exec.LookPath(name)
305 return []Installed{{Version: ver, Path: path, Active: true, Managed: managed}}
306}
307
308func detectDir(root, binRel string) []Installed {
309 entries, err := os.ReadDir(root)
310 if err != nil {
311 return nil
312 }
313 active := currentTarget(root)
314 var out []Installed
315 for _, entry := range entries {
316 if !entry.IsDir() || entry.Name() == "current" {
317 continue
318 }
319 bin := filepath.Join(root, entry.Name(), binRel)
320 if st, err := os.Stat(bin); err != nil || st.IsDir() {
321 continue
322 }
323 out = append(out, Installed{
324 Version: entry.Name(), Path: bin, Active: active == entry.Name(), Managed: true,
325 })
326 }
327 sortInstalled(out)
328 return out
329}
330
331func currentTarget(root string) string {
332 target, err := filepath.EvalSymlinks(filepath.Join(root, "current"))
333 if err != nil {
334 return ""
335 }
336 return filepath.Base(target)
337}
338
339func detectPHP(ctx context.Context) []Installed {
340 seen := map[string]bool{}
341 var out []Installed
342 if entries, err := os.ReadDir("/run/php"); err == nil {
343 for _, entry := range entries {
344 name := entry.Name()
345 if !strings.HasPrefix(name, "php") || !strings.HasSuffix(name, "-fpm.sock") {
346 continue
347 }
348 ver := strings.TrimSuffix(strings.TrimPrefix(name, "php"), "-fpm.sock")
349 if ver == "" || seen[ver] {
350 continue
351 }
352 seen[ver] = true
353 out = append(out, Installed{Version: ver, Path: "/run/php/" + name, Active: true, Managed: true})
354 }
355 }
356 if entries, err := os.ReadDir(phpRoot); err == nil {
357 for _, entry := range entries {
358 if !entry.IsDir() || seen[entry.Name()] {
359 continue
360 }
361 bin := filepath.Join(phpRoot, entry.Name(), "bin/php")
362 if st, err := os.Stat(bin); err == nil && !st.IsDir() {
363 seen[entry.Name()] = true
364 out = append(out, Installed{Version: entry.Name(), Path: bin, Active: true, Managed: true})
365 }
366 }
367 }
368 if len(out) == 0 {
369 if o, err := command(ctx, 3*time.Second, "php", "-v"); err == nil {
370 out = installedFromOutput(o, phpVersion, true)
371 }
372 }
373 sortInstalled(out)
374 return out
375}
376
377func detectDirs(root, sub, marker string) []Installed {
378 base := filepath.Join(root, sub)
379 entries, err := os.ReadDir(base)
380 if err != nil {
381 return nil
382 }
383 active := currentTarget(base)
384 var out []Installed
385 for _, entry := range entries {
386 if !entry.IsDir() || entry.Name() == "current" {
387 continue
388 }
389 if _, err := os.Stat(filepath.Join(base, entry.Name(), marker)); err != nil {
390 continue
391 }
392 out = append(out, Installed{
393 Version: entry.Name(), Path: filepath.Join(base, entry.Name()), Active: active == entry.Name(), Managed: true,
394 })
395 }
396 sortInstalled(out)
397 return out
398}
399
400func installedFromOutput(out string, parse func(string) string, managed bool) []Installed {
401 ver := parse(out)
402 if ver == "" {
403 return nil
404 }
405 return []Installed{{Version: ver, Path: "", Active: true, Managed: managed}}
406}
407
408func mergeInstalled(a, b []Installed) []Installed {
409 seen := map[string]bool{}
410 var out []Installed
411 for _, item := range append(a, b...) {
412 if item.Version == "" || seen[item.Version] {
413 continue
414 }
415 seen[item.Version] = true
416 out = append(out, item)
417 }
418 sortInstalled(out)
419 return out
420}
421
422func sortInstalled(list []Installed) {
423 sort.Slice(list, func(i, j int) bool { return compareVersion(list[i].Version, list[j].Version) > 0 })
424}
425
426func compareVersion(a, b string) int {
427 pa := strings.FieldsFunc(strings.TrimPrefix(a, "v"), func(r rune) bool { return r == '.' || r == '-' || r == '_' })
428 pb := strings.FieldsFunc(strings.TrimPrefix(b, "v"), func(r rune) bool { return r == '.' || r == '-' || r == '_' })
429 for i := 0; i < len(pa) || i < len(pb); i++ {
430 var na, nb int
431 if i < len(pa) {
432 na, _ = strconv.Atoi(pa[i])
433 }
434 if i < len(pb) {
435 nb, _ = strconv.Atoi(pb[i])
436 }
437 if na != nb {
438 if na > nb {
439 return 1
440 }
441 return -1
442 }
443 }
444 return 0
445}
446
447func serviceActive(ctx context.Context, unit string) bool {
448 out, err := command(ctx, 3*time.Second, "systemctl", "is-active", unit)
449 return err == nil && strings.TrimSpace(out) == "active"
450}
451
452func command(ctx context.Context, timeout time.Duration, name string, args ...string) (string, error) {
453 runCtx, cancel := context.WithTimeout(ctx, timeout)
454 defer cancel()
455 out, err := exec.CommandContext(runCtx, name, args...).CombinedOutput()
456 return strings.TrimSpace(string(out)), err
457}
458
459var (
460 nginxVersion = func(s string) string { return firstMatch(s, `nginx/([0-9][0-9.]*)`) }
461 goVersion = func(s string) string { return firstMatch(s, `go([0-9][0-9.]*)`) }
462 nodeVersion = func(s string) string { return firstMatch(s, `v?([0-9][0-9.]*)`) }
463 pythonVersion = func(s string) string { return firstMatch(s, `Python ([0-9][0-9.]*)`) }
464 phpVersion = func(s string) string { return firstMatch(s, `PHP ([0-9][0-9.]*)`) }
465 mysqlVersion = func(s string) string { return firstMatch(s, `(?:Distrib |Ver )?([0-9]+\.[0-9]+\.[0-9]+)`) }
466 gitVersion = func(s string) string { return firstMatch(s, `git version ([0-9][0-9.]*)`) }
467 dockerVersion = func(s string) string { return firstMatch(s, `Docker version ([0-9][0-9.]*)`) }
468)
469
470func firstMatch(s, pattern string) string {
471 m := regexp.MustCompile(pattern).FindStringSubmatch(s)
472 if len(m) < 2 {
473 return ""
474 }
475 return m[1]
476}