service.go 9.8 KB

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