service.go 8.4 KB

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