summaryrefslogtreecommitdiffstats
path: root/lib/service_model.lua
blob: c619d617b625e103b144ea3d21e77e6eb9adeff1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
require("fs")

function create_service_model(cfglist, loglist, servlist, notepath)

	local me = {}

	local function get_any_pid(pname)
		for e in lfs.dir("/proc") do
			if e == string.match(e, "^%d*$") then
				for line in io.lines("/proc/" .. e .. "/status") do
					tag, val = string.match(line, "^([^:]*):%s*(%S*)$");
					if tag == "Name" then
						if val == pname then return e end
						break
					end
				end
			end
		end
	end

	local function get_cfg_path(name)
		if not cfglist or not cfglist[name] then
			return
		end
		return cfglist[name].path
	end

	local function get_log_path(name)
		if not loglist or not loglist[name] then
			return
		end
		return loglist[name].path
	end

	--[[ Public Functions go here ]]--

	function me.status(name)
		if not servlist or not servlist[name] then
			return "unknown service"
		end
		local cmdname = servlist[name].cmdname
		if get_any_pid(cmdname) == nil then
			return "seems to be stopped"
		else
			return "seems to be running"
		end
	end

	function me.initd(name, action)
		if not servlist or not servlist[name] then
			return "unknown service"
		end
		local p = io.popen("/etc/init.d/"
			.. servlist[name].initdname .. " " .. action, "r")
		local ret = p:read("*a")
		p:close()
		return ret
	end

	function me.get_note()
		if not notepath or not fs.is_file(notepath) then return "" end
		return fs.read_file(notepath)
	end

	function me.set_note(value)
		if notepath == nil then return end
		fs.write_file(notepath, value)
	end

	function me.get_cfg_names()
		return cfglist    
	end

	function me.get_log_names()
		return loglist    
	end

	function me.get_service_names()
		return servlist
	end

	function me.get_cfg(name)
		local path = get_cfg_path(name)
		if not path or not fs.is_file(path) then
			return ""
		end
		return fs.read_file(path)
	end

	function me.set_cfg(name, value)
		local path = get_cfg_path(name)
		if path then
			fs.write_file(path, value)
		end
	end

-- 	local function wrap_single(x)
-- 		return function(state, prev)
-- 			if not prev then
-- 				return x
-- 			end
-- 		end
-- 	end

	function me.get_log_producer(name)
		local path = get_log_path(name)
		if not path or not fs.is_file(path) then
			return "cannot access " .. path
		end
		return io.lines(path)
	end

	return me

end