service.go 14 KB

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