Skip to content

Commit

Permalink
Implement graceful server shutdown and update port settings
Browse files Browse the repository at this point in the history
Added signal handling in server.go to support graceful shutdown upon receiving an interrupt or termination signal. Updated docker-compose.yml and Dockerfile to adjust port ranges for better resource management.
  • Loading branch information
mjm918 committed Aug 15, 2024
1 parent 7a1561d commit 3f09298
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 16 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ COPY . .
RUN go build -o jerusalem-tunnel -v ./...
ENTRYPOINT ["./jerusalem-tunnel"]

EXPOSE 1024-65535
EXPOSE 1024-1100
8 changes: 4 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ services:
jerusalem-tunnel:
build: .
ports:
- "1024-2000:1024-2000"
- "8901:8901"
- "1024-1100:1024-1100"
- "1024:1024"
environment:
- SERVER_PORT=8901
- PORT_RANGE=1024...2000
- SERVER_PORT=1024
- PORT_RANGE=1024...1100
- SECRET_KEY=2y6sUp8cBSfNDk7Jq5uLm0xHAIOb9ZGqE4hR1WVXtCwKjP3dYzvTn2QiFXe8rMb6
entrypoint: [ "./jerusalem-tunnel" ]
restart: always
48 changes: 37 additions & 11 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"log"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
Expand Down Expand Up @@ -74,19 +75,44 @@ func (s *Server) StartServer() error {
}
log.Printf("Server listening on %s\n", a)

// Create a channel to listen for an interrupt or termination signal.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
shutdownCh := make(chan struct{})

// Goroutine to handle shutdown signal.
go func() {
<-sigCh
log.Println("Shutdown signal received, closing server...")
close(shutdownCh)
l.Close() // Close the listener to stop accepting new connections
}()

for {
c, e := l.Accept()
if e != nil {
return fmt.Errorf("error accepting connection: %w", e)
}
go func() {
log.Println("Incoming connection")
if e := s.handleConnection(c); e != nil {
log.Printf("Connection exited with error: %v\n", e)
} else {
log.Println("Connection exited")
select {
case <-shutdownCh:
log.Println("Server gracefully shut down")
return nil
default:
c, e := l.Accept()
if e != nil {
select {
case <-shutdownCh:
log.Println("Listener closed, shutting down connection handler")
return nil
default:
return fmt.Errorf("error accepting connection: %w", e)
}
}
}()
go func() {
log.Println("Incoming connection")
if e := s.handleConnection(c); e != nil {
log.Printf("Connection exited with error: %v\n", e)
} else {
log.Println("Connection exited")
}
}()
}
}
}

Expand Down

0 comments on commit 3f09298

Please sign in to comment.