service.go 8.2 KB

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