OSDN Git Service

Remove pdb
[karesansui/karesansui.git] / karesansui / lib / parser / iptables.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Karesansui Core.
5 #
6 # Copyright (C) 2009-2010 HDE, Inc.
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13
14 import os
15 import re
16 import sys
17 import time
18
19 from karesansui.lib.dict_op import DictOp
20 from karesansui.lib.parser.base.line_parser import lineParser as Parser
21 from karesansui.lib.utils import array_replace
22 from karesansui.lib.utils import preprint_r
23
24
25 """
26 Define Variables for This Parser
27 """
28 PARSER_COMMAND_IPTABLES="/sbin/iptables"
29 PARSER_COMMAND_IPTABLES_SAVE="/sbin/iptables-save"
30 PARSER_COMMAND_IPTABLES_RESTORE="/sbin/iptables-restore"
31 PARSER_IPTABLES_CONF="/etc/sysconfig/iptables"
32 PARSER_IPTABLES_INITRD="/etc/init.d/iptables"
33 PARSER_IPTABLES_INITRD_ACTIONS="start|stop|restart|condrestart|status|panic|save"
34
35 PARSER_IPTABLES_CONF_HEADER="(# Generated by .* on ).*"
36 PARSER_IPTABLES_CONF_FOOTER="(# Completed on ).*"
37
38
39 class iptablesParser:
40
41     _module = "iptables"
42
43     def __init__(self):
44         self.dop = DictOp()
45         self.dop.addconf(self._module,{})
46
47         self.parser = Parser()
48         self.base_parser_name = self.parser.__class__.__name__
49         pass
50
51     def source_file(self):
52         retval = [PARSER_IPTABLES_CONF]
53
54         return retval
55
56     def read_conf(self,extra_args=None):
57         retval = {}
58
59         self.parser.set_source_file([PARSER_IPTABLES_CONF])
60         self.dop.addconf(self._module,{})
61
62         conf_arr = self.parser.read_conf()
63         try:
64             lines = conf_arr[PARSER_IPTABLES_CONF]['value']
65             lint = self.do_lint("\n".join(lines))
66             self.dop.set(self._module,["config"],lines)
67             self.dop.set(self._module,["lint"]  ,lint)
68         except:
69             pass
70
71         cmdfile = "cmd:%s" % PARSER_COMMAND_IPTABLES_SAVE
72         self.parser.set_source_file([cmdfile])
73         conf_arr = self.parser.read_conf()
74         try:
75             lines = conf_arr[cmdfile]['value']
76             self.dop.set(self._module,["status"],lines)
77         except:
78             pass
79
80         self.parser.set_source_file([PARSER_IPTABLES_CONF])
81
82         self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
83         #self.dop.preprint_r(self._module)
84         return self.dop.getconf(self._module)
85
86     def write_conf(self,conf_arr={},extra_args=None,dryrun=False):
87         retval = True
88
89         now = time.strftime("%c",time.localtime())
90         try:
91             self.dop.addconf("parser",{})
92
93             lines = conf_arr["config"]["value"]
94             lines = array_replace(lines,PARSER_IPTABLES_CONF_HEADER,"# Generated by karesansui on %s" % (now,))
95             lines = array_replace(lines,PARSER_IPTABLES_CONF_FOOTER,"# Completed on %s" % (now,))
96             self.dop.set("parser",[PARSER_IPTABLES_CONF],lines)
97             #self.dop.preprint_r("parser")
98             arr = self.dop.getconf("parser")
99             self.parser.write_conf(arr,dryrun=dryrun)
100             self.do_condrestart()
101         except:
102             pass
103
104         return retval
105
106     def do_start(self):
107         return self._do("start")
108
109     def do_stop(self):
110         return self._do("stop")
111
112     def do_restart(self):
113         return self._do("restart")
114
115     def do_condrestart(self):
116         return self._do("condrestart")
117
118     def do_status(self):
119         return self._do("status")
120
121     def is_running(self):
122         return self.do_status()[0]
123
124     def _do(self,action=None):
125         from karesansui.lib.utils import execute_command
126
127         retval = False
128         res    = []
129         if re.match("^(%s)$" % PARSER_IPTABLES_INITRD_ACTIONS, action):
130             command_args = [PARSER_IPTABLES_INITRD,action]
131             (ret,res) = execute_command(command_args)
132             if ret == 0:
133                 retval = True
134         return [retval,res]
135
136     # reverseがFalseなら設定ファイルをもとに、システムに反映(condrestart)
137     # reverseがTrueならシステムの状態をもとに、設定ファイルに反映
138     def do_sync(self,reverse=False):
139         try:
140             self.dop.addconf("parser",self.read_conf())
141             if reverse is False:
142                 self.do_restart()
143             else:
144                 lines = self.dop.get("parser",["status"])
145                 self.dop.set("parser",["config"],lines)
146                 conf = self.dop.getconf("parser")
147                 self.write_conf(conf)
148             return True
149         except:
150             return False
151
152     def do_lint(self,string,lint=True):
153         import signal
154         import subprocess
155         retval = []
156
157         if lint is True:
158             (old_ret,old_res) = self.do_status()
159             if old_ret is True:
160                 old_lines = []
161                 cmdfile = "cmd:%s" % PARSER_COMMAND_IPTABLES_SAVE
162                 self.parser.set_source_file([cmdfile])
163                 conf_arr = self.parser.read_conf()
164                 try:
165                     old_lines = conf_arr[cmdfile]['value']
166                 except:
167                     pass
168                 self.parser.set_source_file([PARSER_IPTABLES_CONF])
169
170
171         signal.alarm(10)
172         if lint is True:
173             command_args = [PARSER_COMMAND_IPTABLES_RESTORE,"--test"]
174         else:
175             command_args = [PARSER_COMMAND_IPTABLES_RESTORE]
176         proc = subprocess.Popen(command_args,
177                    bufsize=1,
178                    shell=True,
179                    stdin=subprocess.PIPE,
180                    stdout=subprocess.PIPE,
181                    stderr=subprocess.PIPE)
182
183         #proc.stdin.write(string)
184         (stdout,stderr) = proc.communicate(string)
185         ret = proc.wait()
186         signal.alarm(0)
187
188         exclude_strings = [
189            "Try `iptables-restore -h' or 'iptables-restore --help' for more information.",
190            "iptables-restore v[0-9\.]+: iptables-restore:",
191            "iptables-restore v[0-9\.]+: ",
192         ]
193
194         new_stderr = []
195         for _aline in re.split("[\r\n]+",stderr):
196             new_stderr.append(_aline)
197         new_stderr = array_replace(new_stderr,exclude_strings,["","",""])
198         stderr = "\n".join(new_stderr)
199         """
200         """
201
202         retval = [ret,stdout,stderr]
203
204         if lint is True:
205             if old_ret is True and len(old_lines) != 0:
206                 self.do_lint("\n".join(old_lines),lint=False)
207             elif old_ret is False:
208                 self.do_stop()
209
210         return retval
211
212 """
213 """
214 if __name__ == '__main__':
215     """Testing
216     """
217     parser = iptablesParser()
218     dop = DictOp()
219     dop.addconf("dum",parser.read_conf())
220     lines = dop.get("dum",['config'])
221     lines.append("aa# test")
222     lines.append("bb# test")
223     lines.append("aa# test")
224     #preprint_r(lines)
225
226     dop.set("dum",['config'],lines)
227     conf = dop.getconf("dum")
228     #preprint_r(conf)
229
230     parser.do_stop()
231     print parser.is_running()
232     parser.do_start()
233     print parser.is_running()
234     parser.do_stop()
235     print parser.is_running()
236
237     parser.write_conf(conf,dryrun=True)
238     #parser.do_sync(True)
239     print parser.do_sync(False)
240
241     contents = open("/etc/sysconfig/iptables.corrupted").read()
242     print parser.do_lint(contents)
243