service.go 9.7 KB

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