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