2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation;
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # Author: Lucia Guevgeozian Odizzio <lucia.guevgeozian_odizzio@inria.fr>
24 class MANIFOLDAPI(object):
26 API to query different data platforms as SFA, TopHat, OML Central Server,
27 using Manifold Framework, the backend of MySlice.
29 def __init__(self, username, password, hostname, urlpattern):
31 self.auth_pwd = dict(AuthMethod='password', Username=username,
33 self._url = urlpattern % {'hostname':hostname}
34 self.lock = threading.Lock()
35 self.auth = self.get_session_key()
39 return xmlrpclib.Server(self._url, allow_none = True)
41 def get_session_key(self):
43 Retrieves the session key, in order to use the same session for
46 query = {'timestamp' : 'now', 'object': 'local:session',
47 'filters' : [], 'fields' : [], 'action' : 'create'}
49 session = self.api.forward(self.auth_pwd, query)
51 if not session['value']:
52 msg = "Can not authenticate in Manifold API"
53 raise RuntimeError, msg
55 session_key = session['value'][0]['session']
56 return dict(AuthMethod='session', session=session_key)
58 def get_resource_info(self, filters=None, fields=None):
60 Create and execute the Manifold API Query to get the resources
61 according fields and filters.
62 :param filters: resource's constraints for the experiment
64 :param fields: desire fields in the result of the query
67 query = {'action' : 'get', 'object' : 'resource'}
70 filters = self._map_attr_to_resource_filters(filters)
73 for filtername, filtervalue in filters.iteritems():
74 newfilter = [filtername, "==", filtervalue]
75 qfilters.append(newfilter)
77 query['filters'] = qfilters
80 fields = self._check_valid_fields(fields)
83 query['fields'] = fields
85 return self.api.forward(self.auth, query)['value']
87 def get_resource_urn(self, filters=None):
89 Retrieves the resources urn of the resources matching filters.
91 return self.get_resource_info(filters, 'urn')
93 def get_slice_resources(self, slicename):
95 Retrieves resources attached to user's slice.
96 return value: list of resources' urn
99 query = {'action' : 'get', 'object' : 'resource',
100 'filters' : [['slice','==', slicename]],
104 value = self.api.forward(self.auth, query)['value']
106 for resource in value:
107 result.append(resource['urn'])
111 def add_resource_to_slice(self, slicename, resource_urn):
113 Add resource to user's slice. The query needs to specify the new
114 resource plus the previous resources already in the slice.
116 resources = self.get_slice_resources(slicename)
117 resources.append(resource_urn)
123 urn_list.append(urn_dict)
125 query = {'action' : 'update', 'object' : 'slice',
126 'filters' : [['slice_hrn','==', slicename]],
127 'params' : {'resource' : urn_list}}
130 self.api.forward(self.auth, query)
132 resources = self.get_slice_resources(slicename)
133 if resource_urn in resources:
136 msg = "Failed while trying to add %s to slice" % resource_urn
138 # check how to do warning
141 def remove_resource_from_slice(self, slicename, resource_urn):
143 Remove resource from user's slice. The query needs to specify the list
144 of previous resources in the slice without the one to be remove.
146 resources = self.get_slice_resources(slicename)
147 resources.remove(resource_urn)
153 urn_list.append(urn_dict)
155 query = {'action' : 'update', 'object' : 'slice',
156 'filters' : [['slice_hrn','==', slicename]],
157 'params' : {'resource' : urn_list}}
160 self.api.forward(self.auth, query)
162 resources = self.get_slice_resources(slicename)
163 if resource_urn not in resources:
166 msg = "Failed while trying to remove %s to slice" % resource_urn
167 # check how to do warning
170 def _get_metadata(self):
172 This method is useful to retrive metadata from different platforms
173 in order to update fields and possible filters.
175 query = {'action' : 'get', 'object' : 'local:object',
176 'filters' : [['table','=','resource']]}
178 res = self.api.forward(self.auth, query)
180 valid_fields = list()
181 for i in res['value'][0]['column']:
182 valid_fields.append(i['name'])
186 def _map_attr_to_resource_filters(self, filters):
188 Depending on the object used for the Manifold query, the filters and
189 fields can change its sintaxis. A resource field in a slice object
190 query adds 'resource.' to the field. Other changes don't follow any
191 particular convention.
193 #TODO: find out useful filters
195 'hostname' : 'hostname',
196 'longitude' : 'longitude',
197 'latitude' : 'latitude',
198 'network' : 'network',
199 'component_id' : 'component_id'
202 mapped_filters = dict()
203 for filtername, filtervalue in filters.iteritems():
204 if attr_to_filter[filtername]:
205 new_filtername = attr_to_filter[filtername]
206 mapped_filters[new_filtername] = filtervalue
208 return mapped_filters
210 def _check_valid_fields(self, fields):
212 The fields can be a predefine set, define in the Manifold metadata.
214 valid_fields = self._get_metadata()
216 if not isinstance(fields, list):
220 if field not in valid_fields:
222 #self.warning(" Invalid Manifold field or filter ")
227 class MANIFOLDAPIFactory(object):
229 API Factory to manage a map of MANIFOLDAPI instances as key-value pairs, it
230 instanciate a single instance per key. The key represents the same SFA,
231 MF (ManiFold) credentials.
234 _lock = threading.Lock()
238 def get_api(cls, username, password,
239 #hostname = "manifold.pl.sophia.inria.fr",
240 hostname ="test.myslice.info",
241 urlpattern = "http://%(hostname)s:7080"):
243 :param username: Manifold user (also used for MySlice web login)
245 :param password: Manifold password (also used for MySlice web login)
247 :param hostname: Hostname of the Manifold API to query SFA, TopHat, etc
249 :param urlpattern: Url of the Manifold API to query SFA, TopHat, etc
250 :type urlpattern: str
253 if username and password:
254 key = cls.make_key(username, password)
256 api = cls._apis.get(key)
259 api = MANIFOLDAPI(username, password, hostname, urlpattern)
267 def make_key(cls, *args):
268 skey = "".join(map(str, args))
269 return hashlib.md5(skey).hexdigest()