service.go 14 KB

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