-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathweb_runner.go
356 lines (296 loc) · 8.45 KB
/
web_runner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
"github.com/launchrctl/launchr"
"github.com/launchrctl/web/server"
)
const (
backgroundEnvVar = "LAUNCHR_BACKGROUND"
serverInfoFilename = "server-info.json"
)
func isBackGroundEnv() bool {
return len(os.Getenv(backgroundEnvVar)) == 1
}
func (p *Plugin) runWeb(ctx context.Context, webOpts webFlags) error {
var err error
port := webOpts.Port
if !isAvailablePort(port) {
launchr.Term().Warning().Printfln("The port %d you are trying to use for the web server is not available.", port)
port, err = getAvailablePort(port)
if err != nil {
return err
}
}
swaggerFS, _ := GetSwaggerUIAssetsFS()
serverOpts := &server.RunOptions{
Addr: fmt.Sprintf(":%d", port), // @todo use proper addr
APIPrefix: APIPrefix,
SwaggerJSON: webOpts.UseSwaggerUI,
ProxyClient: webOpts.ProxyClient,
ClientFS: GetClientAssetsFS(),
SwaggerUIFS: swaggerFS,
}
go func() {
time.Sleep(time.Second)
err := openInBrowserWhenReady(serverOpts.BaseURL())
if err != nil {
launchr.Term().Error().Println(err)
}
}()
err = storeServerInfo(serverInfo{URL: serverOpts.BaseURL()}, webOpts.PluginDir)
if err != nil {
return err
}
defer cleanupPluginTemp(webOpts.PluginDir)
return server.Run(ctx, p.app, serverOpts)
}
func (p *Plugin) runBackgroundWeb(cmd *launchr.Command, flags webFlags, pidFile string) error {
if isBackGroundEnv() {
err := redirectOutputs(flags.PluginDir)
if err != nil {
return err
}
return p.runWeb(cmd.Context(), flags)
}
pid, err := runBackgroundCmd(cmd, pidFile)
if err != nil {
return err
}
// Wait until background server is up.
// Check if run info created and server is reachable.
// Print server URL in CLI.
// Kill process in case of timeout
timeout := time.After(10 * time.Second)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-timeout:
// Kill existing process
_ = killProcess(pid)
// Cleanup temp dir
cleanupPluginTemp(flags.PluginDir)
return errors.New("couldn't start background process")
case <-ticker.C:
info, _ := getServerInfo(flags.PluginDir)
if info == nil {
continue
}
launchr.Term().Info().Printfln("Web is running in the background (pid: %d)\nURL: %s", pid, info.URL)
return nil
}
}
}
func stopWeb(pidFile, pluginDir string) (err error) {
onSuccess := "The web UI has been successfully shut down."
// Try to finish the background process.
pid, ok := pidFileInfo(pidFile)
if pid != 0 && ok {
err = interruptProcess(pid)
if err != nil {
return err
}
launchr.Term().Success().Println(onSuccess)
return nil
}
// If we don't have pid, probably there is a server running in foreground.
// We may also not have access to the pid file, prompt user the same.
serverRunInfo, err := getServerInfo(pluginDir)
if err != nil {
return err
}
if serverRunInfo == nil || serverRunInfo.URL == "" {
launchr.Term().Warning().Println("There is no active Web UI that can be stopped.")
return nil
}
if checkHealth(serverRunInfo.URL) {
return fmt.Errorf("the web UI is currently running at %s\nPlease stop it through the user interface or terminate the process", serverRunInfo.URL)
}
launchr.Term().Success().Println(onSuccess)
return nil
}
func runBackgroundCmd(cmd *launchr.Command, pidFile string) (int, error) {
err := launchr.EnsurePath(filepath.Dir(pidFile))
if err != nil {
return 0, fmt.Errorf("cannot create tmp directory for %q", pidFile)
}
// Prepare the command to restart itself in the background
args := append([]string{cmd.Name()}, os.Args[2:]...)
command := exec.Command(os.Args[0], args...) //nolint G204
command.Env = append(os.Environ(), backgroundEnvVar+"=1")
// Set platform-specific process ID
setSysProcAttr(command)
err = command.Start()
if err != nil {
return 0, fmt.Errorf("failed to start the process in background: %w", err)
}
err = os.WriteFile(pidFile, []byte(strconv.Itoa(command.Process.Pid)), os.FileMode(0644))
if err != nil {
return 0, fmt.Errorf("failed to write PID file: %w", err)
}
return command.Process.Pid, nil
}
func redirectOutputs(dir string) error {
err := launchr.EnsurePath(dir)
if err != nil {
return fmt.Errorf("can't create plugin temporary directory")
}
outLog, err := os.Create(filepath.Join(dir, "out.log")) //nolint G304 // Path is clean.
if err != nil {
return err
}
// Redirect log messages to a file.
launchr.Log().SetOutput(outLog)
// Discard console output because it's intended for user interaction.
launchr.Term().SetOutput(io.Discard)
return nil
}
// serverInfo is structure that stores current running server metadata.
type serverInfo struct {
// URL holds the server's publicly accessible URL.
URL string `json:"url"`
}
func storeServerInfo(ri serverInfo, storePath string) error {
out, err := json.Marshal(&ri)
if err != nil {
return err
}
err = os.MkdirAll(storePath, 0750)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(storePath, serverInfoFilename), out, os.FileMode(0640))
if err != nil {
return err
}
return nil
}
func cleanupPluginTemp(dir string) {
err := os.RemoveAll(dir)
if err != nil {
launchr.Log().Warn("error on server info cleanup", "error", err)
}
}
// checkHealth helper to check if server is available by request.
func checkHealth(url string) bool {
resp, err := http.Head(url) //nolint G107 // @todo URL may come from user input, potential vulnerability.
if err != nil {
// Error is thrown on an incorrect url.
panic(err)
}
_ = resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// getServerInfo lookups server run info metadata and tries to get it from storage.
func getServerInfo(dir string) (*serverInfo, error) {
path := filepath.Clean(filepath.Join(dir, serverInfoFilename))
_, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, nil
} else if err != nil {
return nil, err
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("error reading plugin storage path: %w", err)
}
var info serverInfo
err = json.Unmarshal(data, &info)
if err != nil {
return nil, fmt.Errorf("error unmarshalling json: %w", err)
}
return &info, nil
}
func getExistingWeb(pidFile string, pluginDir string) (string, error) {
if isBackGroundEnv() {
// The case was checked on the init step.
return "", nil
}
serverRunInfo, err := getServerInfo(pluginDir)
if err != nil {
launchr.Log().Warn("error on getting server run info", "error", err)
return "", err
}
if serverRunInfo == nil || serverRunInfo.URL == "" {
// No server.
return "", nil
}
if _, ok := pidFileInfo(pidFile); ok {
return serverRunInfo.URL, nil
}
if !checkHealth(serverRunInfo.URL) {
return serverRunInfo.URL, errors.New("web: unhealthy response")
}
return serverRunInfo.URL, nil
}
func getAvailablePort(port int) (int, error) {
// Quick check if port available and return if yes.
if isAvailablePort(port) {
return port, nil
}
maxPort := 65535
newPort := 49152
// Check available port from pool.
for !isAvailablePort(newPort) && newPort < maxPort {
launchr.Log().Debug("port is not available", "port", newPort)
newPort++
}
if newPort >= maxPort && !isAvailablePort(newPort) {
panic("port limit exceeded")
}
return newPort, nil
}
func isAvailablePort(port int) bool {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return false
}
_ = listener.Close()
return true
}
func openInBrowserWhenReady(url string) error {
// Wait until the service is healthy.
retries := 0
for !checkHealth(url) {
time.Sleep(time.Second)
if retries == 10 {
return errors.New("the service is unhealthy")
}
retries++
if retries == 3 {
launchr.Term().Info().Println("The server isn't ready yet, please standby...")
}
launchr.Log().Debug("waiting for server to start", "retries", retries)
}
// Open the browser
launchr.Term().Info().Printfln("You can reach the web server at this URL: %s", url)
if err := openBrowser(url); err != nil {
launchr.Log().Error("failed to open browser", "error", err)
return fmt.Errorf("Failed to open browser: %w", err)
}
return nil
}
func openBrowser(url string) error {
switch runtime.GOOS {
case "linux":
return exec.Command("xdg-open", url).Start()
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
return exec.Command("open", url).Start()
default:
return fmt.Errorf("unsupported platform")
}
}