Replace some prints with logging.info messages and
[htsworkflow.git] / htsworkflow / pipelines / retrieve_config.py
1 #!/usr/bin/env python
2
3 from optparse import OptionParser, IndentedHelpFormatter
4 from ConfigParser import SafeConfigParser
5
6 import logging
7 import os
8 import sys
9 import urllib2
10
11 __docformat__ = "restructredtext en"
12
13 CONFIG_SYSTEM = '/etc/hts_frontend/hts_frontend.conf'
14 CONFIG_USER = os.path.expanduser('~/.hts_frontend.conf')
15
16 #Disable or enable commandline arg parsing; disabled by default.
17 DISABLE_CMDLINE = True
18
19 class FlowCellNotFound(Exception): pass
20 class WebError404(Exception): pass
21
22 class DummyOptions:
23   """
24   Used when command line parsing is disabled; default
25   """
26   def __init__(self):
27     self.url = None
28     self.output_filepath = None
29     self.flowcell = None
30     self.genome_dir = None
31
32 class PreformattedDescriptionFormatter(IndentedHelpFormatter):
33   
34   #def format_description(self, description):
35   #  
36   #  if description:
37   #      return description + "\n"
38   #  else:
39   #     return ""
40       
41   def format_epilog(self, epilog):
42     """
43     It was removing my preformated epilog, so this should override
44     that behavior! Muhahaha!
45     """
46     if epilog:
47         return "\n" + epilog + "\n"
48     else:
49         return ""
50
51
52 def constructOptionParser():
53   """
54   returns a pre-setup optparser
55   """
56   global DISABLE_CMDLINE
57   
58   if DISABLE_CMDLINE:
59     return None
60   
61   parser = OptionParser(formatter=PreformattedDescriptionFormatter())
62
63   parser.set_description('Retrieves eland config file from hts_frontend web frontend.')
64   
65   parser.epilog = """
66 Config File:
67   * %s (System wide)
68   * %s (User specific; overrides system)
69   * command line overrides all config file options
70   
71   Example Config File:
72   
73     [config_file_server]
74     base_host_url=http://somewhere.domain:port
75 """ % (CONFIG_SYSTEM, CONFIG_USER)
76   
77   #Special formatter for allowing preformatted description.
78   ##parser.format_epilog(PreformattedDescriptionFormatter())
79
80   parser.add_option("-u", "--url",
81                     action="store", type="string", dest="url")
82   
83   parser.add_option("-o", "--output",
84                     action="store", type="string", dest="output_filepath")
85   
86   parser.add_option("-f", "--flowcell",
87                     action="store", type="string", dest="flowcell")
88
89   parser.add_option("-g", "--genome_dir",
90                     action="store", type="string", dest="genome_dir")
91   
92   #parser.set_default("url", "default")
93   
94   return parser
95
96 def constructConfigParser():
97   """
98   returns a pre-setup config parser
99   """
100   parser = SafeConfigParser()
101   parser.read([CONFIG_SYSTEM, CONFIG_USER])
102   if not parser.has_section('config_file_server'):
103     parser.add_section('config_file_server')
104   if not parser.has_section('local_setup'):
105     parser.add_section('local_setup')
106   
107   return parser
108
109
110 def getCombinedOptions():
111   """
112   Returns optparse options after it has be updated with ConfigParser
113   config files and merged with parsed commandline options.
114   """
115   cl_parser = constructOptionParser()
116   conf_parser = constructConfigParser()
117   
118   if cl_parser is None:
119     options = DummyOptions()
120   else:
121     options, args = cl_parser.parse_args()
122   
123   if options.url is None:
124     if conf_parser.has_option('config_file_server', 'base_host_url'):
125       options.url = conf_parser.get('config_file_server', 'base_host_url')
126
127   if options.genome_dir is None:
128     if conf_parser.has_option('local_setup', 'genome_dir'):
129       options.genome_dir = conf_parser.get('local_setup', 'genome_dir')
130   
131   logging.info('USING OPTIONS:')
132   logging.info(' URL: %s' % (options.url,))
133   logging.info(' OUT: %s' % (options.output_filepath,))
134   logging.info('  FC: %s' % (options.flowcell,))
135   logging.info('GDIR: %s' % (options.genome_dir,))
136   
137   return options
138
139
140 def saveConfigFile(flowcell, base_host_url, output_filepath):
141   """
142   retrieves the flowcell eland config file, give the base_host_url
143   (i.e. http://sub.domain.edu:port)
144   """
145   url = base_host_url + '/eland_config/%s/' % (flowcell)
146   
147   f = open(output_filepath, 'w')
148   #try:
149   try:
150     web = urllib2.urlopen(url)
151   except urllib2.URLError, e:
152     errmsg = 'URLError: %d %s' % (e.code, e.msg)
153     logging.error(errmsg)
154     logging.error('opened %s' % (url,))
155     raise IOError(errmsg)
156
157   #except IOError, msg:
158   #  if str(msg).find("Connection refused") >= 0:
159   #    print 'Error: Connection refused for: %s' % (url)
160   #    f.close()
161   #    sys.exit(1)
162   #  elif str(msg).find("Name or service not known") >= 0:
163   #    print 'Error: Invalid domain or ip address for: %s' % (url)
164   #    f.close()
165   #    sys.exit(2)
166   #  else:
167   #    raise IOError, msg
168
169   data = web.read()
170
171   if data.find('Hmm, config file for') >= 0:
172     msg = "Flowcell (%s) not found in DB; full url(%s)" % (flowcell, url)
173     raise FlowCellNotFound, msg
174
175   if data.find('404 - Not Found') >= 0:
176     msg = "404 - Not Found: Flowcell (%s); base_host_url (%s);\n full url(%s)\n " \
177           "Did you get right port #?" % (flowcell, base_host_url, url)
178     raise FlowCellNotFound, msg
179   
180   f.write(data)
181   web.close()
182   f.close()
183   logging.info('Wrote config file to %s' % (output_filepath,))
184
185