service.go 12 KB

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