service.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package kos
  2. import (
  3. "context"
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "git.nspix.com/golang/kos/entry"
  8. "git.nspix.com/golang/kos/entry/cli"
  9. "git.nspix.com/golang/kos/entry/http"
  10. "git.nspix.com/golang/kos/pkg/log"
  11. "git.nspix.com/golang/kos/util/env"
  12. "github.com/sourcegraph/conc"
  13. "net"
  14. "net/http/pprof"
  15. "os"
  16. "os/signal"
  17. "runtime"
  18. "strconv"
  19. "sync"
  20. "sync/atomic"
  21. "syscall"
  22. "time"
  23. )
  24. var (
  25. ErrStopping = errors.New("stopping")
  26. cliFlag = flag.Bool("cli", false, "Go application interactive mode")
  27. )
  28. type (
  29. application struct {
  30. ctx context.Context
  31. cancelFunc context.CancelCauseFunc
  32. opts *Options
  33. gateway *entry.Gateway
  34. http *http.Server
  35. command *cli.Server
  36. uptime time.Time
  37. info *Info
  38. plugins sync.Map
  39. waitGroup conc.WaitGroup
  40. exitFlag int32
  41. }
  42. )
  43. func (app *application) Log() log.Logger {
  44. return log.GetLogger()
  45. }
  46. func (app *application) Healthy() string {
  47. if atomic.LoadInt32(&app.gateway.State().Processing) == 1 && atomic.LoadInt32(&app.gateway.State().Accepting) == 1 {
  48. return StateHealthy
  49. }
  50. if atomic.LoadInt32(&app.gateway.State().Processing) == 1 {
  51. return StateNoAccepting
  52. }
  53. if atomic.LoadInt32(&app.gateway.State().Accepting) == 1 {
  54. return StateNoProgress
  55. }
  56. return StateUnavailable
  57. }
  58. func (app *application) Info() *Info {
  59. return app.info
  60. }
  61. func (app *application) Http() *http.Server {
  62. return app.http
  63. }
  64. func (app *application) Command() *cli.Server {
  65. return app.command
  66. }
  67. func (app *application) Handle(path string, cb HandleFunc) {
  68. if app.http != nil {
  69. app.http.Handle(http.MethodPost, path, func(ctx *http.Context) (err error) {
  70. return cb(ctx)
  71. })
  72. }
  73. if app.command != nil {
  74. app.command.Handle(path, "", func(ctx *cli.Context) (err error) {
  75. return cb(ctx)
  76. })
  77. }
  78. }
  79. func (app *application) httpServe() (err error) {
  80. var (
  81. l net.Listener
  82. )
  83. app.http = http.New(app.ctx)
  84. if l, err = app.gateway.Apply(
  85. entry.Feature(http.MethodGet),
  86. entry.Feature(http.MethodHead),
  87. entry.Feature(http.MethodPost),
  88. entry.Feature(http.MethodPut),
  89. entry.Feature(http.MethodPatch),
  90. entry.Feature(http.MethodDelete),
  91. entry.Feature(http.MethodConnect),
  92. entry.Feature(http.MethodOptions),
  93. entry.Feature(http.MethodTrace),
  94. ); err != nil {
  95. return
  96. }
  97. if app.opts.EnableDebug {
  98. app.http.Handle(http.MethodGet, "/debug/pprof/", http.Wrap(pprof.Index))
  99. app.http.Handle(http.MethodGet, "/debug/pprof/goroutine", http.Wrap(pprof.Index))
  100. app.http.Handle(http.MethodGet, "/debug/pprof/heap", http.Wrap(pprof.Index))
  101. app.http.Handle(http.MethodGet, "/debug/pprof/mutex", http.Wrap(pprof.Index))
  102. app.http.Handle(http.MethodGet, "/debug/pprof/threadcreate", http.Wrap(pprof.Index))
  103. app.http.Handle(http.MethodGet, "/debug/pprof/cmdline", http.Wrap(pprof.Cmdline))
  104. app.http.Handle(http.MethodGet, "/debug/pprof/profile", http.Wrap(pprof.Profile))
  105. app.http.Handle(http.MethodGet, "/debug/pprof/symbol", http.Wrap(pprof.Symbol))
  106. app.http.Handle(http.MethodGet, "/debug/pprof/trace", http.Wrap(pprof.Trace))
  107. }
  108. timer := time.NewTimer(time.Millisecond * 200)
  109. defer timer.Stop()
  110. errChan := make(chan error, 1)
  111. app.waitGroup.Go(func() {
  112. select {
  113. case errChan <- app.http.Serve(l):
  114. log.Infof("http server closed")
  115. }
  116. })
  117. select {
  118. case err = <-errChan:
  119. case <-timer.C:
  120. log.Infof("http server started")
  121. }
  122. return
  123. }
  124. func (app *application) commandServe() (err error) {
  125. var (
  126. l net.Listener
  127. )
  128. app.command = cli.New(app.ctx)
  129. if l, err = app.gateway.Apply(
  130. cli.Feature,
  131. ); err != nil {
  132. return
  133. }
  134. timer := time.NewTimer(time.Millisecond * 200)
  135. defer timer.Stop()
  136. errChan := make(chan error, 1)
  137. app.waitGroup.Go(func() {
  138. select {
  139. case errChan <- app.command.Serve(l):
  140. log.Infof("command server closed")
  141. }
  142. })
  143. select {
  144. case err = <-errChan:
  145. case <-timer.C:
  146. log.Infof("command server started")
  147. }
  148. return
  149. }
  150. func (app *application) gotoInteractive() (err error) {
  151. var (
  152. client *cli.Client
  153. )
  154. client = cli.NewClient(
  155. app.ctx,
  156. net.JoinHostPort(app.opts.Address, strconv.Itoa(app.opts.Port)),
  157. )
  158. return client.Shell()
  159. }
  160. func (app *application) buildInfo() *Info {
  161. info := &Info{
  162. ID: app.opts.Name,
  163. Name: app.opts.Name,
  164. Version: app.opts.Version,
  165. Status: StateHealthy,
  166. Address: app.opts.Address,
  167. Port: app.opts.Port,
  168. Metadata: app.opts.Metadata,
  169. }
  170. if info.Metadata == nil {
  171. info.Metadata = make(map[string]string)
  172. }
  173. info.Metadata["os"] = runtime.GOOS
  174. info.Metadata["numOfCPU"] = strconv.Itoa(runtime.NumCPU())
  175. info.Metadata["goVersion"] = runtime.Version()
  176. info.Metadata["shortName"] = app.opts.ShortName()
  177. info.Metadata["upTime"] = app.uptime.Format(time.DateTime)
  178. return info
  179. }
  180. func (app *application) preStart() (err error) {
  181. var (
  182. addr string
  183. )
  184. app.ctx, app.cancelFunc = context.WithCancelCause(app.opts.Context)
  185. if *cliFlag && !app.opts.DisableCommand {
  186. if err = app.gotoInteractive(); err != nil {
  187. fmt.Println(err)
  188. os.Exit(1)
  189. }
  190. os.Exit(0)
  191. }
  192. app.info = app.buildInfo()
  193. app.Log().Infof("server starting")
  194. env.Set(EnvAppName, app.opts.ShortName())
  195. env.Set(EnvAppVersion, app.opts.Version)
  196. addr = net.JoinHostPort(app.opts.Address, strconv.Itoa(app.opts.Port))
  197. app.Log().Infof("server listen on: %s", addr)
  198. app.gateway = entry.New(addr)
  199. if err = app.gateway.Start(app.ctx); err != nil {
  200. return
  201. }
  202. if !app.opts.DisableHttp {
  203. if err = app.httpServe(); err != nil {
  204. return
  205. }
  206. }
  207. if !app.opts.DisableCommand {
  208. if err = app.commandServe(); err != nil {
  209. return
  210. }
  211. }
  212. app.plugins.Range(func(key, value any) bool {
  213. if plugin, ok := value.(Plugin); ok {
  214. if err = plugin.BeforeStart(); err != nil {
  215. return false
  216. }
  217. }
  218. return true
  219. })
  220. if app.opts.server != nil {
  221. if err = app.opts.server.Start(app.ctx); err != nil {
  222. app.Log().Warnf("server start error: %s", err.Error())
  223. return
  224. }
  225. }
  226. if !app.opts.DisableStateApi {
  227. app.Handle("/-/run/state", func(ctx Context) (err error) {
  228. return ctx.Success(State{
  229. ID: app.opts.Name,
  230. Name: app.opts.Name,
  231. Version: app.opts.Version,
  232. Uptime: time.Now().Sub(app.uptime).String(),
  233. Gateway: app.gateway.State(),
  234. })
  235. })
  236. app.Handle("/-/healthy", func(ctx Context) (err error) {
  237. return ctx.Success(app.Healthy())
  238. })
  239. }
  240. app.plugins.Range(func(key, value any) bool {
  241. if plugin, ok := value.(Plugin); ok {
  242. if err = plugin.AfterStart(); err != nil {
  243. return false
  244. }
  245. }
  246. return true
  247. })
  248. app.Log().Infof("server started")
  249. return
  250. }
  251. func (app *application) preStop() (err error) {
  252. if !atomic.CompareAndSwapInt32(&app.exitFlag, 0, 1) {
  253. return
  254. }
  255. app.Log().Infof("server stopping")
  256. app.cancelFunc(ErrStopping)
  257. app.plugins.Range(func(key, value any) bool {
  258. if plugin, ok := value.(Plugin); ok {
  259. if err = plugin.BeforeStop(); err != nil {
  260. return false
  261. }
  262. }
  263. return true
  264. })
  265. if app.http != nil {
  266. if err = app.http.Shutdown(); err != nil {
  267. app.Log().Warnf("server http shutdown error: %s", err.Error())
  268. }
  269. }
  270. if app.command != nil {
  271. if err = app.command.Shutdown(); err != nil {
  272. app.Log().Warnf("server command shutdown error: %s", err.Error())
  273. }
  274. }
  275. if err = app.gateway.Stop(); err != nil {
  276. app.Log().Warnf("server gateway shutdown error: %s", err.Error())
  277. }
  278. app.plugins.Range(func(key, value any) bool {
  279. if plugin, ok := value.(Plugin); ok {
  280. if err = plugin.AfterStop(); err != nil {
  281. return false
  282. }
  283. }
  284. return true
  285. })
  286. app.waitGroup.Wait()
  287. app.Log().Infof("server stopped")
  288. return
  289. }
  290. func (app *application) Use(plugin Plugin) (err error) {
  291. var (
  292. ok bool
  293. )
  294. if _, ok = app.plugins.Load(plugin.Name()); ok {
  295. return fmt.Errorf("plugin %s already registered", plugin.Name())
  296. }
  297. if err = plugin.Mount(app.ctx); err != nil {
  298. return
  299. }
  300. app.plugins.Store(plugin.Name(), plugin)
  301. return
  302. }
  303. func (app *application) Run() (err error) {
  304. if err = app.preStart(); err != nil {
  305. return
  306. }
  307. ch := make(chan os.Signal, 1)
  308. if app.opts.Signals == nil {
  309. app.opts.Signals = []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL}
  310. }
  311. signal.Notify(ch, app.opts.Signals...)
  312. select {
  313. case <-ch:
  314. case <-app.ctx.Done():
  315. }
  316. return app.preStop()
  317. }
  318. func New(cbs ...Option) *application {
  319. opts := NewOptions()
  320. for _, cb := range cbs {
  321. cb(opts)
  322. }
  323. app := &application{
  324. opts: opts,
  325. uptime: time.Now(),
  326. }
  327. return app
  328. }