Operating system for OpenComputers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.3KB

  1. local serial = require "serialization"
  2. local rc = {}
  3. rc.paths = "/boot/service\n/pkg/service"
  4. rc.pids = {}
  5. local service = {}
  6. local cfg = {}
  7. cfg.enabled = {"getty","minitel","fsmanager"}
  8. local function loadConfig()
  9. local f = io.open("/boot/cfg/rc.cfg","rb")
  10. if not f then return false end
  11. cfg = serial.unserialize(f:read("*a")) or {}
  12. f:close()
  13. cfg.enabled = cfg.enabled or {}
  14. return true
  15. end
  16. local function saveConfig()
  17. local f = io.open("/boot/cfg/rc.cfg","wb")
  18. if not f then return false end
  19. f:write(serial.serialize(cfg))
  20. f:close()
  21. return true
  22. end
  23. function rc.load(name,force) -- string boolean -- table -- Attempts to load service *name*, and if *force* is true, replaces the current instance.
  24. if not service[name] or force then
  25. for d in rc.paths:gmatch("[^\n]+") do
  26. if fs.exists(d.."/"..name..".lua") then
  27. service[name] = runfile(d.."/"..name..".lua")
  28. end
  29. end
  30. end
  31. if service[name] then
  32. return service[name]
  33. end
  34. return false, "unable to load service "..name
  35. end
  36. function rc.stop(name,...) -- string -- boolean string -- Stops service *name*, supplying *...* to the stop function. Returns false and a reason if this fails.
  37. if not service[name] then return false, "service not found" end
  38. if service[name].stop then
  39. service[name].stop(...)
  40. coroutine.yield()
  41. end
  42. if rc.pids[name] then
  43. os.kill(rc.pids[name])
  44. end
  45. rc.pids[name] = nil
  46. end
  47. function rc.start(name,...) -- string -- boolean string -- Stops service *name*, supplying *...* to the stop function. Returns false and a reason if this fails.
  48. rc.load(name)
  49. if not service[name] then return false, "service not found" end
  50. local rv = {service[name].start(...)}
  51. if type(rv[1]) == "number" then
  52. rc.pids[name] = rv[1]
  53. end
  54. end
  55. function rc.restart(name) -- string -- -- Restarts service *name* using rc.stop and rc.start.
  56. rc.stop(name)
  57. rc.start(name)
  58. end
  59. function rc.enable(name) -- string -- -- Enables service *name* being started on startup.
  60. for k,v in pairs(cfg.enabled) do
  61. if v == name then return false end
  62. end
  63. cfg.enabled[#cfg.enabled+1] = name
  64. saveConfig()
  65. end
  66. function rc.disable(name) -- string -- -- Disables service *name* being started on startup.
  67. local disabled = false
  68. for k,v in pairs(cfg.enabled) do
  69. if v == name then table.remove(cfg.enabled,k) disabled = true break end
  70. end
  71. saveConfig()
  72. return disabled
  73. end
  74. loadConfig()
  75. _G.service = service
  76. rc.cfg = cfg
  77. return rc