autopep8
[sfa.git] / sfa / util / xrn.py
1 #----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
13 #
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
21 # IN THE WORK.
22 #----------------------------------------------------------------------
23
24 import re
25
26 from sfa.util.faults import SfaAPIError
27
28 # for convenience and smoother translation - we should get rid of these
29 # functions eventually
30
31
32 def get_leaf(hrn): return Xrn(hrn).get_leaf()
33
34
35 def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
36
37
38 def urn_to_hrn(urn): xrn = Xrn(urn)
39 return (xrn.hrn, xrn.type)
40
41
42 def hrn_to_urn(hrn, type): return Xrn(hrn, type=type).urn
43
44
45 def hrn_authfor_hrn(
46     parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)
47
48
49 class Xrn:
50
51     # basic tools on HRNs
52     # split a HRN-like string into pieces
53     # this is like split('.') except for escaped (backslashed) dots
54     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
55     @staticmethod
56     def hrn_split(hrn):
57         return [x.replace('--sep--', '\\.') for x in hrn.replace('\\.', '--sep--').split('.')]
58
59     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
60     @staticmethod
61     def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]
62
63     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
64     @staticmethod
65     def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]
66
67     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
68     @staticmethod
69     def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))
70
71     # e.g. escape ('a.b') -> 'a\.b'
72     @staticmethod
73     def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)
74
75     # e.g. unescape ('a\.b') -> 'a.b'
76     @staticmethod
77     def unescape(token): return token.replace('\\.', '.')
78
79     # Return the HRN authority chain from top to bottom.
80     # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']
81     @staticmethod
82     def hrn_auth_chain(hrn):
83         parts = Xrn.hrn_auth_list(hrn)
84         chain = []
85         for i in range(len(parts)):
86             chain.append('.'.join(parts[:i + 1]))
87         # Include the HRN itself?
88         # chain.append(hrn)
89         return chain
90
91     # Is the given HRN a true authority over the namespace of the other
92     # child HRN?
93     # A better alternative than childHRN.startswith(parentHRN)
94     # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,
95     # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False
96     # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True
97     @staticmethod
98     def hrn_is_auth_for_hrn(parenthrn, hrn):
99         if parenthrn == hrn:
100             return True
101         for auth in Xrn.hrn_auth_chain(hrn):
102             if parenthrn == auth:
103                 return True
104         return False
105
106     # basic tools on URNs
107     URN_PREFIX = "urn:publicid:IDN"
108     URN_PREFIX_lower = "urn:publicid:idn"
109
110     @staticmethod
111     def is_urn(text):
112         return text.lower().startswith(Xrn.URN_PREFIX_lower)
113
114     @staticmethod
115     def urn_full(urn):
116         if Xrn.is_urn(urn):
117             return urn
118         else:
119             return Xrn.URN_PREFIX + urn
120
121     @staticmethod
122     def urn_meaningful(urn):
123         if Xrn.is_urn(urn):
124             return urn[len(Xrn.URN_PREFIX):]
125         else:
126             return urn
127
128     @staticmethod
129     def urn_split(urn):
130         return Xrn.urn_meaningful(urn).split('+')
131
132     @staticmethod
133     def filter_type(urns=None, type=None):
134         if urns is None:
135             urns = []
136         urn_list = []
137         if not type:
138             return urns
139
140         for urn in urns:
141             xrn = Xrn(xrn=urn)
142             if (xrn.type == type):
143                 # Xrn is probably a urn so we can just compare types
144                 urn_list.append(urn)
145         return urn_list
146     ####################
147     # the local fields that are kept consistent
148     # self.urn
149     # self.hrn
150     # self.type
151     # self.path
152     # provide either urn, or (hrn + type)
153
154     def __init__(self, xrn="", type=None, id=None):
155         if not xrn:
156             xrn = ""
157         # user has specified xrn : guess if urn or hrn
158         self.id = id
159         if Xrn.is_urn(xrn):
160             self.hrn = None
161             self.urn = xrn
162             if id:
163                 self.urn = "%s:%s" % (self.urn, str(id))
164             self.urn_to_hrn()
165         else:
166             self.urn = None
167             self.hrn = xrn
168             self.type = type
169             self.hrn_to_urn()
170         self._normalize()
171 # happens all the time ..
172 #        if not type:
173 #            debug_logger.debug("type-less Xrn's are not safe")
174
175     def __repr__(self):
176         result = "<XRN u=%s h=%s" % (self.urn, self.hrn)
177         if hasattr(self, 'leaf'):
178             result += " leaf=%s" % self.leaf
179         if hasattr(self, 'authority'):
180             result += " auth=%s" % self.authority
181         result += ">"
182         return result
183
184     def get_urn(self): return self.urn
185
186     def get_hrn(self): return self.hrn
187
188     def get_type(self): return self.type
189
190     def get_hrn_type(self): return (self.hrn, self.type)
191
192     def _normalize(self):
193         if self.hrn is None:
194             raise SfaAPIError("Xrn._normalize")
195         if not hasattr(self, 'leaf'):
196             self.leaf = Xrn.hrn_split(self.hrn)[-1]
197         # self.authority keeps a list
198         if not hasattr(self, 'authority'):
199             self.authority = Xrn.hrn_auth_list(self.hrn)
200
201     def get_leaf(self):
202         self._normalize()
203         return self.leaf
204
205     def get_authority_hrn(self):
206         self._normalize()
207         return '.'.join(self.authority)
208
209     def get_authority_urn(self):
210         self._normalize()
211         return ':'.join([Xrn.unescape(x) for x in self.authority])
212
213     def set_authority(self, authority):
214         """
215         update the authority section of an existing urn
216         """
217         authority_hrn = self.get_authority_hrn()
218         if not authority_hrn.startswith(authority):
219             hrn = ".".join([authority, authority_hrn, self.get_leaf()])
220         else:
221             hrn = ".".join([authority_hrn, self.get_leaf()])
222
223         self.hrn = hrn
224         self.hrn_to_urn()
225         self._normalize()
226
227     # sliver_id_parts is list that contains the sliver's
228     # slice id and node id
229     def get_sliver_id_parts(self):
230         sliver_id_parts = []
231         if self.type == 'sliver' or '-' in self.leaf:
232             sliver_id_parts = self.leaf.split('-')
233         return sliver_id_parts
234
235     def urn_to_hrn(self):
236         """
237         compute tuple (hrn, type) from urn
238         """
239
240 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
241         if not Xrn.is_urn(self.urn):
242             raise SfaAPIError("Xrn.urn_to_hrn")
243
244         parts = Xrn.urn_split(self.urn)
245         type = parts.pop(2)
246         # Remove the authority name (e.g. '.sa')
247         if type == 'authority':
248             name = parts.pop()
249             # Drop the sa. This is a bad hack, but its either this
250             # or completely change how record types are generated/stored
251             if name != 'sa':
252                 type = type + "+" + name
253             name = ""
254         else:
255             name = parts.pop(len(parts) - 1)
256         # convert parts (list) into hrn (str) by doing the following
257         # 1. remove blank parts
258         # 2. escape dots inside parts
259         # 3. replace ':' with '.' inside parts
260         # 3. join parts using '.'
261         hrn = '.'.join([Xrn.escape(part).replace(':', '.')
262                         for part in parts if part])
263         # dont replace ':' in the name section
264         if name:
265             parts = name.split(':')
266             if len(parts) > 1:
267                 self.id = ":".join(parts[1:])
268                 name = parts[0]
269             hrn += '.%s' % Xrn.escape(name)
270
271         self.hrn = str(hrn)
272         self.type = str(type)
273
274     def hrn_to_urn(self):
275         """
276         compute urn from (hrn, type)
277         """
278
279 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
280         if Xrn.is_urn(self.hrn):
281             raise SfaAPIError("Xrn.hrn_to_urn, hrn=%s" % self.hrn)
282
283         if self.type and self.type.startswith('authority'):
284             self.authority = Xrn.hrn_auth_list(self.hrn)
285             leaf = self.get_leaf()
286             # if not self.authority:
287             #    self.authority = [self.hrn]
288             type_parts = self.type.split("+")
289             self.type = type_parts[0]
290             name = 'sa'
291             if len(type_parts) > 1:
292                 name = type_parts[1]
293             auth_parts = [part for part in [
294                 self.get_authority_urn(), leaf] if part]
295             authority_string = ":".join(auth_parts)
296         else:
297             self.authority = Xrn.hrn_auth_list(self.hrn)
298             name = Xrn.hrn_leaf(self.hrn)
299             authority_string = self.get_authority_urn()
300
301         if self.type == None:
302             urn = "+".join(['', authority_string, Xrn.unescape(name)])
303         else:
304             urn = "+".join(['', authority_string,
305                             self.type, Xrn.unescape(name)])
306
307         if hasattr(self, 'id') and self.id:
308             urn = "%s:%s" % (urn, self.id)
309
310         self.urn = Xrn.URN_PREFIX + urn
311
312     def dump_string(self):
313         result = "-------------------- XRN\n"
314         result += "URN=%s\n" % self.urn
315         result += "HRN=%s\n" % self.hrn
316         result += "TYPE=%s\n" % self.type
317         result += "LEAF=%s\n" % self.get_leaf()
318         result += "AUTH(hrn format)=%s\n" % self.get_authority_hrn()
319         result += "AUTH(urn format)=%s\n" % self.get_authority_urn()
320         return result