snaxd.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. local skynet = require "skynet"
  2. local c = require "skynet.core"
  3. local snax_interface = require "snax.interface"
  4. local profile = require "skynet.profile"
  5. local snax = require "skynet.snax"
  6. local snax_name = tostring(...)
  7. local loaderpath = skynet.getenv"snax_loader"
  8. local loader = loaderpath and assert(dofile(loaderpath))
  9. local func, pattern = snax_interface(snax_name, _ENV, loader)
  10. local snax_path = pattern:sub(1,pattern:find("?", 1, true)-1) .. snax_name .. "/"
  11. package.path = snax_path .. "?.lua;" .. package.path
  12. SERVICE_NAME = snax_name
  13. SERVICE_PATH = snax_path
  14. local profile_table = {}
  15. local function update_stat(name, ti)
  16. local t = profile_table[name]
  17. if t == nil then
  18. t = { count = 0, time = 0 }
  19. profile_table[name] = t
  20. end
  21. t.count = t.count + 1
  22. t.time = t.time + ti
  23. end
  24. local traceback = debug.traceback
  25. local function return_f(f, ...)
  26. return skynet.ret(skynet.pack(f(...)))
  27. end
  28. local function timing( method, ... )
  29. local err, msg
  30. profile.start()
  31. if method[2] == "accept" then
  32. -- no return
  33. err,msg = xpcall(method[4], traceback, ...)
  34. else
  35. err,msg = xpcall(return_f, traceback, method[4], ...)
  36. end
  37. local ti = profile.stop()
  38. update_stat(method[3], ti)
  39. assert(err,msg)
  40. end
  41. skynet.start(function()
  42. local init = false
  43. local function dispatcher( session , source , id, ...)
  44. local method = func[id]
  45. if method[2] == "system" then
  46. local command = method[3]
  47. if command == "hotfix" then
  48. local hotfix = require "snax.hotfix"
  49. skynet.ret(skynet.pack(hotfix(func, ...)))
  50. elseif command == "profile" then
  51. skynet.ret(skynet.pack(profile_table))
  52. elseif command == "init" then
  53. assert(not init, "Already init")
  54. local initfunc = method[4] or function() end
  55. initfunc(...)
  56. skynet.ret()
  57. skynet.info_func(function()
  58. return profile_table
  59. end)
  60. init = true
  61. else
  62. assert(init, "Never init")
  63. assert(command == "exit")
  64. local exitfunc = method[4] or function() end
  65. exitfunc(...)
  66. skynet.ret()
  67. init = false
  68. skynet.exit()
  69. end
  70. else
  71. assert(init, "Init first")
  72. timing(method, ...)
  73. end
  74. end
  75. skynet.dispatch("snax", dispatcher)
  76. -- set lua dispatcher
  77. function snax.enablecluster()
  78. skynet.dispatch("lua", dispatcher)
  79. end
  80. end)