service.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. package micro
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "git.nspix.com/golang/micro/helper/random"
  7. "git.nspix.com/golang/micro/helper/utils"
  8. "io/ioutil"
  9. "math"
  10. "math/rand"
  11. "net"
  12. hp "net/http"
  13. "net/http/pprof"
  14. "os"
  15. "os/signal"
  16. "path"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "syscall"
  21. "time"
  22. "git.nspix.com/golang/micro/broker"
  23. "git.nspix.com/golang/micro/gateway/cli"
  24. "git.nspix.com/golang/micro/helper/machineid"
  25. "git.nspix.com/golang/micro/stats/prometheusbackend"
  26. "github.com/google/btree"
  27. "github.com/prometheus/client_golang/prometheus/promhttp"
  28. "git.nspix.com/golang/micro/gateway"
  29. "git.nspix.com/golang/micro/gateway/http"
  30. "git.nspix.com/golang/micro/gateway/rpc"
  31. "git.nspix.com/golang/micro/helper/docker"
  32. "git.nspix.com/golang/micro/helper/net/ip"
  33. "git.nspix.com/golang/micro/helper/unsafestr"
  34. "git.nspix.com/golang/micro/log"
  35. "git.nspix.com/golang/micro/registry"
  36. )
  37. var (
  38. tickSequence int64
  39. )
  40. type Service struct {
  41. opts *Options
  42. ctx context.Context
  43. cancelFunc context.CancelFunc
  44. registry registry.Registry
  45. node *registry.ServiceNode
  46. listener net.Listener
  47. gateway *gateway.Gateway
  48. wg sync.WaitGroup
  49. httpSvr *http.Server
  50. rpcSvr *rpc.Server
  51. cliSvr *cli.Server
  52. upTime time.Time
  53. client *Client
  54. triesRegister int
  55. tickTimer *time.Timer
  56. tickTree *btree.BTree
  57. environment string
  58. exitFlag int32
  59. }
  60. func (svr *Service) async(f func()) {
  61. svr.wg.Add(1)
  62. go func() {
  63. f()
  64. svr.wg.Done()
  65. }()
  66. }
  67. func (svr *Service) worker() {
  68. var (
  69. err error
  70. ticker *time.Ticker
  71. )
  72. ticker = time.NewTicker(time.Second * 20)
  73. defer func() {
  74. ticker.Stop()
  75. }()
  76. for {
  77. select {
  78. case <-svr.tickTimer.C:
  79. node := svr.tickTree.Min()
  80. if node == nil {
  81. svr.tickTimer.Reset(math.MaxInt64)
  82. break
  83. }
  84. tick := node.(*tickPtr)
  85. if tick.next.Before(time.Now()) {
  86. svr.tickTree.Delete(node)
  87. if !tick.options.Canceled {
  88. if atomic.CompareAndSwapInt32(&tick.running, 0, 1) {
  89. svr.async(func() {
  90. tick.callback(tick.options.Context)
  91. })
  92. }
  93. }
  94. next := svr.tickTree.Min()
  95. if next == nil {
  96. svr.tickTimer.Reset(math.MaxInt64)
  97. } else {
  98. svr.tickTimer.Reset(next.(*tickPtr).next.Sub(time.Now()))
  99. }
  100. } else {
  101. svr.tickTimer.Reset(tick.next.Sub(time.Now()))
  102. }
  103. case <-ticker.C:
  104. if !svr.opts.DisableRegister {
  105. if err = svr.registry.Register(svr.ctx, svr.node); err != nil {
  106. svr.triesRegister++
  107. if svr.triesRegister%18 == 0 {
  108. log.Warnf("service registered %s failed %d times, last error: %s", svr.opts.ShortName(), svr.triesRegister, err.Error())
  109. }
  110. } else {
  111. svr.triesRegister = 0
  112. }
  113. }
  114. case <-svr.ctx.Done():
  115. return
  116. }
  117. }
  118. }
  119. //DeferTick 定时执行一个任务
  120. func (svr *Service) DeferTick(duration time.Duration, callback HandleTickerFunc, opts ...TickOption) int64 {
  121. tick := &tickPtr{
  122. sequence: atomic.AddInt64(&tickSequence, 1),
  123. next: time.Now().Add(duration),
  124. options: &TickOptions{},
  125. callback: callback,
  126. }
  127. for _, optFunc := range opts {
  128. optFunc(tick.options)
  129. }
  130. if tick.options.Context == nil {
  131. tick.options.Context = svr.ctx
  132. }
  133. svr.tickTimer.Reset(0)
  134. svr.tickTree.ReplaceOrInsert(tick)
  135. return tick.sequence
  136. }
  137. //Handle 处理函数
  138. func (svr *Service) Handle(method string, cb HandleFunc, opts ...HandleOption) {
  139. //disable cli default
  140. opt := &HandleOptions{HttpMethod: "POST", DisableCli: true}
  141. for _, f := range opts {
  142. f(opt)
  143. }
  144. //HTTP处理
  145. if svr.opts.EnableHttp && !opt.DisableHttp {
  146. if opt.HttpPath == "" {
  147. opt.HttpPath = strings.ReplaceAll(method, ".", "/")
  148. }
  149. if opt.HttpPath[0] != '/' {
  150. opt.HttpPath = "/" + opt.HttpPath
  151. }
  152. svr.httpSvr.Handle(opt.HttpMethod, opt.HttpPath, func(ctx *http.Context) (err error) {
  153. return cb(ctx)
  154. })
  155. }
  156. //启动RPC功能
  157. if svr.opts.EnableRPC && !opt.DisableRpc {
  158. svr.rpcSvr.Handle(method, func(ctx *rpc.Context) error {
  159. return cb(ctx)
  160. })
  161. }
  162. //启用CLI模式
  163. if svr.opts.EnableCli && !opt.DisableCli {
  164. svr.cliSvr.Handle(method, func(ctx *cli.Context) (err error) {
  165. return cb(ctx)
  166. })
  167. }
  168. return
  169. }
  170. //NewRequest 创建一个请求
  171. func (svr *Service) NewRequest(name, method string, body interface{}) (req *Request, err error) {
  172. return &Request{
  173. ServiceName: name,
  174. Method: method,
  175. Body: body,
  176. client: svr.client,
  177. }, nil
  178. }
  179. //PeekService 选取一个可靠的服务
  180. func (svr *Service) PeekService(name string) ([]*registry.ServiceNode, error) {
  181. return svr.registry.Get(svr.ctx, name)
  182. }
  183. func (svr *Service) HttpServe() *http.Server {
  184. return svr.httpSvr
  185. }
  186. func (svr *Service) CliServe() *cli.Server {
  187. return svr.cliSvr
  188. }
  189. func (svr *Service) RPCServe() *rpc.Server {
  190. return svr.rpcSvr
  191. }
  192. func (svr *Service) Node() *registry.ServiceNode {
  193. return svr.node
  194. }
  195. func (svr *Service) Environment() string {
  196. return svr.environment
  197. }
  198. func (svr *Service) getMachineID() (machineID string) {
  199. var (
  200. buf []byte
  201. err error
  202. )
  203. cacheFile := path.Join(utils.CacheDir(), utils.HiddenFilePrefix()+svr.opts.ShortName())
  204. if utils.FileExists(cacheFile) {
  205. if buf, err = ioutil.ReadFile(cacheFile); err == nil {
  206. machineID = string(buf)
  207. return
  208. }
  209. }
  210. if machineID == "" {
  211. if machineID, err = machineid.Code(); err != nil {
  212. machineID = random.String(64)
  213. }
  214. }
  215. _ = os.MkdirAll(path.Dir(cacheFile), 0644)
  216. _ = ioutil.WriteFile(cacheFile, []byte(machineID), 0755)
  217. return machineID
  218. }
  219. func (svr *Service) instance() *registry.ServiceNode {
  220. var (
  221. err error
  222. id string
  223. dockerID string
  224. tcpAddr *net.TCPAddr
  225. ipLocal string
  226. node *registry.ServiceNode
  227. )
  228. if id, err = docker.SelfContainerID(); err != nil {
  229. //生成唯一ID
  230. e5 := md5.New()
  231. e5.Write(unsafestr.StringToBytes(svr.opts.Name))
  232. e5.Write(unsafestr.StringToBytes(svr.opts.Version))
  233. id = hex.EncodeToString(e5.Sum(nil))
  234. } else {
  235. dockerID = id
  236. svr.environment = EnvironmentDocker
  237. }
  238. node = &registry.ServiceNode{
  239. ID: id,
  240. Name: svr.opts.Name,
  241. Version: svr.opts.Version,
  242. Metadata: map[string]string{},
  243. Addresses: make(map[string]registry.Addr),
  244. }
  245. if svr.opts.Address == "" {
  246. ipLocal = ip.InternalIP()
  247. } else {
  248. ipLocal = svr.opts.Address
  249. }
  250. node.Address = ipLocal
  251. if svr.listener != nil {
  252. if tcpAddr, err = net.ResolveTCPAddr("tcp", svr.listener.Addr().String()); err == nil {
  253. node.Port = tcpAddr.Port
  254. }
  255. } else {
  256. node.Port = svr.opts.Port
  257. }
  258. //上报机器码
  259. node.Metadata["machine-code"] = svr.getMachineID()
  260. node.Metadata["docker-id"] = dockerID
  261. if svr.opts.EnableHttp {
  262. node.Metadata["enable-http"] = "true"
  263. }
  264. if svr.opts.EnableRPC {
  265. node.Metadata["enable-rpc"] = "true"
  266. }
  267. //服务注册时候处理
  268. if svr.opts.EnableStats {
  269. node.Metadata["prometheus"] = "enable"
  270. }
  271. //添加服务注册参数
  272. if svr.opts.RegistryArguments != nil {
  273. for k, v := range svr.opts.RegistryArguments {
  274. node.Metadata["registry-"+k] = v
  275. }
  276. }
  277. return node
  278. }
  279. func (svr *Service) startHTTPServe() (err error) {
  280. l := gateway.NewListener(svr.listener.Addr())
  281. if err = svr.gateway.Attaches([][]byte{[]byte("GET"), []byte("POST"), []byte("PUT"), []byte("DELETE"), []byte("OPTIONS")}, l); err == nil {
  282. svr.async(func() {
  283. if err = svr.httpSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  284. log.Warnf("http serve error: %s", err.Error())
  285. }
  286. log.Infof("http server stopped")
  287. })
  288. svr.httpSvr.Handle("GET", "/healthy", func(ctx *http.Context) (err error) {
  289. return ctx.Success(map[string]interface{}{
  290. "id": svr.node.ID,
  291. "healthy": "healthy",
  292. "uptime": time.Now().Sub(svr.upTime).String(),
  293. })
  294. })
  295. if svr.opts.EnableStats {
  296. prometheusbackend.Init(svr.opts.shortName)
  297. svr.httpSvr.Handler("GET", "/metrics", promhttp.Handler())
  298. }
  299. if svr.opts.EnableHttpPProf {
  300. svr.httpSvr.Handler("GET", "/debug/pprof/", hp.HandlerFunc(pprof.Index))
  301. svr.httpSvr.Handler("GET", "/debug/pprof/goroutine", hp.HandlerFunc(pprof.Index))
  302. svr.httpSvr.Handler("GET", "/debug/pprof/heap", hp.HandlerFunc(pprof.Index))
  303. svr.httpSvr.Handler("GET", "/debug/pprof/mutex", hp.HandlerFunc(pprof.Index))
  304. svr.httpSvr.Handler("GET", "/debug/pprof/threadcreate", hp.HandlerFunc(pprof.Index))
  305. svr.httpSvr.Handler("GET", "/debug/pprof/cmdline", hp.HandlerFunc(pprof.Cmdline))
  306. svr.httpSvr.Handler("GET", "/debug/pprof/profile", hp.HandlerFunc(pprof.Profile))
  307. svr.httpSvr.Handler("GET", "/debug/pprof/symbol", hp.HandlerFunc(pprof.Symbol))
  308. svr.httpSvr.Handler("GET", "/debug/pprof/trace", hp.HandlerFunc(pprof.Trace))
  309. }
  310. log.Infof("attach http listener success")
  311. } else {
  312. log.Warnf("attach http listener failed cause by %s", err.Error())
  313. }
  314. return
  315. }
  316. func (svr *Service) startRPCServe() (err error) {
  317. l := gateway.NewListener(svr.listener.Addr())
  318. if err = svr.gateway.Attach([]byte("RPC"), l); err == nil {
  319. svr.async(func() {
  320. if err = svr.rpcSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  321. log.Warnf("rpc serve start error: %s", err.Error())
  322. }
  323. log.Infof("rpc server stopped")
  324. })
  325. log.Infof("attach rpc listener success")
  326. } else {
  327. log.Warnf("attach rpc listener failed cause by %s", err.Error())
  328. }
  329. return
  330. }
  331. func (svr *Service) startCliServe() (err error) {
  332. l := gateway.NewListener(svr.listener.Addr())
  333. if err = svr.gateway.Attach([]byte("CLI"), l); err == nil {
  334. svr.async(func() {
  335. if err = svr.cliSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  336. log.Warnf("cli serve start error: %s", err.Error())
  337. }
  338. log.Infof("cli server stopped")
  339. })
  340. log.Infof("attach cli listener success")
  341. } else {
  342. log.Warnf("attach cli listener failed cause by %s", err.Error())
  343. }
  344. return
  345. }
  346. func (svr *Service) prepare() (err error) {
  347. svr.ctx = WithContext(svr.ctx, svr)
  348. if svr.opts.EnableInternalListener {
  349. var tcpAddr *net.TCPAddr
  350. //绑定指定的端口
  351. if svr.opts.Port != 0 {
  352. tcpAddr = &net.TCPAddr{
  353. Port: svr.opts.Port,
  354. }
  355. }
  356. //默认指定为本机IP
  357. if svr.opts.Address == "" {
  358. svr.opts.Address = ip.InternalIP()
  359. }
  360. //绑定指定的IP
  361. if tcpAddr == nil {
  362. tcpAddr = &net.TCPAddr{
  363. IP: net.ParseIP(svr.opts.Address),
  364. }
  365. } else {
  366. tcpAddr.IP = net.ParseIP(svr.opts.Address)
  367. }
  368. _ = os.Setenv("MICRO_SERVICE_NAME", svr.opts.ShortName())
  369. _ = os.Setenv("MICRO_SERVICE_VERSION", svr.opts.Version)
  370. if svr.listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
  371. return
  372. }
  373. log.Infof("server listen on: %s", svr.listener.Addr())
  374. svr.gateway = gateway.New(svr.listener, svr.opts.EnableStats)
  375. svr.async(func() {
  376. svr.gateway.Run(svr.ctx)
  377. })
  378. //开启HTTP服务
  379. if svr.opts.EnableHttp {
  380. err = svr.startHTTPServe()
  381. }
  382. //开启RCP服务
  383. if svr.opts.EnableRPC {
  384. err = svr.startRPCServe()
  385. }
  386. //开启cli服务
  387. if svr.opts.EnableCli {
  388. err = svr.startCliServe()
  389. }
  390. }
  391. svr.node = svr.instance()
  392. svr.async(func() {
  393. svr.worker()
  394. })
  395. if !svr.opts.DisableRegister {
  396. if err = svr.registry.Register(svr.ctx, svr.node); err != nil {
  397. log.Warnf("service %s registered failed cause by %s", svr.opts.ShortName(), err.Error())
  398. svr.triesRegister++
  399. err = nil
  400. }
  401. }
  402. if svr.opts.EnableReport {
  403. rn := rand.Int31n(48) + 60
  404. svr.DeferTick(time.Hour*time.Duration(rn), func(ctx context.Context) {
  405. _ = defaultReporter.Do(svr.opts.Name)
  406. })
  407. }
  408. return
  409. }
  410. //destroy stop and destroy service
  411. func (svr *Service) destroy() (err error) {
  412. if !atomic.CompareAndSwapInt32(&svr.exitFlag, 0, 1) {
  413. return
  414. }
  415. log.Infof("service stopping")
  416. if !svr.opts.DisableRegister {
  417. if err = svr.registry.Deregister(svr.ctx, svr.node); err != nil {
  418. log.Warnf("service %s deregister error: %s", svr.opts.Name, err.Error())
  419. } else {
  420. log.Infof("service %s deregister successful", svr.opts.Name)
  421. }
  422. }
  423. svr.cancelFunc()
  424. if svr.listener != nil {
  425. if err = svr.listener.Close(); err != nil {
  426. log.Warnf(err.Error())
  427. } else {
  428. log.Infof("listener closed")
  429. }
  430. }
  431. if err = svr.client.Close(); err != nil {
  432. log.Warnf(err.Error())
  433. }
  434. svr.tickTimer.Stop()
  435. for svr.tickTree.Len() > 0 {
  436. node := svr.tickTree.DeleteMin()
  437. if node == nil {
  438. break
  439. }
  440. tick := node.(*tickPtr)
  441. if tick.options.MustBeExecute {
  442. tick.callback(tick.options.Context)
  443. }
  444. }
  445. svr.wg.Wait()
  446. log.Infof("service stopped")
  447. return
  448. }
  449. func (svr *Service) Run() (err error) {
  450. if svr.opts.EnableLogPrefix {
  451. log.Prefix(svr.opts.Name)
  452. }
  453. log.Infof("service starting")
  454. if err = svr.prepare(); err != nil {
  455. return
  456. }
  457. //set global broker component
  458. broker.SetGlobal(broker.NewInPrcBus(svr.ctx))
  459. //start server
  460. if svr.opts.Server != nil {
  461. if err = svr.opts.Server.Start(svr.ctx); err != nil {
  462. return
  463. }
  464. }
  465. log.Infof("service started")
  466. //waiting
  467. ch := make(chan os.Signal, 1)
  468. signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
  469. select {
  470. case <-ch:
  471. case <-svr.ctx.Done():
  472. }
  473. //stop server
  474. if svr.opts.Server != nil {
  475. err = svr.opts.Server.Stop()
  476. }
  477. return svr.destroy()
  478. }
  479. func New(opts ...Option) *Service {
  480. o := NewOptions()
  481. for _, opt := range opts {
  482. opt(o)
  483. }
  484. svr := &Service{
  485. opts: o,
  486. upTime: time.Now(),
  487. httpSvr: http.New(),
  488. cliSvr: cli.New(),
  489. rpcSvr: rpc.NewServer(),
  490. registry: o.registry,
  491. tickTimer: time.NewTimer(math.MaxInt64),
  492. tickTree: btree.New(64),
  493. client: NewClient(o.registry),
  494. environment: EnvironmentHost,
  495. }
  496. svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
  497. return svr
  498. }