service.go 9.4 KB

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