Work towards disabling command-line parsing outside of use
[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
26 class PreformattedDescriptionFormatter(IndentedHelpFormatter):
27   
28   #def format_description(self, description):
29   #  
30   #  if description:
31   #      return description + "\n"
32   #  else:
33   #     return ""
34       
35   def format_epilog(self, epilog):
36     """
37     It was removing my preformated epilog, so this should override
38     that behavior! Muhahaha!
39     """
40     if epilog:
41         return "\n" + epilog + "\n"
42     else:
43         return ""
44
45
46 def constructOptionParser():
47   """
48   returns a pre-setup optparser
49   """
50   global DISABLE_CMDLINE
51   
52   if DISABLE_CMDLINE:
53     return None
54   
55   parser = OptionParser(formatter=PreformattedDescriptionFormatter())
56
57   parser.set_description('Retrieves eland config file from ga_frontend web frontend.')
58   
59   parser.epilog = """
60 Config File:
61   * %s (System wide)
62   * %s (User specific; overrides system)
63   * command line overrides all config file options
64   
65   Example Config File:
66   
67     [config_file_server]
68     base_host_url=http://somewhere.domain:port
69 """ % (CONFIG_SYSTEM, CONFIG_USER)
70   
71   #Special formatter for allowing preformatted description.
72   ##parser.format_epilog(PreformattedDescriptionFormatter())
73
74   parser.add_option("-u", "--url",
75                     action="store", type="string", dest="url")
76   
77   parser.add_option("-o", "--output",
78                     action="store", type="string", dest="output_filepath")
79   
80   parser.add_option("-f", "--flowcell",
81                     action="store", type="string", dest="flowcell")
82   
83   #parser.set_default("url", "default")
84   
85   return parser
86
87 def constructConfigParser():
88   """
89   returns a pre-setup config parser
90   """
91   parser = SafeConfigParser()
92   parser.read([CONFIG_SYSTEM, CONFIG_USER])
93   if not parser.has_section('config_file_server'):
94     parser.add_section('config_file_server')
95   
96   return parser
97
98
99 def getCombinedOptions():
100   """
101   Returns optparse options after it has be updated with ConfigParser
102   config files and merged with parsed commandline options.
103   """
104   cl_parser = constructOptionParser()
105   conf_parser = constructConfigParser()
106   
107   if cl_parser is None:
108     options = DummyOptions()
109   else:
110     options, args = cl_parser.parse_args()
111   
112   if options.url is None:
113     if conf_parser.has_option('config_file_server', 'base_host_url'):
114       options.url = conf_parser.get('config_file_server', 'base_host_url')
115   
116   print 'USING OPTIONS:'
117   print ' URL:', options.url
118   print ' OUT:', options.output_filepath
119   print '  FC:', options.flowcell
120   print ''
121   
122   return options
123
124
125 def saveConfigFile(flowcell, base_host_url, output_filepath):
126   """
127   retrieves the flowcell eland config file, give the base_host_url
128   (i.e. http://sub.domain.edu:port)
129   """
130   url = base_host_url + '/eland_config/%s/' % (flowcell)
131   
132   f = open(output_filepath, 'w')
133   #try:
134   web = urllib.urlopen(url)
135   #except IOError, msg:
136   #  if str(msg).find("Connection refused") >= 0:
137   #    print 'Error: Connection refused for: %s' % (url)
138   #    f.close()
139   #    sys.exit(1)
140   #  elif str(msg).find("Name or service not known") >= 0:
141   #    print 'Error: Invalid domain or ip address for: %s' % (url)
142   #    f.close()
143   #    sys.exit(2)
144   #  else:
145   #    raise IOError, msg
146
147   data = web.read()
148
149   if data.find('Hmm, config file for') >= 0:
150     msg = "Flowcell (%s) not found in DB; full url(%s)" % (flowcell, url)
151     raise FlowCellNotFound, msg
152
153   if data.find('404 - Not Found') >= 0:
154     msg = "404 - Not Found: Flowcell (%s); base_host_url (%s);\n full url(%s)\n " \
155           "Did you get right port #?" % (flowcell, base_host_url, url)
156     raise FlowCellNotFound, msg
157   
158   f.write(data)
159   web.close()
160   f.close()
161   print 'Wrote config file to %s' % (output_filepath)
162
163