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