service.go 8.5 KB

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