1
2
3
4
5
6
7
8
9
10
11
12
13
14 __doc__="""CmdBase
15
16 Provide utility functions for logging and config file parsing
17 to command line programs
18
19
20 $Id: CmdBase.py,v 1.10 2004/04/04 02:22:21 edahl Exp $"""
21
22 __version__ = "$Revision: 1.10 $"[11:-2]
23
24 import os
25 import sys
26 import logging
27 import logging.config
28 from optparse import OptionParser, SUPPRESS_HELP, NO_DEFAULT
29
30
32 """parse a config file which has key value pairs delimited by white space"""
33 if not os.path.exists(options.configfile):
34 print >>sys.stderr, "WARN: config file %s not found skipping" % (
35 options.configfile)
36 return
37 lines = open(options.configfile).readlines()
38 for line in lines:
39 if line.lstrip().startswith('#'): continue
40 if line.strip() == '': continue
41 key, value = line.split(None, 1)
42 value = value.rstrip('\r\n')
43 key = key.lower()
44 defval = getattr(options, key, None)
45 if defval: value = type(defval)(value)
46 setattr(options, key, value)
47
48
50
52
53 doesLogging = True
54
67
68
70 rlog = logging.getLogger()
71 rlog.setLevel(logging.WARN)
72 mname = self.__class__.__name__
73 self.log = logging.getLogger("zen."+ mname)
74 zlog = logging.getLogger("zen")
75 zlog.setLevel(self.options.logseverity)
76 if self.options.logpath:
77 logdir = self.options.logpath
78 if not os.path.isdir(os.path.dirname(logdir)):
79 raise SystemExit("logpath:%s doesn't exist" % logdir)
80 logfile = os.path.join(logdir, mname.lower()+".log")
81 h = logging.FileHandler(logfile)
82 h.setFormatter(logging.Formatter(
83 "%(asctime)s %(levelname)s %(name)s: %(message)s",
84 "%Y-%m-%d %H:%M:%S"))
85 rlog.addHandler(h)
86 else:
87 logging.basicConfig()
88
89
91 if not self.parser:
92 self.parser = OptionParser(usage=self.usage,
93 version="%prog " + __version__)
94
96 """basic options setup sub classes can add more options here"""
97 self.buildParser()
98 if self.doesLogging:
99 self.parser.add_option('-v', '--logseverity',
100 dest='logseverity',
101 default=20,
102 type='int',
103 help='Logging severity threshold')
104 self.parser.add_option('--logpath',dest='logpath',
105 help='override default logging path')
106 self.parser.add_option("-C", "--configfile",
107 dest="configfile",
108 help="config file must define all params (see man)")
109
110
111
163
164
165
167 """Create a configuration file based on the long-form of the option names"""
168
169
170
171
172 daemon_name= os.path.basename( sys.argv[0] )
173 daemon_name= daemon_name.replace( '.py', '' )
174
175 print """#
176 # Configuration file for %s
177 #
178 # To enable a particular option, uncomment the desired entry.
179 #
180 # Parameter Setting
181 # --------- -------""" % ( daemon_name )
182
183
184 options_to_ignore= ( 'help', 'version', '', 'genconf', 'genxmltable' )
185
186
187
188
189
190
191
192 import re
193 for opt in parser.option_list:
194 if opt.help is SUPPRESS_HELP:
195 continue
196
197
198
199
200 option_name= re.sub( r'.*/--', '', "%s" % opt )
201
202
203
204
205 option_name= re.sub( r'^--', '', "%s" % option_name )
206
207
208
209
210 if option_name in options_to_ignore:
211 continue
212
213
214
215
216
217 value= getattr( parser.values, opt.dest )
218
219 default_value= parser.defaults.get( opt.dest )
220 if default_value is NO_DEFAULT or default_value is None:
221 default_value= ""
222 default_string= ""
223 if default_value != "":
224 default_string= ", default: " + str( default_value )
225
226 comment= self.pretty_print_config_comment( opt.help + default_string )
227
228
229
230
231
232 print """#
233 # %s
234 #%s %s""" % ( comment, option_name, value )
235
236
237
238
239 print "#"
240 sys.exit( 0 )
241
242
243
245 """Create a Docbook table based on the long-form of the option names"""
246
247
248
249
250 daemon_name= os.path.basename( sys.argv[0] )
251 daemon_name= daemon_name.replace( '.py', '' )
252
253 print """<?xml version="1.0" encoding="UTF-8"?>
254
255 <section version="4.0" xmlns="http://docbook.org/ns/docbook"
256 xmlns:xlink="http://www.w3.org/1999/xlink"
257 xmlns:xi="http://www.w3.org/2001/XInclude"
258 xmlns:svg="http://www.w3.org/2000/svg"
259 xmlns:mml="http://www.w3.org/1998/Math/MathML"
260 xmlns:html="http://www.w3.org/1999/xhtml"
261 xmlns:db="http://docbook.org/ns/docbook"
262
263 xml:id="%s.options"
264 >
265
266 <title>%s Options</title>
267 <para />
268 <table frame="all">
269 <caption>%s <indexterm><primary>Daemons</primary><secondary>%s</secondary></indexterm> options</caption>
270 <tgroup cols="2">
271 <colspec colname="option" colwidth="1*" />
272 <colspec colname="description" colwidth="2*" />
273 <thead>
274 <row>
275 <entry> <para>Option</para> </entry>
276 <entry> <para>Description</para> </entry>
277 </row>
278 </thead>
279 <tbody>
280 """ % ( daemon_name, daemon_name, daemon_name, daemon_name )
281
282
283 options_to_ignore= ( 'help', 'version', '', 'genconf', 'genxmltable' )
284
285
286
287
288
289
290
291 import re
292 for opt in parser.option_list:
293 if opt.help is SUPPRESS_HELP:
294 continue
295
296
297
298
299
300
301 all_options= '<literal>' + re.sub( r'/', '</literal>,</para> <para><literal>', "%s" % opt ) + '</literal>'
302
303
304
305
306 option_name= re.sub( r'.*/--', '', "%s" % opt )
307 option_name= re.sub( r'^--', '', "%s" % option_name )
308 if option_name in options_to_ignore:
309 continue
310
311 default_value= parser.defaults.get( opt.dest )
312 if default_value is NO_DEFAULT or default_value is None:
313 default_value= ""
314 default_string= ""
315 if default_value != "":
316 default_string= "<para> Default: <literal>" + str( default_value ) + "</literal></para>\n"
317
318 comment= self.pretty_print_config_comment( opt.help )
319
320
321
322
323 if opt.action in [ 'store_true', 'store_false' ]:
324 print """<row>
325 <entry> <para>%s</para> </entry>
326 <entry>
327 <para>%s</para>
328 %s</entry>
329 </row>
330 """ % ( all_options, comment, default_string )
331
332 else:
333 target= '=<replaceable>' + opt.dest.lower() + '</replaceable>'
334 all_options= all_options + target
335 all_options= re.sub( r',', target + ',', all_options )
336 print """<row>
337 <entry> <para>%s</para> </entry>
338 <entry>
339 <para>%s</para>
340 %s</entry>
341 </row>
342 """ % ( all_options, comment, default_string )
343
344
345
346
347
348
349 print """</tbody></tgroup>
350 </table>
351 <para />
352 </section>
353 """
354 sys.exit( 0 )
355
356
357
359
360 self.parser.add_option("--genconf",
361 action="store_true",
362 default=False,
363 help="Generate a template configuration file" )
364
365 self.parser.add_option("--genxmltable",
366 action="store_true",
367 default=False,
368 help="Generate a Docbook table showing command-line switches." )
369
370 if self.noopts:
371 args = []
372 else:
373 import sys
374 args = sys.argv[1:]
375 (self.options, self.args) = self.parser.parse_args(args=args)
376
377 if self.options.genconf:
378 self.generate_configs( self.parser, self.options )
379
380 if self.options.genxmltable:
381 self.generate_xml_table( self.parser, self.options )
382