service.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package micro
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "net"
  7. hp "net/http"
  8. "net/http/pprof"
  9. "os"
  10. "os/signal"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. "git.nspix.com/golang/micro/gateway"
  16. "git.nspix.com/golang/micro/gateway/http"
  17. "git.nspix.com/golang/micro/gateway/rpc"
  18. "git.nspix.com/golang/micro/log"
  19. "git.nspix.com/golang/micro/registry"
  20. "git.nspix.com/golang/micro/stats/prometheusbackend"
  21. "git.nspix.com/golang/micro/utils/docker"
  22. "git.nspix.com/golang/micro/utils/net/ip"
  23. "git.nspix.com/golang/micro/utils/unsafestr"
  24. "github.com/prometheus/client_golang/prometheus/promhttp"
  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. return node
  165. }
  166. func (svr *Service) startHTTPServe() (err error) {
  167. l := gateway.NewListener(svr.listener.Addr())
  168. if err = svr.gateway.Attaches([][]byte{[]byte("GET"), []byte("POST"), []byte("PUT"), []byte("DELETE"), []byte("OPTIONS")}, l); err == nil {
  169. svr.wrapSync(func() {
  170. if err = svr.httpSvr.Serve(l); err != nil {
  171. log.Warnf("http serve error: %s", err.Error())
  172. }
  173. })
  174. svr.httpSvr.Handle("GET", "/healthy", func(ctx *http.Context) (err error) {
  175. return ctx.Success(map[string]interface{}{
  176. "id": svr.node.ID,
  177. "healthy": "healthy",
  178. "uptime": time.Now().Sub(svr.upTime).String(),
  179. })
  180. })
  181. if svr.opts.EnableHttpPProf {
  182. svr.httpSvr.Handler("GET", "/debug/pprof/", hp.HandlerFunc(pprof.Index))
  183. svr.httpSvr.Handler("GET", "/debug/pprof/goroutine", hp.HandlerFunc(pprof.Index))
  184. svr.httpSvr.Handler("GET", "/debug/pprof/heap", hp.HandlerFunc(pprof.Index))
  185. svr.httpSvr.Handler("GET", "/debug/pprof/mutex", hp.HandlerFunc(pprof.Index))
  186. svr.httpSvr.Handler("GET", "/debug/pprof/threadcreate", hp.HandlerFunc(pprof.Index))
  187. svr.httpSvr.Handler("GET", "/debug/pprof/cmdline", hp.HandlerFunc(pprof.Cmdline))
  188. svr.httpSvr.Handler("GET", "/debug/pprof/profile", hp.HandlerFunc(pprof.Profile))
  189. svr.httpSvr.Handler("GET", "/debug/pprof/symbol", hp.HandlerFunc(pprof.Symbol))
  190. svr.httpSvr.Handler("GET", "/debug/pprof/trace", hp.HandlerFunc(pprof.Trace))
  191. }
  192. if svr.opts.EnableStats {
  193. prometheusbackend.Init(svr.opts.shortName)
  194. svr.httpSvr.Handler("GET", "/metrics", promhttp.Handler())
  195. }
  196. log.Infof("attach http server success")
  197. } else {
  198. log.Warnf("attach http listener error: %s", err.Error())
  199. }
  200. return
  201. }
  202. func (svr *Service) startRPCServe() (err error) {
  203. l := gateway.NewListener(svr.listener.Addr())
  204. if err = svr.gateway.Attach([]byte("RPC"), l); err == nil {
  205. svr.wrapSync(func() {
  206. if err = svr.rpcSvr.Serve(l); err != nil {
  207. log.Warnf("rpc serve error: %s", err.Error())
  208. }
  209. })
  210. log.Infof("attach rpc server success")
  211. } else {
  212. log.Warnf("attach rpc listener error: %s", err.Error())
  213. }
  214. return
  215. }
  216. func (svr *Service) prepare() (err error) {
  217. log.Prefix(svr.opts.Name)
  218. svr.ctx = WithContext(svr.ctx, svr)
  219. if svr.opts.EnableInternalListener {
  220. var tcpAddr *net.TCPAddr
  221. //绑定指定的端口
  222. if svr.opts.Port != 0 {
  223. tcpAddr = &net.TCPAddr{
  224. Port: svr.opts.Port,
  225. }
  226. }
  227. //默认指定为本机IP
  228. if svr.opts.Address == "" {
  229. svr.opts.Address = ip.InternalIP()
  230. }
  231. //绑定指定的IP
  232. if tcpAddr == nil {
  233. tcpAddr = &net.TCPAddr{
  234. IP: net.ParseIP(svr.opts.Address),
  235. }
  236. } else {
  237. tcpAddr.IP = net.ParseIP(svr.opts.Address)
  238. }
  239. if svr.listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
  240. return
  241. }
  242. log.Infof("listen on: %s", svr.listener.Addr())
  243. svr.gateway = gateway.New(svr.listener)
  244. svr.wrapSync(func() {
  245. svr.gateway.Run(svr.ctx)
  246. })
  247. //start http serve
  248. if svr.opts.EnableHttp {
  249. err = svr.startHTTPServe()
  250. }
  251. //start rpc serve
  252. if svr.opts.EnableRPC {
  253. err = svr.startRPCServe()
  254. }
  255. }
  256. svr.node = svr.instance()
  257. svr.wrapSync(func() {
  258. svr.eventLoop()
  259. })
  260. if !svr.opts.DisableRegister {
  261. _ = svr.registry.Register(svr.node)
  262. }
  263. return
  264. }
  265. func (svr *Service) destroy() (err error) {
  266. log.Infof("service stopping")
  267. svr.cancelFunc()
  268. if !svr.opts.DisableRegister {
  269. if err = svr.registry.Deregister(svr.node); err != nil {
  270. log.Warnf("deregister service %s error: %s", svr.opts.Name, err.Error())
  271. } else {
  272. log.Infof("deregister service %s successful", svr.opts.Name)
  273. }
  274. }
  275. if svr.listener != nil {
  276. if err = svr.listener.Close(); err != nil {
  277. log.Warnf(err.Error())
  278. }
  279. }
  280. if err = svr.client.Close(); err != nil {
  281. log.Warnf(err.Error())
  282. }
  283. log.Infof("service stopped")
  284. return
  285. }
  286. func (svr *Service) Run() (err error) {
  287. log.Infof("service starting")
  288. if err = svr.prepare(); err != nil {
  289. return
  290. }
  291. //start server
  292. if svr.opts.Server != nil {
  293. if err = svr.opts.Server.Start(svr.ctx); err != nil {
  294. return
  295. }
  296. }
  297. log.Infof("service ready")
  298. //waiting
  299. ch := make(chan os.Signal, 1)
  300. signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
  301. select {
  302. case <-ch:
  303. case <-svr.ctx.Done():
  304. }
  305. //stop server
  306. if svr.opts.Server != nil {
  307. err = svr.opts.Server.Stop()
  308. }
  309. return svr.destroy()
  310. }
  311. func New(opts ...Option) *Service {
  312. o := NewOptions()
  313. for _, opt := range opts {
  314. opt(o)
  315. }
  316. svr := &Service{
  317. opts: o,
  318. upTime: time.Now(),
  319. httpSvr: http.New(),
  320. rpcSvr: rpc.NewServer(),
  321. registry: o.registry,
  322. client: NewClient(o.registry),
  323. environment: EnvironmentHost,
  324. }
  325. svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
  326. return svr
  327. }