Close this server with deadline.
(ctx context.Context)
| 59 | |
| 60 | // Close this server with deadline. |
| 61 | func (s *server) Close(ctx context.Context) error { |
| 62 | s.operator.Control(PollDetach) |
| 63 | s.ln.Close() |
| 64 | |
| 65 | for { |
| 66 | activeConn := 0 |
| 67 | s.connections.Range(func(key, value interface{}) bool { |
| 68 | conn, ok := value.(gracefulExit) |
| 69 | if !ok || conn.isIdle() { |
| 70 | value.(Connection).Close() |
| 71 | } else { |
| 72 | activeConn++ |
| 73 | } |
| 74 | return true |
| 75 | }) |
| 76 | if activeConn == 0 { // all connections have been closed |
| 77 | return nil |
| 78 | } |
| 79 | |
| 80 | // smart control graceful shutdown check internal |
| 81 | // we should wait for more time if there are more active connections |
| 82 | waitTime := time.Millisecond * time.Duration(activeConn) |
| 83 | if waitTime > time.Second { // max wait time is 1000 ms |
| 84 | waitTime = time.Millisecond * 1000 |
| 85 | } else if waitTime < time.Millisecond*50 { // min wait time is 50 ms |
| 86 | waitTime = time.Millisecond * 50 |
| 87 | } |
| 88 | select { |
| 89 | case <-ctx.Done(): |
| 90 | return ctx.Err() |
| 91 | case <-time.After(waitTime): |
| 92 | continue |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // OnRead implements FDOperator. |
| 98 | func (s *server) OnRead(p Poll) error { |