miaopanel
1package plugins
2
3import (
4 "context"
5 "fmt"
6 "net"
7 "net/http"
8 "os"
9 "path/filepath"
10 "strings"
11 "time"
12)
13
14const pluginUser = "mp"
15
16func unitName(slug string) string { return "miaopanel-plugin-" + slug }
17
18func (s *Service) unitPath(slug string) string {
19 return filepath.Join("/etc/systemd/system", unitName(slug)+".service")
20}
21
22// ensureServiceUser creates the unprivileged account service plugins run as.
23func (s *Service) ensureServiceUser(ctx context.Context) error {
24 if _, err := s.runner.RunLong(ctx, 15*time.Second, "id", "-u", pluginUser); err == nil {
25 return nil
26 }
27 if _, err := s.runner.RunLong(ctx, 60*time.Second, "useradd",
28 "-r", "-s", "/sbin/nologin", "-d", "/var/lib/miaopanel-plugins", pluginUser); err != nil {
29 return fmt.Errorf("创建插件运行用户失败: %w", err)
30 }
31 return os.MkdirAll("/var/lib/miaopanel-plugins", 0o755)
32}
33
34// writeUnit renders and installs the systemd unit of a service plugin.
35func (s *Service) writeUnit(ctx context.Context, slug string, m *Manifest) error {
36 spec := m.Runtime.Service
37 if spec == nil {
38 return fmt.Errorf("插件 %s 缺少 service 配置", slug)
39 }
40 dir := s.cfg.PluginDir(slug)
41 dataDir := s.cfg.PluginDataDir(slug)
42 if err := os.MkdirAll(dataDir, 0o755); err != nil {
43 return err
44 }
45 if err := s.ensureServiceUser(ctx); err != nil {
46 return err
47 }
48 _, _ = s.runner.RunLong(ctx, 30*time.Second, "chown", "-R", pluginUser+":"+pluginUser, dataDir)
49
50 execPath := filepath.Join(dir, filepath.FromSlash(spec.Exec))
51 var args []string
52 for _, a := range spec.Args {
53 args = append(args, quoteUnitArg(s.substitute(a, slug, m.Version)))
54 }
55 execStart := execPath
56 if len(args) > 0 {
57 execStart += " " + strings.Join(args, " ")
58 }
59 restart := spec.Restart
60 switch restart {
61 case "always", "on-failure", "no":
62 default:
63 restart = "on-failure"
64 }
65 memory := ""
66 if spec.MemoryMaxMB > 0 {
67 memory = fmt.Sprintf("MemoryMax=%dM\n", spec.MemoryMaxMB)
68 }
69 unit := fmt.Sprintf(`[Unit]
70Description=MiaoPanel plugin: %s
71After=network-online.target
72Wants=network-online.target
73
74[Service]
75Type=simple
76User=%s
77Group=%s
78WorkingDirectory=%s
79ExecStart=%s
80Restart=%s
81RestartSec=3
82NoNewPrivileges=yes
83PrivateTmp=yes
84ProtectSystem=strict
85ProtectHome=yes
86ReadWritePaths=%s
87%sEnvironment=MP_SLUG=%s
88Environment=MP_VERSION=%s
89Environment=MP_DIR=%s
90Environment=MP_DATA_DIR=%s
91Environment=MP_SOCKET=%s
92Environment=MP_PANEL_VERSION=%s
93Environment=HOME=%s
94
95[Install]
96WantedBy=multi-user.target
97`, m.Name, pluginUser, pluginUser, quoteUnitArg(dir), execStart, restart, dataDir, memory,
98 slug, m.Version, quoteUnitArg(dir), quoteUnitArg(dataDir),
99 quoteUnitArg(s.socketPath(slug)), s.version, quoteUnitArg(dataDir))
100
101 if err := os.MkdirAll("/etc/systemd/system", 0o755); err != nil {
102 return err
103 }
104 if err := os.WriteFile(s.unitPath(slug), []byte(unit), 0o644); err != nil {
105 return err
106 }
107 if _, err := s.runner.RunLong(ctx, 60*time.Second, "systemctl", "daemon-reload"); err != nil {
108 return err
109 }
110 return nil
111}
112
113func (s *Service) removeUnit(ctx context.Context, slug string) error {
114 _, _ = s.runner.RunLong(ctx, 60*time.Second, "systemctl", "disable", "--now", unitName(slug))
115 if err := os.Remove(s.unitPath(slug)); err != nil && !os.IsNotExist(err) {
116 return err
117 }
118 _, err := s.runner.RunLong(ctx, 60*time.Second, "systemctl", "daemon-reload")
119 return err
120}
121
122// healthCheck waits for the socket and, when declared, the health endpoint.
123func (s *Service) healthCheck(ctx context.Context, slug string, m *Manifest) error {
124 socket := s.socketPath(slug)
125 deadline := time.Now().Add(30 * time.Second)
126 health := ""
127 if m.Runtime.Service != nil {
128 health = m.Runtime.Service.Health
129 }
130 client := &http.Client{
131 Timeout: 3 * time.Second,
132 Transport: &http.Transport{
133 DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
134 var d net.Dialer
135 return d.DialContext(ctx, "unix", socket)
136 },
137 },
138 }
139 for time.Now().Before(deadline) {
140 if _, err := os.Stat(socket); err == nil {
141 if health == "" {
142 return nil
143 }
144 req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://plugin"+health, nil)
145 res, err := client.Do(req)
146 if err == nil {
147 res.Body.Close()
148 if res.StatusCode < 500 {
149 return nil
150 }
151 }
152 }
153 select {
154 case <-ctx.Done():
155 return ctx.Err()
156 case <-time.After(time.Second):
157 }
158 }
159 if health == "" {
160 return fmt.Errorf("插件服务在 30 秒内没有创建套接字 %s", socket)
161 }
162 return fmt.Errorf("插件健康检查 %s 未在 30 秒内通过", health)
163}
164
165func (s *Service) substitute(value, slug, version string) string {
166 replacer := strings.NewReplacer(
167 "${MP_DIR}", s.cfg.PluginDir(slug),
168 "${MP_DATA_DIR}", s.cfg.PluginDataDir(slug),
169 "${MP_SOCKET}", s.socketPath(slug),
170 "${MP_VERSION}", version,
171 )
172 return replacer.Replace(value)
173}
174
175func quoteUnitArg(s string) string {
176 if s == "" {
177 return `""`
178 }
179 if !strings.ContainsAny(s, " \t\"'\\") {
180 return s
181 }
182 s = strings.ReplaceAll(s, `\`, `\\`)
183 s = strings.ReplaceAll(s, `"`, `\"`)
184 return `"` + s + `"`
185}