062aea5280e99fffed8e267fb3f1b0ab522255fd
[certmaster.git] / certmaster / minion / modules / service.py
1 ## func
2 ##
3 ## Copyright 2007, Red Hat, Inc
4 ## Michael DeHaan <mdehaan@redhat.com>
5 ##
6 ## This software may be freely redistributed under the terms of the GNU
7 ## general public license.
8 ##
9 ## You should have received a copy of the GNU General Public License
10 ## along with this program; if not, write to the Free Software
11 ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
12 ##
13 ##
14
15 import codes
16 import func_module
17
18 import sub_process
19 import os
20
21 class Service(func_module.FuncModule):
22
23 version = "0.0.1"
24 api_version = "0.0.1"
25 description = "Allows for service control via func."
26
27 def __command(self, service_name, command):
28
29 filename = os.path.join("/etc/rc.d/init.d/",service_name)
30 if os.path.exists(filename):
31 return sub_process.call(["/sbin/service", service_name, command])
32 else:
33 raise codes.FuncException("Service not installed: %s" % service_name)
34
35 def start(self, service_name):
36 return self.__command(service_name, "start")
37
38 def stop(self, service_name):
39 return self.__command(service_name, "stop")
40
41 def restart(self, service_name):
42 return self.__command(service_name, "restart")
43
44 def reload(self, service_name):
45 return self.__command(service_name, "reload")
46
47 def status(self, service_name):
48 return self.__command(service_name, "status")
49
50 def inventory(self):
51 return {
52 "running" : self.get_running(),
53 "enabled" : self.get_enabled()
54 }
55
56 def get_enabled(self):
57 """
58 Get the list of services that are enabled at the various runlevels. Xinetd services
59 only provide whether or not they are running, not specific runlevel info.
60 """
61
62 chkconfig = sub_process.Popen(["/sbin/chkconfig", "--list"], stdout=sub_process.PIPE)
63 data = chkconfig.communicate()[0]
64 results = []
65 for line in data.split("\n"):
66 if line.find("0:") != -1:
67 # regular services
68 tokens = line.split()
69 results.append((tokens[0],tokens[1:]))
70 elif line.find(":") != -1 and not line.endswith(":"):
71 # xinetd.d based services
72 tokens = line.split()
73 tokens[0] = tokens[0].replace(":","")
74 results.append((tokens[0],tokens[1]))
75 return results
76
77 def get_running(self):
78 """
79 Get a list of which services are running, stopped, or disabled.
80 """
81 chkconfig = sub_process.Popen(["/sbin/service", "--status-all"], stdout=sub_process.PIPE)
82 data = chkconfig.communicate()[0]
83 results = []
84 for line in data.split("\n"):
85 if line.find(" is ") != -1:
86 tokens = line.split()
87 results.append((tokens[0], tokens[-1].replace("...","")))
88 return results