Skip to content

Commit

Permalink
fix(ipc): ovm crash when client closed connection (#53)
Browse files Browse the repository at this point in the history
Signed-off-by: Kevin Cui <[email protected]>
  • Loading branch information
BlackHole1 authored Aug 23, 2024
1 parent dcd239e commit 8bb86b6
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions pkg/ipc/restful/restful.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,23 +162,30 @@ func (s *Restful) mux() *http.ServeMux {
}

outCh := infinity.NewChannel[string]()
errCh := make(chan string)
doneCh := make(chan struct{})
errCh := make(chan string, 1)
doneCh := make(chan struct{}, 1)

go func() {
if err := s.exec(body.Command, outCh, errCh); err != nil {
if err := s.exec(r.Context(), body.Command, outCh, errCh); err != nil {
s.log.Warnf("Failed to execute command: %v", err)
}

_, _ = fmt.Fprintf(w, "event: done\n")
_, _ = fmt.Fprintf(w, "data: done\n\n")
w.(http.Flusher).Flush()

doneCh <- struct{}{}
outCh.Close()
close(errCh)
}()

defer func() {
select {
case <-r.Context().Done():
// pass
default:
_, _ = fmt.Fprintf(w, "event: done\n")
_, _ = fmt.Fprintf(w, "data: done\n\n")
w.(http.Flusher).Flush()
}
}()

for {
select {
case <-doneCh:
Expand Down Expand Up @@ -295,7 +302,7 @@ func (s *Restful) powerSaveMode(enable bool) {
s.opt.PowerSaveMode = enable
}

func (s *Restful) exec(command string, outCh *infinity.Channel[string], errCh chan string) error {
func (s *Restful) exec(ctx context.Context, command string, outCh *infinity.Channel[string], errCh chan string) error {
s.log.Info("request /exec")

conf := &ssh.ClientConfig{
Expand All @@ -313,6 +320,10 @@ func (s *Restful) exec(command string, outCh *infinity.Channel[string], errCh ch
}
defer conn.Close()

context.AfterFunc(ctx, func() {
_ = conn.Close()
})

session, err := conn.NewSession()
if err != nil {
errCh <- fmt.Sprintf("new ssh session error: %v", err)
Expand Down

0 comments on commit 8bb86b6

Please sign in to comment.