service.go 10 KB

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