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