7cb116bb66d7be5f5d104f1b774d9b7000e6db73
[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: Could not connect to: %s' % (url)
117       f.close()
118       sys.exit(1)
119     else:
120       raise IOError, msg
121     
122   f.write(web.read())
123   web.close()
124   f.close()
125
126 if __name__ == '__main__':
127   #Display help if no args are presented
128   if len(sys.argv) == 1:
129     sys.argv.append('-h')
130     
131   options = getCombinedOptions()
132   msg_list = ['ERROR MESSAGES:']
133   if options.output_filepath is None:
134     msg_list.append("  Output filepath argument required. -o <filepath> or --output=<filepath>")
135     
136   if options.flowcell is None:
137     msg_list.append("  Flow cell argument required. -f <flowcell> or --flowcell=<flowcell>")
138     
139   if options.url is None:
140     msg_list.append("  URL argument required (-u <url> or --url=<url>), or entry\n" \
141                     "    in /etc/elandifier/elandifer.conf or ~/.elandifier.conf")
142     
143   if len(msg_list) > 1:
144     print '\n'.join(msg_list)
145     sys.exit(0)
146   
147   saveConfigFile(options.flowcell, options.url, options.output_filepath)
148