main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "math/rand"
  7. "os"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "github.com/BurntSushi/toml"
  12. "github.com/judwhite/go-svc"
  13. "github.com/mreiferson/go-options"
  14. "github.com/nsqio/nsq/internal/lg"
  15. "github.com/nsqio/nsq/internal/version"
  16. "github.com/nsqio/nsq/nsqd"
  17. )
  18. type program struct {
  19. once sync.Once
  20. nsqd *nsqd.NSQD
  21. }
  22. func main() {
  23. prg := &program{}
  24. if err := svc.Run(prg, syscall.SIGINT, syscall.SIGTERM); err != nil {
  25. logFatal("%s", err)
  26. }
  27. }
  28. func (p *program) Init(env svc.Environment) error {
  29. opts := nsqd.NewOptions()
  30. flagSet := nsqdFlagSet(opts)
  31. flagSet.Parse(os.Args[1:])
  32. rand.Seed(time.Now().UTC().UnixNano())
  33. if flagSet.Lookup("version").Value.(flag.Getter).Get().(bool) {
  34. fmt.Println(version.String("smqd"))
  35. os.Exit(0)
  36. }
  37. var cfg config
  38. configFile := flagSet.Lookup("config").Value.String()
  39. if configFile != "" {
  40. _, err := toml.DecodeFile(configFile, &cfg)
  41. if err != nil {
  42. logFatal("failed to load config file %s - %s", configFile, err)
  43. }
  44. }
  45. cfg.Validate()
  46. options.Resolve(opts, flagSet, cfg)
  47. nsqd, err := nsqd.New(opts)
  48. if err != nil {
  49. logFatal("failed to instantiate smqd - %s", err)
  50. }
  51. p.nsqd = nsqd
  52. return nil
  53. }
  54. func (p *program) Start() error {
  55. err := p.nsqd.LoadMetadata()
  56. if err != nil {
  57. logFatal("failed to load metadata - %s", err)
  58. }
  59. err = p.nsqd.PersistMetadata()
  60. if err != nil {
  61. logFatal("failed to persist metadata - %s", err)
  62. }
  63. go func() {
  64. err := p.nsqd.Main()
  65. if err != nil {
  66. p.Stop()
  67. os.Exit(1)
  68. }
  69. }()
  70. return nil
  71. }
  72. func (p *program) Stop() error {
  73. p.once.Do(func() {
  74. p.nsqd.Exit()
  75. })
  76. return nil
  77. }
  78. func (p *program) Handle(s os.Signal) error {
  79. return svc.ErrStop
  80. }
  81. // Context returns a context that will be canceled when nsqd initiates the shutdown
  82. func (p *program) Context() context.Context {
  83. return p.nsqd.Context()
  84. }
  85. func logFatal(f string, args ...interface{}) {
  86. lg.LogFatal("[smqd] ", f, args...)
  87. }