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