service.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package micro
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "git.nspix.com/golang/micro/stats/prometheusbackend"
  7. "github.com/prometheus/client_golang/prometheus/promhttp"
  8. "net"
  9. hp "net/http"
  10. "net/http/pprof"
  11. "os"
  12. "os/signal"
  13. "strings"
  14. "sync"
  15. "syscall"
  16. "time"
  17. "git.nspix.com/golang/micro/gateway"
  18. "git.nspix.com/golang/micro/gateway/http"
  19. "git.nspix.com/golang/micro/gateway/rpc"
  20. "git.nspix.com/golang/micro/log"
  21. "git.nspix.com/golang/micro/registry"
  22. "git.nspix.com/golang/micro/utils/docker"
  23. "git.nspix.com/golang/micro/utils/net/ip"
  24. "git.nspix.com/golang/micro/utils/unsafestr"
  25. )
  26. type Service struct {
  27. opts *Options
  28. ctx context.Context
  29. cancelFunc context.CancelFunc
  30. registry registry.Registry
  31. node *registry.ServiceNode
  32. listener net.Listener
  33. gateway *gateway.Gateway
  34. wg sync.WaitGroup
  35. httpSvr *http.Server
  36. rpcSvr *rpc.Server
  37. upTime time.Time
  38. client *Client
  39. environment string
  40. }
  41. func (svr *Service) wrapSync(f func()) {
  42. svr.wg.Add(1)
  43. go func() {
  44. f()
  45. svr.wg.Done()
  46. }()
  47. }
  48. func (svr *Service) eventLoop() {
  49. var (
  50. err error
  51. registryTicker *time.Ticker
  52. )
  53. registryTicker = time.NewTicker(time.Second * 20)
  54. defer func() {
  55. registryTicker.Stop()
  56. }()
  57. for {
  58. select {
  59. case <-registryTicker.C:
  60. if !svr.opts.DisableRegister {
  61. if err = svr.registry.Register(svr.node); err != nil {
  62. log.Warnf("registry service %s error: %s", svr.opts.Name, err.Error())
  63. }
  64. }
  65. case <-svr.ctx.Done():
  66. return
  67. }
  68. }
  69. }
  70. func (svr *Service) Handle(method string, cb HandleFunc, opts ...HandleOption) {
  71. opt := &HandleOptions{HttpMethod: "POST"}
  72. for _, f := range opts {
  73. f(opt)
  74. }
  75. //HTTP处理
  76. if svr.opts.EnableHttp && !opt.DisableHttp {
  77. if opt.HttpPath == "" {
  78. opt.HttpPath = strings.ReplaceAll(method, ".", "/")
  79. }
  80. if opt.HttpPath[0] != '/' {
  81. opt.HttpPath = "/" + opt.HttpPath
  82. }
  83. svr.httpSvr.Handle(opt.HttpMethod, opt.HttpPath, func(ctx *http.Context) (err error) {
  84. return cb(ctx)
  85. })
  86. }
  87. //启动RPC功能
  88. if svr.opts.EnableRPC && !opt.DisableRpc {
  89. svr.rpcSvr.Handle(method, func(ctx *rpc.Context) error {
  90. return cb(ctx)
  91. })
  92. }
  93. return
  94. }
  95. func (svr *Service) NewRequest(name, method string, body interface{}) (req *Request, err error) {
  96. return &Request{
  97. ServiceName: name,
  98. Method: method,
  99. Body: body,
  100. client: svr.client,
  101. }, nil
  102. }
  103. func (svr *Service) PeekService(name string) ([]*registry.ServiceNode, error) {
  104. return svr.registry.Get(name)
  105. }
  106. func (svr *Service) HttpServe() *http.Server {
  107. return svr.httpSvr
  108. }
  109. func (svr *Service) RPCServe() *rpc.Server {
  110. return svr.rpcSvr
  111. }
  112. func (svr *Service) Node() *registry.ServiceNode {
  113. return svr.node
  114. }
  115. func (svr *Service) Environment() string {
  116. return svr.environment
  117. }
  118. func (svr *Service) instance() *registry.ServiceNode {
  119. var (
  120. err error
  121. id string
  122. dockerID string
  123. tcpAddr *net.TCPAddr
  124. ipLocal string
  125. node *registry.ServiceNode
  126. )
  127. if id, err = docker.SelfContainerID(); err != nil {
  128. //生成唯一ID
  129. e5 := md5.New()
  130. e5.Write(unsafestr.StringToBytes(svr.opts.Name))
  131. e5.Write(unsafestr.StringToBytes(svr.opts.Version))
  132. id = hex.EncodeToString(e5.Sum(nil))
  133. } else {
  134. dockerID = id
  135. svr.environment = EnvironmentDocker
  136. }
  137. node = &registry.ServiceNode{
  138. ID: id,
  139. Name: svr.opts.Name,
  140. Version: svr.opts.Version,
  141. Metadata: map[string]string{},
  142. Addresses: make(map[string]registry.Addr),
  143. }
  144. if svr.opts.Address == "" {
  145. ipLocal = ip.InternalIP()
  146. } else {
  147. ipLocal = svr.opts.Address
  148. }
  149. node.Address = ipLocal
  150. if svr.listener != nil {
  151. if tcpAddr, err = net.ResolveTCPAddr("tcp", svr.listener.Addr().String()); err == nil {
  152. node.Port = tcpAddr.Port
  153. }
  154. } else {
  155. node.Port = svr.opts.Port
  156. }
  157. node.Metadata["docker-id"] = dockerID
  158. if svr.opts.EnableHttp {
  159. node.Metadata["enable-http"] = "true"
  160. }
  161. if svr.opts.EnableRPC {
  162. node.Metadata["enable-rpc"] = "true"
  163. }
  164. //服务注册时候处理
  165. if svr.opts.EnableStats {
  166. node.Metadata["prometheus"] = "enable"
  167. }
  168. return node
  169. }
  170. func (svr *Service) startHTTPServe() (err error) {
  171. l := gateway.NewListener(svr.listener.Addr())
  172. if err = svr.gateway.Attaches([][]byte{[]byte("GET"), []byte("POST"), []byte("PUT"), []byte("DELETE"), []byte("OPTIONS")}, l); err == nil {
  173. svr.wrapSync(func() {
  174. if err = svr.httpSvr.Serve(l); err != nil {
  175. log.Warnf("http serve error: %s", err.Error())
  176. }
  177. })
  178. svr.httpSvr.Handle("GET", "/healthy", func(ctx *http.Context) (err error) {
  179. return ctx.Success(map[string]interface{}{
  180. "id": svr.node.ID,
  181. "healthy": "healthy",
  182. "uptime": time.Now().Sub(svr.upTime).String(),
  183. })
  184. })
  185. if svr.opts.EnableStats {
  186. prometheusbackend.Init(svr.opts.shortName)
  187. svr.httpSvr.Handler("GET", "/metrics", promhttp.Handler())
  188. }
  189. if svr.opts.EnableHttpPProf {
  190. svr.httpSvr.Handler("GET", "/debug/pprof/", hp.HandlerFunc(pprof.Index))
  191. svr.httpSvr.Handler("GET", "/debug/pprof/goroutine", hp.HandlerFunc(pprof.Index))
  192. svr.httpSvr.Handler("GET", "/debug/pprof/heap", hp.HandlerFunc(pprof.Index))
  193. svr.httpSvr.Handler("GET", "/debug/pprof/mutex", hp.HandlerFunc(pprof.Index))
  194. svr.httpSvr.Handler("GET", "/debug/pprof/threadcreate", hp.HandlerFunc(pprof.Index))
  195. svr.httpSvr.Handler("GET", "/debug/pprof/cmdline", hp.HandlerFunc(pprof.Cmdline))
  196. svr.httpSvr.Handler("GET", "/debug/pprof/profile", hp.HandlerFunc(pprof.Profile))
  197. svr.httpSvr.Handler("GET", "/debug/pprof/symbol", hp.HandlerFunc(pprof.Symbol))
  198. svr.httpSvr.Handler("GET", "/debug/pprof/trace", hp.HandlerFunc(pprof.Trace))
  199. }
  200. log.Infof("attach http listener success")
  201. } else {
  202. log.Warnf("attach http listener failed cause by %s", err.Error())
  203. }
  204. return
  205. }
  206. func (svr *Service) startRPCServe() (err error) {
  207. l := gateway.NewListener(svr.listener.Addr())
  208. if err = svr.gateway.Attach([]byte("RPC"), l); err == nil {
  209. svr.wrapSync(func() {
  210. if err = svr.rpcSvr.Serve(l); err != nil {
  211. log.Warnf("rpc serve start error: %s", err.Error())
  212. }
  213. })
  214. log.Infof("attach rpc listener success")
  215. } else {
  216. log.Warnf("attach rpc listener failed cause by %s", err.Error())
  217. }
  218. return
  219. }
  220. func (svr *Service) prepare() (err error) {
  221. svr.ctx = WithContext(svr.ctx, svr)
  222. if svr.opts.EnableInternalListener {
  223. var tcpAddr *net.TCPAddr
  224. //绑定指定的端口
  225. if svr.opts.Port != 0 {
  226. tcpAddr = &net.TCPAddr{
  227. Port: svr.opts.Port,
  228. }
  229. }
  230. //默认指定为本机IP
  231. if svr.opts.Address == "" {
  232. svr.opts.Address = ip.InternalIP()
  233. }
  234. //绑定指定的IP
  235. if tcpAddr == nil {
  236. tcpAddr = &net.TCPAddr{
  237. IP: net.ParseIP(svr.opts.Address),
  238. }
  239. } else {
  240. tcpAddr.IP = net.ParseIP(svr.opts.Address)
  241. }
  242. if svr.listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
  243. return
  244. }
  245. log.Infof("server listen on: %s", svr.listener.Addr())
  246. svr.gateway = gateway.New(svr.listener, svr.opts.EnableStats)
  247. svr.wrapSync(func() {
  248. svr.gateway.Run(svr.ctx)
  249. })
  250. //开启HTTP服务
  251. if svr.opts.EnableHttp {
  252. err = svr.startHTTPServe()
  253. }
  254. //开启RCP服务
  255. if svr.opts.EnableRPC {
  256. err = svr.startRPCServe()
  257. }
  258. }
  259. svr.node = svr.instance()
  260. svr.wrapSync(func() {
  261. svr.eventLoop()
  262. })
  263. if !svr.opts.DisableRegister {
  264. _ = svr.registry.Register(svr.node)
  265. }
  266. return
  267. }
  268. func (svr *Service) destroy() (err error) {
  269. log.Infof("service stopping")
  270. svr.cancelFunc()
  271. if !svr.opts.DisableRegister {
  272. if err = svr.registry.Deregister(svr.node); err != nil {
  273. log.Warnf("deregister service %s error: %s", svr.opts.Name, err.Error())
  274. } else {
  275. log.Infof("deregister service %s successful", svr.opts.Name)
  276. }
  277. }
  278. if svr.listener != nil {
  279. if err = svr.listener.Close(); err != nil {
  280. log.Warnf(err.Error())
  281. }
  282. }
  283. if err = svr.client.Close(); err != nil {
  284. log.Warnf(err.Error())
  285. }
  286. log.Infof("service stopped")
  287. return
  288. }
  289. func (svr *Service) Run() (err error) {
  290. if svr.opts.EnableLogPrefix {
  291. log.Prefix(svr.opts.Name)
  292. }
  293. log.Infof("service starting")
  294. if err = svr.prepare(); err != nil {
  295. return
  296. }
  297. //start server
  298. if svr.opts.Server != nil {
  299. if err = svr.opts.Server.Start(svr.ctx); err != nil {
  300. return
  301. }
  302. }
  303. log.Infof("service started")
  304. //waiting
  305. ch := make(chan os.Signal, 1)
  306. signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
  307. select {
  308. case <-ch:
  309. case <-svr.ctx.Done():
  310. }
  311. //stop server
  312. if svr.opts.Server != nil {
  313. err = svr.opts.Server.Stop()
  314. }
  315. return svr.destroy()
  316. }
  317. func New(opts ...Option) *Service {
  318. o := NewOptions()
  319. for _, opt := range opts {
  320. opt(o)
  321. }
  322. svr := &Service{
  323. opts: o,
  324. upTime: time.Now(),
  325. httpSvr: http.New(),
  326. rpcSvr: rpc.NewServer(),
  327. registry: o.registry,
  328. client: NewClient(o.registry),
  329. environment: EnvironmentHost,
  330. }
  331. svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
  332. return svr
  333. }