package plugins import ( "context" "fmt" "net" "net/http" "os" "path/filepath" "strings" "time" ) const pluginUser = "mp" func unitName(slug string) string { return "miaopanel-plugin-" + slug } func (s *Service) unitPath(slug string) string { return filepath.Join("/etc/systemd/system", unitName(slug)+".service") } // ensureServiceUser creates the unprivileged account service plugins run as. func (s *Service) ensureServiceUser(ctx context.Context) error { if _, err := s.runner.RunLong(ctx, 15*time.Second, "id", "-u", pluginUser); err == nil { return nil } if _, err := s.runner.RunLong(ctx, 60*time.Second, "useradd", "-r", "-s", "/sbin/nologin", "-d", "/var/lib/miaopanel-plugins", pluginUser); err != nil { return fmt.Errorf("创建插件运行用户失败: %w", err) } return os.MkdirAll("/var/lib/miaopanel-plugins", 0o755) } // writeUnit renders and installs the systemd unit of a service plugin. func (s *Service) writeUnit(ctx context.Context, slug string, m *Manifest) error { spec := m.Runtime.Service if spec == nil { return fmt.Errorf("插件 %s 缺少 service 配置", slug) } dir := s.cfg.PluginDir(slug) dataDir := s.cfg.PluginDataDir(slug) if err := os.MkdirAll(dataDir, 0o755); err != nil { return err } if err := s.ensureServiceUser(ctx); err != nil { return err } _, _ = s.runner.RunLong(ctx, 30*time.Second, "chown", "-R", pluginUser+":"+pluginUser, dataDir) execPath := filepath.Join(dir, filepath.FromSlash(spec.Exec)) var args []string for _, a := range spec.Args { args = append(args, quoteUnitArg(s.substitute(a, slug, m.Version))) } execStart := execPath if len(args) > 0 { execStart += " " + strings.Join(args, " ") } restart := spec.Restart switch restart { case "always", "on-failure", "no": default: restart = "on-failure" } memory := "" if spec.MemoryMaxMB > 0 { memory = fmt.Sprintf("MemoryMax=%dM\n", spec.MemoryMaxMB) } unit := fmt.Sprintf(`[Unit] Description=MiaoPanel plugin: %s After=network-online.target Wants=network-online.target [Service] Type=simple User=%s Group=%s WorkingDirectory=%s ExecStart=%s Restart=%s RestartSec=3 NoNewPrivileges=yes PrivateTmp=yes ProtectSystem=strict ProtectHome=yes ReadWritePaths=%s %sEnvironment=MP_SLUG=%s Environment=MP_VERSION=%s Environment=MP_DIR=%s Environment=MP_DATA_DIR=%s Environment=MP_SOCKET=%s Environment=MP_PANEL_VERSION=%s Environment=HOME=%s [Install] WantedBy=multi-user.target `, m.Name, pluginUser, pluginUser, quoteUnitArg(dir), execStart, restart, dataDir, memory, slug, m.Version, quoteUnitArg(dir), quoteUnitArg(dataDir), quoteUnitArg(s.socketPath(slug)), s.version, quoteUnitArg(dataDir)) if err := os.MkdirAll("/etc/systemd/system", 0o755); err != nil { return err } if err := os.WriteFile(s.unitPath(slug), []byte(unit), 0o644); err != nil { return err } if _, err := s.runner.RunLong(ctx, 60*time.Second, "systemctl", "daemon-reload"); err != nil { return err } return nil } func (s *Service) removeUnit(ctx context.Context, slug string) error { _, _ = s.runner.RunLong(ctx, 60*time.Second, "systemctl", "disable", "--now", unitName(slug)) if err := os.Remove(s.unitPath(slug)); err != nil && !os.IsNotExist(err) { return err } _, err := s.runner.RunLong(ctx, 60*time.Second, "systemctl", "daemon-reload") return err } // healthCheck waits for the socket and, when declared, the health endpoint. func (s *Service) healthCheck(ctx context.Context, slug string, m *Manifest) error { socket := s.socketPath(slug) deadline := time.Now().Add(30 * time.Second) health := "" if m.Runtime.Service != nil { health = m.Runtime.Service.Health } client := &http.Client{ Timeout: 3 * time.Second, Transport: &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, "unix", socket) }, }, } for time.Now().Before(deadline) { if _, err := os.Stat(socket); err == nil { if health == "" { return nil } req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://plugin"+health, nil) res, err := client.Do(req) if err == nil { res.Body.Close() if res.StatusCode < 500 { return nil } } } select { case <-ctx.Done(): return ctx.Err() case <-time.After(time.Second): } } if health == "" { return fmt.Errorf("插件服务在 30 秒内没有创建套接字 %s", socket) } return fmt.Errorf("插件健康检查 %s 未在 30 秒内通过", health) } func (s *Service) substitute(value, slug, version string) string { replacer := strings.NewReplacer( "${MP_DIR}", s.cfg.PluginDir(slug), "${MP_DATA_DIR}", s.cfg.PluginDataDir(slug), "${MP_SOCKET}", s.socketPath(slug), "${MP_VERSION}", version, ) return replacer.Replace(value) } func quoteUnitArg(s string) string { if s == "" { return `""` } if !strings.ContainsAny(s, " \t\"'\\") { return s } s = strings.ReplaceAll(s, `\`, `\\`) s = strings.ReplaceAll(s, `"`, `\"`) return `"` + s + `"` }