service.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package micro
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "math"
  7. "math/rand"
  8. "net"
  9. hp "net/http"
  10. "net/http/pprof"
  11. "os"
  12. "os/signal"
  13. "strings"
  14. "sync"
  15. "sync/atomic"
  16. "syscall"
  17. "time"
  18. "git.nspix.com/golang/micro/broker"
  19. "git.nspix.com/golang/micro/gateway/cli"
  20. "git.nspix.com/golang/micro/helper/machineid"
  21. "git.nspix.com/golang/micro/stats/prometheusbackend"
  22. "github.com/google/btree"
  23. "github.com/prometheus/client_golang/prometheus/promhttp"
  24. "git.nspix.com/golang/micro/gateway"
  25. "git.nspix.com/golang/micro/gateway/http"
  26. "git.nspix.com/golang/micro/gateway/rpc"
  27. "git.nspix.com/golang/micro/helper/docker"
  28. "git.nspix.com/golang/micro/helper/net/ip"
  29. "git.nspix.com/golang/micro/helper/unsafestr"
  30. "git.nspix.com/golang/micro/log"
  31. "git.nspix.com/golang/micro/registry"
  32. )
  33. var (
  34. tickSequence int64
  35. )
  36. type Service struct {
  37. opts *Options
  38. ctx context.Context
  39. cancelFunc context.CancelFunc
  40. registry registry.Registry
  41. node *registry.ServiceNode
  42. listener net.Listener
  43. gateway *gateway.Gateway
  44. wg sync.WaitGroup
  45. httpSvr *http.Server
  46. rpcSvr *rpc.Server
  47. cliSvr *cli.Server
  48. upTime time.Time
  49. client *Client
  50. tickTimer *time.Timer
  51. tickTree *btree.BTree
  52. environment string
  53. exitFlag int32
  54. }
  55. func (svr *Service) async(f func()) {
  56. svr.wg.Add(1)
  57. go func() {
  58. f()
  59. svr.wg.Done()
  60. }()
  61. }
  62. func (svr *Service) worker() {
  63. var (
  64. err error
  65. ticker *time.Ticker
  66. )
  67. ticker = time.NewTicker(time.Second * 20)
  68. defer func() {
  69. ticker.Stop()
  70. }()
  71. for {
  72. select {
  73. case <-svr.tickTimer.C:
  74. node := svr.tickTree.Min()
  75. if node == nil {
  76. svr.tickTimer.Reset(math.MaxInt64)
  77. break
  78. }
  79. tick := node.(*tickPtr)
  80. if tick.next.Before(time.Now()) {
  81. svr.tickTree.Delete(node)
  82. if !tick.options.Canceled {
  83. if atomic.CompareAndSwapInt32(&tick.running, 0, 1) {
  84. svr.async(func() {
  85. tick.callback(tick.options.Context)
  86. })
  87. }
  88. }
  89. next := svr.tickTree.Min()
  90. if next == nil {
  91. svr.tickTimer.Reset(math.MaxInt64)
  92. } else {
  93. svr.tickTimer.Reset(next.(*tickPtr).next.Sub(time.Now()))
  94. }
  95. } else {
  96. svr.tickTimer.Reset(tick.next.Sub(time.Now()))
  97. }
  98. case <-ticker.C:
  99. if !svr.opts.DisableRegister {
  100. if err = svr.registry.Register(svr.node); err != nil {
  101. log.Warnf("registry service %s error: %s", svr.opts.Name, err.Error())
  102. }
  103. }
  104. case <-svr.ctx.Done():
  105. return
  106. }
  107. }
  108. }
  109. //DeferTick 定时执行一个任务
  110. func (svr *Service) DeferTick(duration time.Duration, callback HandleTickerFunc, opts ...TickOption) int64 {
  111. tick := &tickPtr{
  112. sequence: atomic.AddInt64(&tickSequence, 1),
  113. next: time.Now().Add(duration),
  114. options: &TickOptions{},
  115. callback: callback,
  116. }
  117. for _, optFunc := range opts {
  118. optFunc(tick.options)
  119. }
  120. if tick.options.Context == nil {
  121. tick.options.Context = svr.ctx
  122. }
  123. svr.tickTimer.Reset(0)
  124. svr.tickTree.ReplaceOrInsert(tick)
  125. return tick.sequence
  126. }
  127. //Handle 处理函数
  128. func (svr *Service) Handle(method string, cb HandleFunc, opts ...HandleOption) {
  129. //disable cli default
  130. opt := &HandleOptions{HttpMethod: "POST", DisableCli: true}
  131. for _, f := range opts {
  132. f(opt)
  133. }
  134. //HTTP处理
  135. if svr.opts.EnableHttp && !opt.DisableHttp {
  136. if opt.HttpPath == "" {
  137. opt.HttpPath = strings.ReplaceAll(method, ".", "/")
  138. }
  139. if opt.HttpPath[0] != '/' {
  140. opt.HttpPath = "/" + opt.HttpPath
  141. }
  142. svr.httpSvr.Handle(opt.HttpMethod, opt.HttpPath, func(ctx *http.Context) (err error) {
  143. return cb(ctx)
  144. })
  145. }
  146. //启动RPC功能
  147. if svr.opts.EnableRPC && !opt.DisableRpc {
  148. svr.rpcSvr.Handle(method, func(ctx *rpc.Context) error {
  149. return cb(ctx)
  150. })
  151. }
  152. //启用CLI模式
  153. if svr.opts.EnableCli && !opt.DisableCli {
  154. svr.cliSvr.Handle(method, func(ctx *cli.Context) (err error) {
  155. return cb(ctx)
  156. })
  157. }
  158. return
  159. }
  160. //NewRequest 创建一个请求
  161. func (svr *Service) NewRequest(name, method string, body interface{}) (req *Request, err error) {
  162. return &Request{
  163. ServiceName: name,
  164. Method: method,
  165. Body: body,
  166. client: svr.client,
  167. }, nil
  168. }
  169. func (svr *Service) PeekService(name string) ([]*registry.ServiceNode, error) {
  170. return svr.registry.Get(name)
  171. }
  172. func (svr *Service) HttpServe() *http.Server {
  173. return svr.httpSvr
  174. }
  175. func (svr *Service) CliServe() *cli.Server {
  176. return svr.cliSvr
  177. }
  178. func (svr *Service) RPCServe() *rpc.Server {
  179. return svr.rpcSvr
  180. }
  181. func (svr *Service) Node() *registry.ServiceNode {
  182. return svr.node
  183. }
  184. func (svr *Service) Environment() string {
  185. return svr.environment
  186. }
  187. func (svr *Service) instance() *registry.ServiceNode {
  188. var (
  189. err error
  190. id string
  191. dockerID string
  192. tcpAddr *net.TCPAddr
  193. ipLocal string
  194. machineCode string
  195. node *registry.ServiceNode
  196. )
  197. if id, err = docker.SelfContainerID(); err != nil {
  198. //生成唯一ID
  199. e5 := md5.New()
  200. e5.Write(unsafestr.StringToBytes(svr.opts.Name))
  201. e5.Write(unsafestr.StringToBytes(svr.opts.Version))
  202. id = hex.EncodeToString(e5.Sum(nil))
  203. } else {
  204. dockerID = id
  205. svr.environment = EnvironmentDocker
  206. }
  207. node = &registry.ServiceNode{
  208. ID: id,
  209. Name: svr.opts.Name,
  210. Version: svr.opts.Version,
  211. Metadata: map[string]string{},
  212. Addresses: make(map[string]registry.Addr),
  213. }
  214. if svr.opts.Address == "" {
  215. ipLocal = ip.InternalIP()
  216. } else {
  217. ipLocal = svr.opts.Address
  218. }
  219. node.Address = ipLocal
  220. if svr.listener != nil {
  221. if tcpAddr, err = net.ResolveTCPAddr("tcp", svr.listener.Addr().String()); err == nil {
  222. node.Port = tcpAddr.Port
  223. }
  224. } else {
  225. node.Port = svr.opts.Port
  226. }
  227. //上报机器码
  228. if machineCode, err = machineid.Code(); err == nil {
  229. node.Metadata["machine-code"] = machineCode
  230. }
  231. node.Metadata["docker-id"] = dockerID
  232. if svr.opts.EnableHttp {
  233. node.Metadata["enable-http"] = "true"
  234. }
  235. if svr.opts.EnableRPC {
  236. node.Metadata["enable-rpc"] = "true"
  237. }
  238. //服务注册时候处理
  239. if svr.opts.EnableStats {
  240. node.Metadata["prometheus"] = "enable"
  241. }
  242. return node
  243. }
  244. func (svr *Service) startHTTPServe() (err error) {
  245. l := gateway.NewListener(svr.listener.Addr())
  246. if err = svr.gateway.Attaches([][]byte{[]byte("GET"), []byte("POST"), []byte("PUT"), []byte("DELETE"), []byte("OPTIONS")}, l); err == nil {
  247. svr.async(func() {
  248. if err = svr.httpSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  249. log.Warnf("http serve error: %s", err.Error())
  250. }
  251. log.Infof("http server stopped")
  252. })
  253. svr.httpSvr.Handle("GET", "/healthy", func(ctx *http.Context) (err error) {
  254. return ctx.Success(map[string]interface{}{
  255. "id": svr.node.ID,
  256. "healthy": "healthy",
  257. "uptime": time.Now().Sub(svr.upTime).String(),
  258. })
  259. })
  260. if svr.opts.EnableStats {
  261. prometheusbackend.Init(svr.opts.shortName)
  262. svr.httpSvr.Handler("GET", "/metrics", promhttp.Handler())
  263. }
  264. if svr.opts.EnableHttpPProf {
  265. svr.httpSvr.Handler("GET", "/debug/pprof/", hp.HandlerFunc(pprof.Index))
  266. svr.httpSvr.Handler("GET", "/debug/pprof/goroutine", hp.HandlerFunc(pprof.Index))
  267. svr.httpSvr.Handler("GET", "/debug/pprof/heap", hp.HandlerFunc(pprof.Index))
  268. svr.httpSvr.Handler("GET", "/debug/pprof/mutex", hp.HandlerFunc(pprof.Index))
  269. svr.httpSvr.Handler("GET", "/debug/pprof/threadcreate", hp.HandlerFunc(pprof.Index))
  270. svr.httpSvr.Handler("GET", "/debug/pprof/cmdline", hp.HandlerFunc(pprof.Cmdline))
  271. svr.httpSvr.Handler("GET", "/debug/pprof/profile", hp.HandlerFunc(pprof.Profile))
  272. svr.httpSvr.Handler("GET", "/debug/pprof/symbol", hp.HandlerFunc(pprof.Symbol))
  273. svr.httpSvr.Handler("GET", "/debug/pprof/trace", hp.HandlerFunc(pprof.Trace))
  274. }
  275. log.Infof("attach http listener success")
  276. } else {
  277. log.Warnf("attach http listener failed cause by %s", err.Error())
  278. }
  279. return
  280. }
  281. func (svr *Service) startRPCServe() (err error) {
  282. l := gateway.NewListener(svr.listener.Addr())
  283. if err = svr.gateway.Attach([]byte("RPC"), l); err == nil {
  284. svr.async(func() {
  285. if err = svr.rpcSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  286. log.Warnf("rpc serve start error: %s", err.Error())
  287. }
  288. log.Infof("rpc server stopped")
  289. })
  290. log.Infof("attach rpc listener success")
  291. } else {
  292. log.Warnf("attach rpc listener failed cause by %s", err.Error())
  293. }
  294. return
  295. }
  296. func (svr *Service) startCliServe() (err error) {
  297. l := gateway.NewListener(svr.listener.Addr())
  298. if err = svr.gateway.Attach([]byte("CLI"), l); err == nil {
  299. svr.async(func() {
  300. if err = svr.cliSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  301. log.Warnf("cli serve start error: %s", err.Error())
  302. }
  303. log.Infof("cli server stopped")
  304. })
  305. log.Infof("attach cli listener success")
  306. } else {
  307. log.Warnf("attach cli listener failed cause by %s", err.Error())
  308. }
  309. return
  310. }
  311. func (svr *Service) prepare() (err error) {
  312. svr.ctx = WithContext(svr.ctx, svr)
  313. if svr.opts.EnableInternalListener {
  314. var tcpAddr *net.TCPAddr
  315. //绑定指定的端口
  316. if svr.opts.Port != 0 {
  317. tcpAddr = &net.TCPAddr{
  318. Port: svr.opts.Port,
  319. }
  320. }
  321. //默认指定为本机IP
  322. if svr.opts.Address == "" {
  323. svr.opts.Address = ip.InternalIP()
  324. }
  325. //绑定指定的IP
  326. if tcpAddr == nil {
  327. tcpAddr = &net.TCPAddr{
  328. IP: net.ParseIP(svr.opts.Address),
  329. }
  330. } else {
  331. tcpAddr.IP = net.ParseIP(svr.opts.Address)
  332. }
  333. _ = os.Setenv("MICRO_SERVICE_NAME", svr.opts.ShortName())
  334. _ = os.Setenv("MICRO_SERVICE_VERSION", svr.opts.Version)
  335. if svr.listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
  336. return
  337. }
  338. log.Infof("server listen on: %s", svr.listener.Addr())
  339. svr.gateway = gateway.New(svr.listener, svr.opts.EnableStats)
  340. svr.async(func() {
  341. svr.gateway.Run(svr.ctx)
  342. })
  343. //开启HTTP服务
  344. if svr.opts.EnableHttp {
  345. err = svr.startHTTPServe()
  346. }
  347. //开启RCP服务
  348. if svr.opts.EnableRPC {
  349. err = svr.startRPCServe()
  350. }
  351. //开启cli服务
  352. if svr.opts.EnableCli {
  353. err = svr.startCliServe()
  354. }
  355. }
  356. svr.node = svr.instance()
  357. svr.async(func() {
  358. svr.worker()
  359. })
  360. if !svr.opts.DisableRegister {
  361. _ = svr.registry.Register(svr.node)
  362. }
  363. if svr.opts.EnableReport {
  364. rn := rand.Int31n(48) + 60
  365. svr.DeferTick(time.Hour*time.Duration(rn), func(ctx context.Context) {
  366. _ = defaultReporter.Do(svr.opts.Name)
  367. })
  368. }
  369. return
  370. }
  371. func (svr *Service) destroy() (err error) {
  372. if !atomic.CompareAndSwapInt32(&svr.exitFlag, 0, 1) {
  373. return
  374. }
  375. log.Infof("service stopping")
  376. svr.cancelFunc()
  377. if !svr.opts.DisableRegister {
  378. if err = svr.registry.Deregister(svr.node); err != nil {
  379. log.Warnf("deregister service %s error: %s", svr.opts.Name, err.Error())
  380. } else {
  381. log.Infof("deregister service %s successful", svr.opts.Name)
  382. }
  383. }
  384. if svr.listener != nil {
  385. if err = svr.listener.Close(); err != nil {
  386. log.Warnf(err.Error())
  387. } else {
  388. log.Infof("listener closed")
  389. }
  390. }
  391. if err = svr.client.Close(); err != nil {
  392. log.Warnf(err.Error())
  393. }
  394. svr.tickTimer.Stop()
  395. for svr.tickTree.Len() > 0 {
  396. node := svr.tickTree.DeleteMin()
  397. if node == nil {
  398. break
  399. }
  400. tick := node.(*tickPtr)
  401. if tick.options.MustBeExecute {
  402. tick.callback(tick.options.Context)
  403. }
  404. }
  405. svr.wg.Wait()
  406. log.Infof("service stopped")
  407. return
  408. }
  409. func (svr *Service) Run() (err error) {
  410. if svr.opts.EnableLogPrefix {
  411. log.Prefix(svr.opts.Name)
  412. }
  413. log.Infof("service starting")
  414. if err = svr.prepare(); err != nil {
  415. return
  416. }
  417. //set global broker component
  418. broker.SetGlobal(broker.NewInPrcBus(svr.ctx))
  419. //start server
  420. if svr.opts.Server != nil {
  421. if err = svr.opts.Server.Start(svr.ctx); err != nil {
  422. return
  423. }
  424. }
  425. log.Infof("service started")
  426. //waiting
  427. ch := make(chan os.Signal, 1)
  428. signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
  429. select {
  430. case <-ch:
  431. case <-svr.ctx.Done():
  432. }
  433. //stop server
  434. if svr.opts.Server != nil {
  435. err = svr.opts.Server.Stop()
  436. }
  437. return svr.destroy()
  438. }
  439. func New(opts ...Option) *Service {
  440. o := NewOptions()
  441. for _, opt := range opts {
  442. opt(o)
  443. }
  444. svr := &Service{
  445. opts: o,
  446. upTime: time.Now(),
  447. httpSvr: http.New(),
  448. cliSvr: cli.New(),
  449. rpcSvr: rpc.NewServer(),
  450. registry: o.registry,
  451. tickTimer: time.NewTimer(math.MaxInt64),
  452. tickTree: btree.New(64),
  453. client: NewClient(o.registry),
  454. environment: EnvironmentHost,
  455. }
  456. svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
  457. return svr
  458. }