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