service.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. svr.httpSvr = http.New(svr.ctx)
  281. l := gateway.NewListener(svr.listener.Addr())
  282. if err = svr.gateway.Attaches([][]byte{[]byte("GET"), []byte("POST"), []byte("PUT"), []byte("DELETE"), []byte("OPTIONS")}, l); err == nil {
  283. svr.async(func() {
  284. if err = svr.httpSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  285. log.Warnf("http serve error: %s", err.Error())
  286. }
  287. log.Infof("http server stopped")
  288. })
  289. svr.httpSvr.Handle("GET", "/healthy", func(ctx *http.Context) (err error) {
  290. return ctx.Success(map[string]interface{}{
  291. "id": svr.node.ID,
  292. "healthy": "healthy",
  293. "uptime": time.Now().Sub(svr.upTime).String(),
  294. })
  295. })
  296. if svr.opts.EnableStats {
  297. prometheusbackend.Init(svr.opts.shortName)
  298. svr.httpSvr.Handler("GET", "/metrics", promhttp.Handler())
  299. }
  300. if svr.opts.EnableHttpPProf {
  301. svr.httpSvr.Handler("GET", "/debug/pprof/", hp.HandlerFunc(pprof.Index))
  302. svr.httpSvr.Handler("GET", "/debug/pprof/goroutine", hp.HandlerFunc(pprof.Index))
  303. svr.httpSvr.Handler("GET", "/debug/pprof/heap", hp.HandlerFunc(pprof.Index))
  304. svr.httpSvr.Handler("GET", "/debug/pprof/mutex", hp.HandlerFunc(pprof.Index))
  305. svr.httpSvr.Handler("GET", "/debug/pprof/threadcreate", hp.HandlerFunc(pprof.Index))
  306. svr.httpSvr.Handler("GET", "/debug/pprof/cmdline", hp.HandlerFunc(pprof.Cmdline))
  307. svr.httpSvr.Handler("GET", "/debug/pprof/profile", hp.HandlerFunc(pprof.Profile))
  308. svr.httpSvr.Handler("GET", "/debug/pprof/symbol", hp.HandlerFunc(pprof.Symbol))
  309. svr.httpSvr.Handler("GET", "/debug/pprof/trace", hp.HandlerFunc(pprof.Trace))
  310. }
  311. log.Infof("attach http listener success")
  312. } else {
  313. log.Warnf("attach http listener failed cause by %s", err.Error())
  314. }
  315. return
  316. }
  317. func (svr *Service) startRPCServe() (err error) {
  318. svr.rpcSvr = rpc.New(svr.ctx)
  319. l := gateway.NewListener(svr.listener.Addr())
  320. if err = svr.gateway.Attach([]byte("RPC"), l); err == nil {
  321. svr.async(func() {
  322. if err = svr.rpcSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  323. log.Warnf("rpc serve start error: %s", err.Error())
  324. }
  325. log.Infof("rpc server stopped")
  326. })
  327. log.Infof("attach rpc listener success")
  328. } else {
  329. log.Warnf("attach rpc listener failed cause by %s", err.Error())
  330. }
  331. return
  332. }
  333. func (svr *Service) startCliServe() (err error) {
  334. svr.cliSvr = cli.New(svr.ctx)
  335. l := gateway.NewListener(svr.listener.Addr())
  336. if err = svr.gateway.Attach([]byte("CLI"), l); err == nil {
  337. svr.async(func() {
  338. if err = svr.cliSvr.Serve(l); err != nil && atomic.LoadInt32(&svr.exitFlag) == 0 {
  339. log.Warnf("cli serve start error: %s", err.Error())
  340. }
  341. log.Infof("cli server stopped")
  342. })
  343. log.Infof("attach cli listener success")
  344. } else {
  345. log.Warnf("attach cli listener failed cause by %s", err.Error())
  346. }
  347. return
  348. }
  349. func (svr *Service) prepare() (err error) {
  350. svr.ctx = WithContext(svr.ctx, svr)
  351. if svr.opts.EnableInternalListener {
  352. var tcpAddr *net.TCPAddr
  353. //绑定指定的端口
  354. if svr.opts.Port != 0 {
  355. tcpAddr = &net.TCPAddr{
  356. Port: svr.opts.Port,
  357. }
  358. }
  359. //默认指定为本机IP
  360. if svr.opts.Address == "" {
  361. svr.opts.Address = ip.InternalIP()
  362. }
  363. //绑定指定的IP
  364. if tcpAddr == nil {
  365. tcpAddr = &net.TCPAddr{
  366. IP: net.ParseIP(svr.opts.Address),
  367. }
  368. } else {
  369. tcpAddr.IP = net.ParseIP(svr.opts.Address)
  370. }
  371. _ = os.Setenv("MICRO_SERVICE_NAME", svr.opts.ShortName())
  372. _ = os.Setenv("MICRO_SERVICE_VERSION", svr.opts.Version)
  373. if svr.listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
  374. return
  375. }
  376. log.Infof("server listen on: %s", svr.listener.Addr())
  377. svr.gateway = gateway.New(svr.listener, svr.opts.EnableStats)
  378. svr.async(func() {
  379. svr.gateway.Run(svr.ctx)
  380. })
  381. //开启HTTP服务
  382. if svr.opts.EnableHttp {
  383. err = svr.startHTTPServe()
  384. }
  385. //开启RCP服务
  386. if svr.opts.EnableRPC {
  387. err = svr.startRPCServe()
  388. }
  389. //开启cli服务
  390. if svr.opts.EnableCli {
  391. err = svr.startCliServe()
  392. }
  393. }
  394. svr.node = svr.instance()
  395. svr.async(func() {
  396. svr.worker()
  397. })
  398. if !svr.opts.DisableRegister {
  399. if err = svr.registry.Register(svr.ctx, svr.node); err != nil {
  400. log.Warnf("service %s registered failed cause by %s", svr.opts.ShortName(), err.Error())
  401. svr.triesRegister++
  402. err = nil
  403. }
  404. }
  405. if svr.opts.EnableReport {
  406. rn := rand.Int31n(48) + 60
  407. svr.DeferTick(time.Hour*time.Duration(rn), func(ctx context.Context) {
  408. _ = defaultReporter.Do(svr.opts.Name)
  409. })
  410. }
  411. return
  412. }
  413. //destroy stop and destroy service
  414. func (svr *Service) destroy() (err error) {
  415. if !atomic.CompareAndSwapInt32(&svr.exitFlag, 0, 1) {
  416. return
  417. }
  418. log.Infof("service stopping")
  419. if !svr.opts.DisableRegister {
  420. if err = svr.registry.Deregister(svr.ctx, svr.node); err != nil {
  421. log.Warnf("service %s deregister error: %s", svr.opts.Name, err.Error())
  422. } else {
  423. log.Infof("service %s deregister successful", svr.opts.Name)
  424. }
  425. }
  426. svr.cancelFunc()
  427. if svr.listener != nil {
  428. if err = svr.listener.Close(); err != nil {
  429. log.Warnf(err.Error())
  430. } else {
  431. log.Infof("listener closed")
  432. }
  433. }
  434. if err = svr.client.Close(); err != nil {
  435. log.Warnf(err.Error())
  436. }
  437. svr.tickTimer.Stop()
  438. for svr.tickTree.Len() > 0 {
  439. node := svr.tickTree.DeleteMin()
  440. if node == nil {
  441. break
  442. }
  443. tick := node.(*tickPtr)
  444. if tick.options.MustBeExecute {
  445. tick.callback(tick.options.Context)
  446. }
  447. }
  448. svr.wg.Wait()
  449. log.Infof("service stopped")
  450. return
  451. }
  452. //Reload reload server
  453. func (svr *Service) Reload() (err error) {
  454. if svr.opts.Server == nil {
  455. return
  456. }
  457. log.Infof("reloading server %s", svr.opts.Name)
  458. if err = svr.opts.Server.Stop(); err != nil {
  459. return
  460. }
  461. return svr.opts.Server.Start(svr.ctx)
  462. }
  463. //Run setup service
  464. func (svr *Service) Run() (err error) {
  465. if svr.opts.EnableLogPrefix {
  466. log.Prefix(svr.opts.Name)
  467. }
  468. log.Infof("service starting")
  469. if err = svr.prepare(); err != nil {
  470. return
  471. }
  472. //set global broker component
  473. broker.SetGlobal(broker.NewInPrcBus(svr.ctx))
  474. //start server
  475. if svr.opts.Server != nil {
  476. if err = svr.opts.Server.Start(svr.ctx); err != nil {
  477. return
  478. }
  479. }
  480. log.Infof("service started")
  481. //waiting
  482. ch := make(chan os.Signal, 1)
  483. signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
  484. select {
  485. case <-ch:
  486. case <-svr.ctx.Done():
  487. }
  488. //stop server
  489. if svr.opts.Server != nil {
  490. err = svr.opts.Server.Stop()
  491. }
  492. return svr.destroy()
  493. }
  494. func New(opts ...Option) *Service {
  495. o := NewOptions()
  496. for _, opt := range opts {
  497. opt(o)
  498. }
  499. svr := &Service{
  500. opts: o,
  501. upTime: time.Now(),
  502. registry: o.registry,
  503. tickTimer: time.NewTimer(math.MaxInt64),
  504. tickTree: btree.New(64),
  505. client: NewClient(o.registry),
  506. environment: EnvironmentHost,
  507. }
  508. svr.ctx, svr.cancelFunc = context.WithCancel(o.Context)
  509. return svr
  510. }