| 50 | } |
| 51 | |
| 52 | func start(c *cli.Context) error { |
| 53 | ctx, cancel := context.WithCancel(context.Background()) |
| 54 | defer cancel() |
| 55 | wg := sync.WaitGroup{} |
| 56 | errSignal := make(chan error) |
| 57 | p, err := proxy.New() |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | |
| 62 | wg.Add(1) |
| 63 | fmt.Println("listener port:", config.Get().Proxy.LocalPort) |
| 64 | utils.GoWithRecover(func() { |
| 65 | defer wg.Done() |
| 66 | p.Run(ctx, errSignal) |
| 67 | }, nil) |
| 68 | err = <-errSignal |
| 69 | |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | |
| 74 | // Listening to the offline |
| 75 | sigs := make(chan os.Signal, 1) |
| 76 | signal.Notify(sigs, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) |
| 77 | for sig := range sigs { |
| 78 | switch sig { |
| 79 | case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT: |
| 80 | logrus.Info("Received shutdown signal, initiating graceful shutdown...") |
| 81 | cancel() |
| 82 | |
| 83 | // Use sync.Once to ensure shutdown is only performed once |
| 84 | var once sync.Once |
| 85 | once.Do(func() { |
| 86 | ok := make(chan struct{}) |
| 87 | go func() { |
| 88 | wg.Wait() |
| 89 | close(ok) |
| 90 | }() |
| 91 | |
| 92 | select { |
| 93 | case <-ok: |
| 94 | logrus.Info("All goroutines have gracefully shut down.") |
| 95 | case <-time.After(time.Second * 5): |
| 96 | logrus.Warn("Context deadline exceeded, forcing shutdown.") |
| 97 | } |
| 98 | |
| 99 | os.Exit(0) |
| 100 | }) |
| 101 | |
| 102 | case syscall.SIGHUP: |
| 103 | logrus.Info("Received SIGHUP signal, performing reload or reconfiguration if supported.") |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | return nil |
| 108 | } |
| 109 | |