service.go 15 KB

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