File tree Expand file tree Collapse file tree 3 files changed +80
-0
lines changed
Expand file tree Collapse file tree 3 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "fmt"
5+ "os"
6+ "strconv"
7+ "strings"
8+ "syscall"
9+ )
10+
11+ func killServerCommand () error {
12+ socketPath , err := getSocketPath (CLI .Socket )
13+ if err != nil {
14+ return fmt .Errorf (
15+ "failed to detect socket path: %s" ,
16+ err ,
17+ )
18+ }
19+
20+ pidPath := getPidPath (socketPath )
21+ data , err := os .ReadFile (pidPath )
22+ if err != nil {
23+ return fmt .Errorf (
24+ "no server running (could not read %s)" ,
25+ pidPath ,
26+ )
27+ }
28+
29+ pid , err := strconv .Atoi (strings .TrimSpace (string (data )))
30+ if err != nil {
31+ return fmt .Errorf (
32+ "invalid PID in %s: %s" ,
33+ pidPath ,
34+ err ,
35+ )
36+ }
37+
38+ process , err := os .FindProcess (pid )
39+ if err != nil {
40+ return fmt .Errorf (
41+ "could not find process %d: %s" ,
42+ pid ,
43+ err ,
44+ )
45+ }
46+
47+ if err := process .Signal (syscall .SIGTERM ); err != nil {
48+ return fmt .Errorf (
49+ "failed to kill server (pid %d): %s" ,
50+ pid ,
51+ err ,
52+ )
53+ }
54+
55+ _ = os .Remove (pidPath )
56+ _ = os .Remove (socketPath )
57+
58+ return nil
59+ }
Original file line number Diff line number Diff line change @@ -31,6 +31,8 @@ var CLI struct {
3131 CPU string `help:"Save a CPU performance report to the given path." name:"perf-file" optional:"" default:""`
3232 Trace string `help:"Save a trace report to the given path." name:"trace-file" optional:"" default:""`
3333 } `cmd:"" default:"1" aliases:"attach" help:"Connect to the cy server, starting one if necessary."`
34+
35+ KillServer struct {} `cmd:"" name:"kill-server" help:"Kill the cy server."`
3436}
3537
3638func writeError (err error ) {
@@ -113,5 +115,10 @@ func main() {
113115 if err != nil {
114116 writeError (err )
115117 }
118+ case "kill-server" :
119+ err := killServerCommand ()
120+ if err != nil {
121+ writeError (err )
122+ }
116123 }
117124}
Original file line number Diff line number Diff line change @@ -19,6 +19,10 @@ func getLockPath(socketPath string) string {
1919 return socketPath + ".lock"
2020}
2121
22+ func getPidPath (socketPath string ) string {
23+ return socketPath + ".pid"
24+ }
25+
2226type Server struct {
2327 cy * cy.Cy
2428}
@@ -146,6 +150,16 @@ func getConfig() (string, error) {
146150}
147151
148152func serve (path string ) error {
153+ pidPath := getPidPath (path )
154+ if err := os .WriteFile (
155+ pidPath ,
156+ []byte (fmt .Sprintf ("%d" , os .Getpid ())),
157+ 0600 ,
158+ ); err != nil {
159+ return err
160+ }
161+ defer func () { _ = os .Remove (pidPath ) }()
162+
149163 cwd , err := os .Getwd ()
150164 if err != nil {
151165 return err
You can’t perform that action at this time.
0 commit comments