minor and harmless cosmetic changes
[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):
33     return Xrn(hrn).get_leaf()
34
35
36 def get_authority(hrn):
37     return Xrn(hrn).get_authority_hrn()
38
39
40 def urn_to_hrn(urn):
41     xrn = Xrn(urn)
42     return (xrn.hrn, xrn.type)
43
44
45 def hrn_to_urn(hrn, type): return Xrn(hrn, type=type).urn
46
47
48 def hrn_authfor_hrn(parenthrn, hrn):
49     return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)
50
51
52 class Xrn:
53
54     # basic tools on HRNs
55     # split a HRN-like string into pieces
56     # this is like split('.') except for escaped (backslashed) dots
57     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
58     @staticmethod
59     def hrn_split(hrn):
60         return [x.replace('--sep--', '\\.')
61                 for x in hrn.replace('\\.', '--sep--').split('.')]
62
63     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
64     @staticmethod
65     def hrn_leaf(hrn):
66         return Xrn.hrn_split(hrn)[-1]
67
68     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
69     @staticmethod
70     def hrn_auth_list(hrn):
71         return Xrn.hrn_split(hrn)[0:-1]
72
73     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
74     @staticmethod
75     def hrn_auth(hrn):
76         return '.'.join(Xrn.hrn_auth_list(hrn))
77
78     # e.g. escape ('a.b') -> 'a\.b'
79     @staticmethod
80     def escape(token):
81         return re.sub(r'([^\\])\.', r'\1\.', token)
82
83     # e.g. unescape ('a\.b') -> 'a.b'
84     @staticmethod
85     def unescape(token):
86         return token.replace('\\.', '.')
87
88     # Return the HRN authority chain from top to bottom.
89     # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']
90     @staticmethod
91     def hrn_auth_chain(hrn):
92         parts = Xrn.hrn_auth_list(hrn)
93         chain = []
94         for i in range(len(parts)):
95             chain.append('.'.join(parts[:i + 1]))
96         # Include the HRN itself?
97         # chain.append(hrn)
98         return chain
99
100     # Is the given HRN a true authority over the namespace of the other
101     # child HRN?
102     # A better alternative than childHRN.startswith(parentHRN)
103     # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,
104     # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False
105     # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True
106     @staticmethod
107     def hrn_is_auth_for_hrn(parenthrn, hrn):
108         if parenthrn == hrn:
109             return True
110         for auth in Xrn.hrn_auth_chain(hrn):
111             if parenthrn == auth:
112                 return True
113         return False
114
115     # basic tools on URNs
116     URN_PREFIX = "urn:publicid:IDN"
117     URN_PREFIX_lower = "urn:publicid:idn"
118
119     @staticmethod
120     def is_urn(text):
121         return text.lower().startswith(Xrn.URN_PREFIX_lower)
122
123     @staticmethod
124     def urn_full(urn):
125         if Xrn.is_urn(urn):
126             return urn
127         else:
128             return Xrn.URN_PREFIX + urn
129
130     @staticmethod
131     def urn_meaningful(urn):
132         if Xrn.is_urn(urn):
133             return urn[len(Xrn.URN_PREFIX):]
134         else:
135             return urn
136
137     @staticmethod
138     def urn_split(urn):
139         return Xrn.urn_meaningful(urn).split('+')
140
141     @staticmethod
142     def filter_type(urns=None, type=None):
143         if urns is None:
144             urns = []
145         urn_list = []
146         if not type:
147             return urns
148
149         for urn in urns:
150             xrn = Xrn(xrn=urn)
151             if (xrn.type == type):
152                 # Xrn is probably a urn so we can just compare types
153                 urn_list.append(urn)
154         return urn_list
155     ####################
156     # the local fields that are kept consistent
157     # self.urn
158     # self.hrn
159     # self.type
160     # self.path
161     # provide either urn, or (hrn + type)
162
163     def __init__(self, xrn="", type=None, id=None):
164         if not xrn:
165             xrn = ""
166         # user has specified xrn : guess if urn or hrn
167         self.id = id
168         if Xrn.is_urn(xrn):
169             self.hrn = None
170             self.urn = xrn
171             if id:
172                 self.urn = "%s:%s" % (self.urn, str(id))
173             self.urn_to_hrn()
174         else:
175             self.urn = None
176             self.hrn = xrn
177             self.type = type
178             self.hrn_to_urn()
179         self._normalize()
180
181     def __repr__(self):
182         result = "<XRN u=%s h=%s" % (self.urn, self.hrn)
183         if hasattr(self, 'leaf'):
184             result += " leaf=%s" % self.leaf
185         if hasattr(self, 'authority'):
186             result += " auth=%s" % self.authority
187         result += ">"
188         return result
189
190     def get_urn(self): return self.urn
191
192     def get_hrn(self): return self.hrn
193
194     def get_type(self): return self.type
195
196     def get_hrn_type(self): return (self.hrn, self.type)
197
198     def _normalize(self):
199         if self.hrn is None:
200             raise SfaAPIError("Xrn._normalize")
201         if not hasattr(self, 'leaf'):
202             self.leaf = Xrn.hrn_split(self.hrn)[-1]
203         # self.authority keeps a list
204         if not hasattr(self, 'authority'):
205             self.authority = Xrn.hrn_auth_list(self.hrn)
206
207     def get_leaf(self):
208         self._normalize()
209         return self.leaf
210
211     def get_authority_hrn(self):
212         self._normalize()
213         return '.'.join(self.authority)
214
215     def get_authority_urn(self):
216         self._normalize()
217         return ':'.join([Xrn.unescape(x) for x in self.authority])
218
219     def set_authority(self, authority):
220         """
221         update the authority section of an existing urn
222         """
223         authority_hrn = self.get_authority_hrn()
224         if not authority_hrn.startswith(authority):
225             hrn = ".".join([authority, authority_hrn, self.get_leaf()])
226         else:
227             hrn = ".".join([authority_hrn, self.get_leaf()])
228
229         self.hrn = hrn
230         self.hrn_to_urn()
231         self._normalize()
232
233     # sliver_id_parts is list that contains the sliver's
234     # slice id and node id
235     def get_sliver_id_parts(self):
236         sliver_id_parts = []
237         if self.type == 'sliver' or '-' in self.leaf:
238             sliver_id_parts = self.leaf.split('-')
239         return sliver_id_parts
240
241     def urn_to_hrn(self):
242         """
243         compute tuple (hrn, type) from urn
244         """
245
246 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
247         if not Xrn.is_urn(self.urn):
248             raise SfaAPIError("Xrn.urn_to_hrn")
249
250         parts = Xrn.urn_split(self.urn)
251         type = parts.pop(2)
252         # Remove the authority name (e.g. '.sa')
253         if type == 'authority':
254             name = parts.pop()
255             # Drop the sa. This is a bad hack, but its either this
256             # or completely change how record types are generated/stored
257             if name != 'sa':
258                 type = type + "+" + name
259             name = ""
260         else:
261             name = parts.pop(len(parts) - 1)
262         # convert parts (list) into hrn (str) by doing the following
263         # 1. remove blank parts
264         # 2. escape dots inside parts
265         # 3. replace ':' with '.' inside parts
266         # 3. join parts using '.'
267         hrn = '.'.join([Xrn.escape(part).replace(':', '.')
268                         for part in parts if part])
269         # dont replace ':' in the name section
270         if name:
271             parts = name.split(':')
272             if len(parts) > 1:
273                 self.id = ":".join(parts[1:])
274                 name = parts[0]
275             hrn += '.%s' % Xrn.escape(name)
276
277         self.hrn = str(hrn)
278         self.type = str(type)
279
280     def hrn_to_urn(self):
281         """
282         compute urn from (hrn, type)
283         """
284
285 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
286         if Xrn.is_urn(self.hrn):
287             raise SfaAPIError("Xrn.hrn_to_urn, hrn=%s" % self.hrn)
288
289         if self.type and self.type.startswith('authority'):
290             self.authority = Xrn.hrn_auth_list(self.hrn)
291             leaf = self.get_leaf()
292             # if not self.authority:
293             #    self.authority = [self.hrn]
294             type_parts = self.type.split("+")
295             self.type = type_parts[0]
296             name = 'sa'
297             if len(type_parts) > 1:
298                 name = type_parts[1]
299             auth_parts = [part for part in [
300                 self.get_authority_urn(), leaf] if part]
301             authority_string = ":".join(auth_parts)
302         else:
303             self.authority = Xrn.hrn_auth_list(self.hrn)
304             name = Xrn.hrn_leaf(self.hrn)
305             authority_string = self.get_authority_urn()
306
307         if self.type is None:
308             urn = "+".join(['', authority_string, Xrn.unescape(name)])
309         else:
310             urn = "+".join(['', authority_string,
311                             self.type, Xrn.unescape(name)])
312
313         if hasattr(self, 'id') and self.id:
314             urn = "%s:%s" % (urn, self.id)
315
316         self.urn = Xrn.URN_PREFIX + urn
317
318     def dump_string(self):
319         result = "-------------------- XRN\n"
320         result += "URN=%s\n" % self.urn
321         result += "HRN=%s\n" % self.hrn
322         result += "TYPE=%s\n" % self.type
323         result += "LEAF=%s\n" % self.get_leaf()
324         result += "AUTH(hrn format)=%s\n" % self.get_authority_hrn()
325         result += "AUTH(urn format)=%s\n" % self.get_authority_urn()
326         return result