service.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. }
  115. })
  116. select {
  117. case err = <-errChan:
  118. case <-timer.C:
  119. }
  120. return
  121. }
  122. func (app *application) commandServe() (err error) {
  123. var (
  124. l net.Listener
  125. )
  126. app.command = cli.New(app.ctx)
  127. if l, err = app.gateway.Apply(
  128. cli.Feature,
  129. ); err != nil {
  130. return
  131. }
  132. timer := time.NewTimer(time.Millisecond * 200)
  133. defer timer.Stop()
  134. errChan := make(chan error, 1)
  135. app.waitGroup.Go(func() {
  136. select {
  137. case errChan <- app.command.Serve(l):
  138. }
  139. })
  140. select {
  141. case err = <-errChan:
  142. case <-timer.C:
  143. }
  144. return
  145. }
  146. func (app *application) gotoInteractive() (err error) {
  147. var (
  148. client *cli.Client
  149. )
  150. client = cli.NewClient(
  151. app.ctx,
  152. net.JoinHostPort(app.opts.Address, strconv.Itoa(app.opts.Port)),
  153. )
  154. return client.Shell()
  155. }
  156. func (app *application) buildInfo() *Info {
  157. info := &Info{
  158. ID: app.opts.Name,
  159. Name: app.opts.Name,
  160. Version: app.opts.Version,
  161. Status: StateHealthy,
  162. Address: app.opts.Address,
  163. Port: app.opts.Port,
  164. Metadata: app.opts.Metadata,
  165. }
  166. if info.Metadata == nil {
  167. info.Metadata = make(map[string]string)
  168. }
  169. info.Metadata["os"] = runtime.GOOS
  170. info.Metadata["numOfCPU"] = strconv.Itoa(runtime.NumCPU())
  171. info.Metadata["goVersion"] = runtime.Version()
  172. info.Metadata["shortName"] = app.opts.ShortName()
  173. info.Metadata["upTime"] = app.uptime.Format(time.DateTime)
  174. return info
  175. }
  176. func (app *application) preStart() (err error) {
  177. var (
  178. addr string
  179. )
  180. app.ctx, app.cancelFunc = context.WithCancelCause(app.opts.Context)
  181. if *cliFlag && !app.opts.DisableCommand {
  182. if err = app.gotoInteractive(); err != nil {
  183. fmt.Println(err)
  184. os.Exit(1)
  185. }
  186. os.Exit(0)
  187. }
  188. app.info = app.buildInfo()
  189. app.Log().Infof("server starting")
  190. env.Set(EnvAppName, app.opts.ShortName())
  191. env.Set(EnvAppVersion, app.opts.Version)
  192. addr = net.JoinHostPort(app.opts.Address, strconv.Itoa(app.opts.Port))
  193. app.Log().Infof("server listen on: %s", addr)
  194. app.gateway = entry.New(addr)
  195. if err = app.gateway.Start(app.ctx); err != nil {
  196. return
  197. }
  198. if !app.opts.DisableHttp {
  199. if err = app.httpServe(); err != nil {
  200. return
  201. }
  202. }
  203. if !app.opts.DisableCommand {
  204. if err = app.commandServe(); err != nil {
  205. return
  206. }
  207. }
  208. app.plugins.Range(func(key, value any) bool {
  209. if plugin, ok := value.(Plugin); ok {
  210. if err = plugin.BeforeStart(); err != nil {
  211. return false
  212. }
  213. }
  214. return true
  215. })
  216. if app.opts.server != nil {
  217. if err = app.opts.server.Start(app.ctx); err != nil {
  218. app.Log().Warnf("server start error: %s", err.Error())
  219. return
  220. }
  221. }
  222. if !app.opts.DisableStateApi {
  223. app.Handle("/-/run/state", func(ctx Context) (err error) {
  224. return ctx.Success(State{
  225. ID: app.opts.Name,
  226. Name: app.opts.Name,
  227. Version: app.opts.Version,
  228. Uptime: time.Now().Sub(app.uptime).String(),
  229. Gateway: app.gateway.State(),
  230. })
  231. })
  232. app.Handle("/-/healthy", func(ctx Context) (err error) {
  233. return ctx.Success(app.Healthy())
  234. })
  235. }
  236. app.plugins.Range(func(key, value any) bool {
  237. if plugin, ok := value.(Plugin); ok {
  238. if err = plugin.AfterStart(); err != nil {
  239. return false
  240. }
  241. }
  242. return true
  243. })
  244. app.Log().Infof("server started")
  245. return
  246. }
  247. func (app *application) preStop() (err error) {
  248. if !atomic.CompareAndSwapInt32(&app.exitFlag, 0, 1) {
  249. return
  250. }
  251. app.Log().Infof("server stopping")
  252. app.cancelFunc(ErrStopping)
  253. app.plugins.Range(func(key, value any) bool {
  254. if plugin, ok := value.(Plugin); ok {
  255. if err = plugin.BeforeStop(); err != nil {
  256. return false
  257. }
  258. }
  259. return true
  260. })
  261. if app.http != nil {
  262. if err = app.http.Shutdown(); err != nil {
  263. app.Log().Warnf("server http shutdown error: %s", err.Error())
  264. }
  265. }
  266. if app.command != nil {
  267. if err = app.command.Shutdown(); err != nil {
  268. app.Log().Warnf("server command shutdown error: %s", err.Error())
  269. }
  270. }
  271. if err = app.gateway.Stop(); err != nil {
  272. app.Log().Warnf("server gateway shutdown error: %s", err.Error())
  273. }
  274. app.plugins.Range(func(key, value any) bool {
  275. if plugin, ok := value.(Plugin); ok {
  276. if err = plugin.AfterStop(); err != nil {
  277. return false
  278. }
  279. }
  280. return true
  281. })
  282. app.waitGroup.Wait()
  283. app.Log().Infof("server stopped")
  284. return
  285. }
  286. func (app *application) Use(plugin Plugin) (err error) {
  287. var (
  288. ok bool
  289. )
  290. if _, ok = app.plugins.Load(plugin.Name()); ok {
  291. return fmt.Errorf("plugin %s already registered", plugin.Name())
  292. }
  293. if err = plugin.Mount(app.ctx); err != nil {
  294. return
  295. }
  296. app.plugins.Store(plugin.Name(), plugin)
  297. return
  298. }
  299. func (app *application) Run() (err error) {
  300. if err = app.preStart(); err != nil {
  301. return
  302. }
  303. ch := make(chan os.Signal, 1)
  304. if app.opts.Signals == nil {
  305. app.opts.Signals = []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL}
  306. }
  307. signal.Notify(ch, app.opts.Signals...)
  308. select {
  309. case <-ch:
  310. case <-app.ctx.Done():
  311. }
  312. return app.preStop()
  313. }
  314. func New(cbs ...Option) *application {
  315. opts := NewOptions()
  316. for _, cb := range cbs {
  317. cb(opts)
  318. }
  319. app := &application{
  320. opts: opts,
  321. uptime: time.Now(),
  322. }
  323. return app
  324. }