service.go 14 KB

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