service.go 12 KB

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