package appstore import ( "context" "errors" "os" "os/exec" "path/filepath" "regexp" "runtime" "sort" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/site" "github.com/miaopanel/miaopanel/internal/system" ) const ( goRoot = "/www/server/go" nodeRoot = "/www/server/node" pythonRoot = "/www/server/python" phpRoot = "/www/server/php" mysqlRoot = "/www/server/mysql" ) // Service detects installed applications and starts installation tasks. type Service struct { cfg *config.Config tasks *taskManager sites *site.Service runner *system.Runner mu sync.Mutex cache []App cacheAt time.Time hook func(context.Context) } // New builds the app store service. func New(cfg *config.Config) *Service { logDir := "./data/appstore" if cfg != nil && cfg.DataDir != "" { logDir = filepath.Join(cfg.DataDir, "appstore") } return &Service{cfg: cfg, tasks: newTaskManager(logDir), runner: system.NewRunner()} } // SetSiteService lets the app store create companion sites (phpMyAdmin). func (s *Service) SetSiteService(sites *site.Service) { s.sites = sites } // List returns the catalog joined with local detection results. Results are // cached briefly because every detection spawns a few version commands. func (s *Service) List(ctx context.Context, refresh bool) []App { s.mu.Lock() defer s.mu.Unlock() if !refresh && !s.cacheAt.IsZero() && time.Since(s.cacheAt) < 15*time.Second { return append([]App(nil), s.cache...) } out := make([]App, 0, len(catalog)) distro := system.Detect() for _, def := range catalog { app := App{AppDef: def, Supported: supportedOn(def, distro)} if runtime.GOOS == "linux" { app.Installed, app.Running = s.detect(ctx, def.ID) } out = append(out, app) } s.cache, s.cacheAt = out, time.Now() return append([]App(nil), out...) } // SetInstallHook runs after nginx is installed, so the panel can inject its // includes into a freshly created nginx.conf. func (s *Service) SetInstallHook(fn func(context.Context)) { s.hook = fn } // Tasks returns the newest tasks, newest first. func (s *Service) Tasks(limit int) []TaskView { return s.tasks.list(limit) } // Task returns one task snapshot. func (s *Service) Task(id string) (TaskView, bool) { return s.tasks.get(id) } // Install validates the request and starts a background installation. func (s *Service) Install(ctx context.Context, appID, version string) (TaskView, error) { def, ver, err := s.resolve(appID, version) if err != nil { return TaskView{}, err } if !supportedOn(def, system.Detect()) { return TaskView{}, errors.New("该应用不支持当前系统") } if def.ID == "phpmyadmin" && len(system.DetectRuntimes().PHP) == 0 { return TaskView{}, errors.New("请先在应用商店安装 PHP(phpMyAdmin 需要 PHP-FPM)") } if err := s.checkDatabaseConflict(ctx, def.ID, ver.Version); err != nil { return TaskView{}, err } script, err := s.installScript(ctx, def, ver) if err != nil { return TaskView{}, err } runner := s.runScript switch def.ID { case "nginx": if s.hook != nil { hook := s.hook runner = func(runCtx context.Context, t *task, script string) error { if err := s.runScript(runCtx, t, script); err != nil { return err } hook(runCtx) return nil } } case "phpmyadmin": runner = func(runCtx context.Context, t *task, script string) error { if err := s.runScript(runCtx, t, script); err != nil { return err } return s.ensurePhpMyAdminSite(runCtx, t) } } task, err := s.tasks.start(def, ver, "install", script, runner) return task, err } // Uninstall removes one installed version. Database packages are removed but // their data directories are kept. func (s *Service) Uninstall(ctx context.Context, appID, version string) (TaskView, error) { def, ok := lookupApp(appID) if !ok { return TaskView{}, os.ErrNotExist } ver := Version{Version: version} if v, ok := lookupVersion(def, version); ok { ver = v } else if !versionRe.MatchString(version) { return TaskView{}, os.ErrInvalid } if runtime.GOOS != "linux" || os.Geteuid() != 0 { return TaskView{}, os.ErrPermission } script, err := s.uninstallScript(def, ver) if err != nil { return TaskView{}, err } runner := s.runScript if def.ID == "phpmyadmin" { // The installer creates a site as a side effect; removing only the // files used to leave a broken vhost pointing at a deleted directory. runner = func(runCtx context.Context, t *task, script string) error { if err := s.runScript(runCtx, t, script); err != nil { return err } return s.removePhpMyAdminSite(runCtx, t) } } return s.tasks.start(def, ver, "uninstall", script, runner) } // checkDatabaseConflict prevents installing MySQL on top of a running MariaDB // (or the reverse): both bind 3306 and share /var/lib/mysql. The app store's // legacy 5.x tree lives outside the package manager, so it is detected by its // "current" symlink instead. func (s *Service) checkDatabaseConflict(ctx context.Context, appID, version string) error { if st, err := os.Stat(filepath.Join(mysqlRoot, "current")); err == nil && st.IsDir() { if appID == "mariadb" || (appID == "mysql" && !isLegacyMySQL(version)) { return errors.New("检测到应用商店安装的 MySQL 5.x(/www/server/mysql),请先备份并卸载旧版 MySQL") } } switch appID { case "mysql": if serviceActive(ctx, "mariadb") || packageInstalled(ctx, "mariadb-server") { return errors.New("检测到已安装 MariaDB,请先在应用商店卸载 MariaDB(数据目录保留)再安装 MySQL") } case "mariadb": if serviceActive(ctx, "mysql") || serviceActive(ctx, "mysqld") || packageInstalled(ctx, "mysql-community-server") { return errors.New("检测到已安装 MySQL,请先在应用商店卸载 MySQL(数据目录保留)再安装 MariaDB") } } return nil } func packageInstalled(ctx context.Context, name string) bool { if _, err := exec.LookPath("dpkg"); err == nil { out, err := command(ctx, 4*time.Second, "dpkg", "-s", name) return err == nil && strings.Contains(out, "Status: install ok installed") } if _, err := exec.LookPath("rpm"); err == nil { _, err := command(ctx, 4*time.Second, "rpm", "-q", name) return err == nil } return false } func (s *Service) resolve(appID, version string) (AppDef, Version, error) { def, ok := lookupApp(appID) if !ok { return AppDef{}, Version{}, os.ErrNotExist } ver, ok := lookupVersion(def, version) if !ok { return AppDef{}, Version{}, os.ErrInvalid } if runtime.GOOS != "linux" { return AppDef{}, Version{}, os.ErrPermission } if os.Geteuid() != 0 { return AppDef{}, Version{}, os.ErrPermission } return def, ver, nil } // supportedOn reports whether the catalog entry can be installed on the host. // Tarball based apps work on every glibc Linux; package based ones declare the // family they support. func supportedOn(def AppDef, distro system.Distro) bool { if runtime.GOOS != "linux" { return false } return familySupported(def.Family, distro.Family) } func familySupported(appFamily, distroFamily string) bool { if distroFamily != "debian" && distroFamily != "rhel" { return false } switch appFamily { case "", "any": return true default: return appFamily == distroFamily } } func (s *Service) detect(ctx context.Context, appID string) ([]Installed, bool) { switch appID { case "nginx": return detectBinary(ctx, "nginx", []string{"-v"}, nginxVersion, true), serviceActive(ctx, "nginx") case "mariadb": out, _ := command(ctx, 3*time.Second, "mariadb", "--version") if out == "" { out, _ = command(ctx, 3*time.Second, "mysqld", "--version") } if !strings.Contains(strings.ToLower(out), "mariadb") { return nil, false } return installedFromOutput(out, mysqlVersion, true), serviceActive(ctx, "mariadb") case "mysql": out, _ := command(ctx, 3*time.Second, "mysqld", "--version") if out == "" { out, _ = command(ctx, 3*time.Second, "mysql", "--version") } list := detectDir(mysqlRoot, "bin/mysqld") if !strings.Contains(strings.ToLower(out), "mariadb") { list = mergeInstalled(list, installedFromOutput(out, mysqlVersion, true)) } return list, serviceActive(ctx, "mysql") case "go": list := detectDir(goRoot, "bin/go") list = mergeInstalled(list, detectBinary(ctx, "go", []string{"version"}, goVersion, false)) return list, false case "node": list := detectDir(nodeRoot, "bin/node") list = mergeInstalled(list, detectBinary(ctx, "node", []string{"-v"}, nodeVersion, false)) return list, false case "python": list := detectDir(pythonRoot, "bin/python3") list = mergeInstalled(list, detectBinary(ctx, "python3", []string{"-V"}, pythonVersion, false)) return list, false case "php": return detectPHP(ctx), false case "phpmyadmin": return detectDirs(s.webRoot(), "phpmyadmin", "index.php"), false case "git": return detectBinary(ctx, "git", []string{"--version"}, gitVersion, true), false case "docker": return detectBinary(ctx, "docker", []string{"--version"}, dockerVersion, true), serviceActive(ctx, "docker") } return nil, false } func (s *Service) webRoot() string { if s.cfg != nil && s.cfg.WebRoot != "" { return s.cfg.WebRoot } return "/www/wwwroot" } func detectBinary(ctx context.Context, name string, args []string, parse func(string) string, managed bool) []Installed { out, err := command(ctx, 4*time.Second, name, args...) if err != nil || out == "" { return nil } ver := parse(out) if ver == "" { return nil } path, _ := exec.LookPath(name) return []Installed{{Version: ver, Path: path, Active: true, Managed: managed}} } func detectDir(root, binRel string) []Installed { entries, err := os.ReadDir(root) if err != nil { return nil } active := currentTarget(root) var out []Installed for _, entry := range entries { if !entry.IsDir() || entry.Name() == "current" { continue } bin := filepath.Join(root, entry.Name(), binRel) if st, err := os.Stat(bin); err != nil || st.IsDir() { continue } out = append(out, Installed{ Version: entry.Name(), Path: bin, Active: active == entry.Name(), Managed: true, }) } sortInstalled(out) return out } func currentTarget(root string) string { target, err := filepath.EvalSymlinks(filepath.Join(root, "current")) if err != nil { return "" } return filepath.Base(target) } func detectPHP(ctx context.Context) []Installed { seen := map[string]bool{} var out []Installed if entries, err := os.ReadDir("/run/php"); err == nil { for _, entry := range entries { name := entry.Name() if !strings.HasPrefix(name, "php") || !strings.HasSuffix(name, "-fpm.sock") { continue } ver := strings.TrimSuffix(strings.TrimPrefix(name, "php"), "-fpm.sock") if ver == "" || seen[ver] { continue } seen[ver] = true out = append(out, Installed{Version: ver, Path: "/run/php/" + name, Active: true, Managed: true}) } } if entries, err := os.ReadDir(phpRoot); err == nil { for _, entry := range entries { if !entry.IsDir() || seen[entry.Name()] { continue } bin := filepath.Join(phpRoot, entry.Name(), "bin/php") if st, err := os.Stat(bin); err == nil && !st.IsDir() { seen[entry.Name()] = true out = append(out, Installed{Version: entry.Name(), Path: bin, Active: true, Managed: true}) } } } if len(out) == 0 { if o, err := command(ctx, 3*time.Second, "php", "-v"); err == nil { out = installedFromOutput(o, phpVersion, true) } } sortInstalled(out) return out } func detectDirs(root, sub, marker string) []Installed { base := filepath.Join(root, sub) entries, err := os.ReadDir(base) if err != nil { return nil } active := currentTarget(base) var out []Installed for _, entry := range entries { if !entry.IsDir() || entry.Name() == "current" { continue } if _, err := os.Stat(filepath.Join(base, entry.Name(), marker)); err != nil { continue } out = append(out, Installed{ Version: entry.Name(), Path: filepath.Join(base, entry.Name()), Active: active == entry.Name(), Managed: true, }) } sortInstalled(out) return out } func installedFromOutput(out string, parse func(string) string, managed bool) []Installed { ver := parse(out) if ver == "" { return nil } return []Installed{{Version: ver, Path: "", Active: true, Managed: managed}} } func mergeInstalled(a, b []Installed) []Installed { seen := map[string]bool{} var out []Installed for _, item := range append(a, b...) { if item.Version == "" || seen[item.Version] { continue } seen[item.Version] = true out = append(out, item) } sortInstalled(out) return out } func sortInstalled(list []Installed) { sort.Slice(list, func(i, j int) bool { return compareVersion(list[i].Version, list[j].Version) > 0 }) } func compareVersion(a, b string) int { pa := strings.FieldsFunc(strings.TrimPrefix(a, "v"), func(r rune) bool { return r == '.' || r == '-' || r == '_' }) pb := strings.FieldsFunc(strings.TrimPrefix(b, "v"), func(r rune) bool { return r == '.' || r == '-' || r == '_' }) for i := 0; i < len(pa) || i < len(pb); i++ { var na, nb int if i < len(pa) { na, _ = strconv.Atoi(pa[i]) } if i < len(pb) { nb, _ = strconv.Atoi(pb[i]) } if na != nb { if na > nb { return 1 } return -1 } } return 0 } func serviceActive(ctx context.Context, unit string) bool { out, err := command(ctx, 3*time.Second, "systemctl", "is-active", unit) return err == nil && strings.TrimSpace(out) == "active" } func command(ctx context.Context, timeout time.Duration, name string, args ...string) (string, error) { runCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() out, err := exec.CommandContext(runCtx, name, args...).CombinedOutput() return strings.TrimSpace(string(out)), err } var ( nginxVersion = func(s string) string { return firstMatch(s, `nginx/([0-9][0-9.]*)`) } goVersion = func(s string) string { return firstMatch(s, `go([0-9][0-9.]*)`) } nodeVersion = func(s string) string { return firstMatch(s, `v?([0-9][0-9.]*)`) } pythonVersion = func(s string) string { return firstMatch(s, `Python ([0-9][0-9.]*)`) } phpVersion = func(s string) string { return firstMatch(s, `PHP ([0-9][0-9.]*)`) } mysqlVersion = func(s string) string { return firstMatch(s, `(?:Distrib |Ver )?([0-9]+\.[0-9]+\.[0-9]+)`) } gitVersion = func(s string) string { return firstMatch(s, `git version ([0-9][0-9.]*)`) } dockerVersion = func(s string) string { return firstMatch(s, `Docker version ([0-9][0-9.]*)`) } ) func firstMatch(s, pattern string) string { m := regexp.MustCompile(pattern).FindStringSubmatch(s) if len(m) < 2 { return "" } return m[1] }