Skip to content

Commit

Permalink
add ReadyEvent fired when proxy can serve connections
Browse files Browse the repository at this point in the history
  • Loading branch information
robinbraemer committed Aug 16, 2020
1 parent cbf938d commit 58cf99d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
4 changes: 4 additions & 0 deletions pkg/proxy/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,10 @@ func (s *PreShutdownEvent) SetReason(reason component.Component) {
//
//

// ReadyEvent is fired once the proxy was successfully
// initialized and is ready to serve connections.
type ReadyEvent struct{}

// ShutdownEvent is fired by the proxy after the proxy
// has stopped accepting connections and PreShutdownEvent,
// but before the proxy process exits.
Expand Down
23 changes: 16 additions & 7 deletions pkg/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"go.minekube.com/gate/pkg/util"
"go.minekube.com/gate/pkg/util/favicon"
"go.minekube.com/gate/pkg/util/sets"
"go.uber.org/atomic"
"go.uber.org/zap"
rpc "google.golang.org/grpc/health/grpc_health_v1"
"net"
Expand All @@ -34,6 +35,7 @@ type Proxy struct {
channelRegistrar *ChannelRegistrar
authenticator *auth.Authenticator

runOnce atomic.Bool
closeOnce sync.Once
closed chan struct{}

Expand All @@ -60,17 +62,17 @@ func New(config config.Config) (s *Proxy) {
}
}

// Returned by Proxy.Run if the proxy instance was already run.
var ErrProxyAlreadyRun = errors.New("proxy was already run, create a new one")

// Run runs the proxy and blocks until Shutdown is called or an error occurred.
// Run can only be called once per Proxy instance.
func (p *Proxy) Run() (err error) {
select {
default:
// Make sure Shutdown is at least called once.
defer p.Shutdown(nil)
return p.run()
case <-p.closed:
return errors.New("proxy was already run, create a new one")
if !p.runOnce.CAS(false, true) {
return ErrProxyAlreadyRun
}
defer p.Shutdown(nil) // Make sure Shutdown is at least called once.
return p.run() // Run and block
}

// Shutdown shuts down the Proxy and blocks until finished.
Expand Down Expand Up @@ -171,6 +173,13 @@ func (p *Proxy) run() error {
errChan <- p.connect.listenAndServe(p.config.Bind, p.closed)
}()

select {
case err := <-errChan:
return err
default:
p.event.Fire(&ReadyEvent{})
}

return <-errChan
}

Expand Down

0 comments on commit 58cf99d

Please sign in to comment.