service.go 7.1 KB

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