Major updateds to encode_find for extracting encode cell line life cycle.
[htsworkflow.git] / htsworkflow / util / api.py
1 """Common functions for accessing the HTS Workflow REST API
2 """
3 from ConfigParser import SafeConfigParser
4 import logging
5
6 # try to deal with python <2.6
7 try:
8   import json
9 except ImportError:
10   import simplejson as json
11
12 import os
13 from optparse import OptionGroup
14 import urllib
15 import urllib2
16 import urlparse
17
18
19 def add_auth_options(parser):
20     """Add options OptParser configure authentication options
21     """
22     # Load defaults from the config files
23     config = SafeConfigParser()
24     config.read([os.path.expanduser('~/.htsworkflow.ini'),
25                  '/etc/htsworkflow.ini'
26                  ])
27     
28     sequence_archive = None
29     apiid = None
30     apikey = None
31     apihost = None
32     SECTION = 'sequence_archive'
33     if config.has_section(SECTION):
34         sequence_archive = config.get(SECTION, 'sequence_archive',sequence_archive)
35         sequence_archive = os.path.expanduser(sequence_archive)
36         apiid = config.get(SECTION, 'apiid', apiid)
37         apikey = config.get(SECTION, 'apikey', apikey)
38         apihost = config.get(SECTION, 'host', apihost)
39
40     # configuration options
41     group = OptionGroup(parser, "htsw api authentication")
42     group.add_option('--apiid', default=apiid, help="Specify API ID")
43     group.add_option('--apikey', default=apikey, help="Specify API KEY")
44     group.add_option('--host',  default=apihost,
45                      help="specify HTSWorkflow host",)
46     group.add_option('--sequence', default=sequence_archive,
47                      help="sequence repository")
48     parser.add_option_group(group)
49
50 def make_auth_from_opts(opts, parser):
51     """Create htsw auth info dictionary from optparse info
52     """
53     if opts.host is None or opts.apiid is None or opts.apikey is None:
54         parser.error("Please specify host url, apiid, apikey")
55         
56     return {'apiid': opts.apiid, 'apikey': opts.apikey }
57
58
59 def library_url(root_url, library_id):
60     """
61     Return the url for retrieving information about a specific library.
62
63     Args:
64       library_id (str): the library id of interest
65       root_url (str): the root portion of the url, e.g. http://localhost
66
67     Returns:
68       str. The url to use for this REST api.
69
70     >>> print library_url('http://localhost', '12345')
71     http://localhost/samples/library/12345/json
72
73     """
74     url_fragment = '/samples/library/%s/json' % (library_id,)
75     url = urlparse.urljoin(root_url, url_fragment)
76
77     return url
78
79
80 def flowcell_url(root_url, flowcell_id):
81     """
82     Return the url for retrieving information about a specific flowcell.
83
84     Args:
85       root_url (str): the root portion of the url, e.g. http://localhost
86       flowcell_id (str): the flowcell id of interest
87
88     Returns:
89       str. The url to use for this REST api.
90
91     >>> print flowcell_url('http://localhost', '1234AAXX')
92     http://localhost/experiments/config/1234AAXX/json
93     """
94     url_fragment = '/experiments/config/%s/json' % (flowcell_id,)
95     url = urlparse.urljoin(root_url, url_fragment)
96
97     return url
98
99
100 def lanes_for_user_url(root_url, username):
101     """
102     Return the url for returning all the lanes associated with a username
103     
104     Args:
105       username (str): a username in your target filesystem
106       root_url (str): the root portion of the url, e.g. http://localhost
107
108     Returns:
109       str. The url to use for this REST api.
110
111     >>> print lanes_for_user_url('http://localhost', 'diane')
112     http://localhost/lanes_for/diane/json
113
114     """
115     url_fragment = '/lanes_for/%s/json' % (username,)
116     url = urlparse.urljoin(root_url, url_fragment)
117
118     return url
119
120 def retrieve_info(url, apidata):
121     """
122     Return a dictionary from the HTSworkflow API
123     """
124     try:
125         apipayload = urllib.urlencode(apidata)
126         web = urllib2.urlopen(url, apipayload)
127     except urllib2.URLError, e:
128         if hasattr(e, 'code') and e.code == 404:
129             logging.info("%s was not found" % (url,))
130             return None
131         else:
132             errmsg = 'URLError: %s' % (str(e))
133             raise IOError(errmsg)
134     
135     contents = web.read()
136     headers = web.info()
137
138     return json.loads(contents)
139
140 class HtswApi(object):
141   def __init__(self, root_url, authdata):
142     self.root_url = root_url
143     self.authdata = authdata
144
145   def get_flowcell(self, flowcellId):
146     url = flowcell_url(self.root_url, flowcellId)
147     return retrieve_info(url, self.authdata)
148
149   def get_library(self, libraryId):
150     url = library_url(self.root_url, libraryId)
151     return retrieve_info(url, self.authdata)
152
153   def get_lanes_for_user(self, user):
154     url = lanes_for_user(self.root_url, user)
155     return retrieve_info(url, self.authdata)
156
157   def get_url(self, url):
158     return retrieve_info(url, self.authdata)
159