Merge branch 'upstreammaster'
[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 functions eventually 
29 def get_leaf(hrn): return Xrn(hrn).get_leaf()
30 def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
31 def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
32 def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn
33 def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)
34
35 def urn_to_sliver_id(urn, slice_id, node_id, index=0, authority=None):
36     return Xrn(urn).get_sliver_id(slice_id, node_id, index, authority)
37
38 class Xrn:
39
40     ########## basic tools on HRNs
41     # split a HRN-like string into pieces
42     # this is like split('.') except for escaped (backslashed) dots
43     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
44     @staticmethod
45     def hrn_split(hrn):
46         return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]
47
48     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
49     @staticmethod
50     def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]
51
52     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
53     @staticmethod
54     def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]
55     
56     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
57     @staticmethod
58     def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))
59     
60     # e.g. escape ('a.b') -> 'a\.b'
61     @staticmethod
62     def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)
63
64     # e.g. unescape ('a\.b') -> 'a.b'
65     @staticmethod
66     def unescape(token): return token.replace('\\.','.')
67
68     # Return the HRN authority chain from top to bottom.
69     # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']
70     @staticmethod
71     def hrn_auth_chain(hrn):
72         parts = Xrn.hrn_auth_list(hrn)
73         chain = []
74         for i in range(len(parts)):
75             chain.append('.'.join(parts[:i+1]))
76         # Include the HRN itself?
77         #chain.append(hrn)
78         return chain
79
80     # Is the given HRN a true authority over the namespace of the other
81     # child HRN?
82     # A better alternative than childHRN.startswith(parentHRN)
83     # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,
84     # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False
85     # Also hrn_is_uauth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True
86     @staticmethod
87     def hrn_is_auth_for_hrn(parenthrn, hrn):
88         if parenthrn == hrn:
89             return True
90         for auth in Xrn.hrn_auth_chain(hrn):
91             if parenthrn == auth:
92                 return True
93         return False
94
95     ########## basic tools on URNs
96     URN_PREFIX = "urn:publicid:IDN"
97     URN_PREFIX_lower = "urn:publicid:idn"
98
99     @staticmethod
100     def is_urn (text):
101         return text.lower().startswith(Xrn.URN_PREFIX_lower)
102
103     @staticmethod
104     def urn_full (urn):
105         if Xrn.is_urn(urn): return urn
106         else: return Xrn.URN_PREFIX+urn
107     @staticmethod
108     def urn_meaningful (urn):
109         if Xrn.is_urn(urn): return urn[len(Xrn.URN_PREFIX):]
110         else: return urn
111     @staticmethod
112     def urn_split (urn):
113         return Xrn.urn_meaningful(urn).split('+')
114
115     ####################
116     # the local fields that are kept consistent
117     # self.urn
118     # self.hrn
119     # self.type
120     # self.path
121     # provide either urn, or (hrn + type)
122     def __init__ (self, xrn, type=None):
123         if not xrn: xrn = ""
124         # user has specified xrn : guess if urn or hrn
125         if Xrn.is_urn(xrn):
126             self.hrn=None
127             self.urn=xrn
128             self.urn_to_hrn()
129         else:
130             self.urn=None
131             self.hrn=xrn
132             self.type=type
133             self.hrn_to_urn()
134 # happens all the time ..
135 #        if not type:
136 #            debug_logger.debug("type-less Xrn's are not safe")
137
138     def __repr__ (self):
139         result="<XRN u=%s h=%s"%(self.urn,self.hrn)
140         if hasattr(self,'leaf'): result += " leaf=%s"%self.leaf
141         if hasattr(self,'authority'): result += " auth=%s"%self.authority
142         result += ">"
143         return result
144
145     def get_urn(self): return self.urn
146     def get_hrn(self): return self.hrn
147     def get_type(self): return self.type
148     def get_hrn_type(self): return (self.hrn, self.type)
149
150     def _normalize(self):
151         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
152         if not hasattr(self,'leaf'): 
153             self.leaf=Xrn.hrn_split(self.hrn)[-1]
154         # self.authority keeps a list
155         if not hasattr(self,'authority'): 
156             self.authority=Xrn.hrn_auth_list(self.hrn)
157
158     def get_leaf(self):
159         self._normalize()
160         return self.leaf
161
162     def get_authority_hrn(self):
163         self._normalize()
164         return '.'.join( self.authority )
165     
166     def get_authority_urn(self): 
167         self._normalize()
168         return ':'.join( [Xrn.unescape(x) for x in self.authority] )
169    
170     def get_sliver_id(self, slice_id, node_id, index=0, authority=None):
171         self._normalize()
172         urn = self.get_urn()
173         if authority:
174             authority_hrn = self.get_authority_hrn()
175             if not authority_hrn.startswith(authority):
176                 hrn = ".".join([authority,self.get_authority_hrn(), self.get_leaf()])
177             else:
178                 hrn = ".".join([self.get_authority_hrn(), self.get_leaf()])
179             urn = Xrn(hrn, self.get_type()).get_urn()
180         return ":".join(map(str, [urn, slice_id, node_id, index])) 
181  
182     def urn_to_hrn(self):
183         """
184         compute tuple (hrn, type) from urn
185         """
186         
187 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
188         if not Xrn.is_urn(self.urn):
189             raise SfaAPIError, "Xrn.urn_to_hrn"
190
191         parts = Xrn.urn_split(self.urn)
192         type=parts.pop(2)
193         # Remove the authority name (e.g. '.sa')
194         if type == 'authority':
195             name = parts.pop()
196             # Drop the sa. This is a bad hack, but its either this
197             # or completely change how record types are generated/stored   
198             if name != 'sa':
199                 type = type + "+" + name
200             name =""
201         else:
202             name = parts.pop(len(parts)-1)
203         # convert parts (list) into hrn (str) by doing the following
204         # 1. remove blank parts
205         # 2. escape dots inside parts
206         # 3. replace ':' with '.' inside parts
207         # 3. join parts using '.'
208         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part])
209         # dont replace ':' in the name section
210         if name:
211             hrn += '.%s' % Xrn.escape(name) 
212
213         self.hrn=str(hrn)
214         self.type=str(type)
215     
216     def hrn_to_urn(self):
217         """
218         compute urn from (hrn, type)
219         """
220
221 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
222         if Xrn.is_urn(self.hrn):
223             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
224
225         if self.type and self.type.startswith('authority'):
226             self.authority = Xrn.hrn_split(self.hrn)
227             type_parts = self.type.split("+")
228             self.type = type_parts[0]
229             name = 'sa'
230             if len(type_parts) > 1:
231                 name = type_parts[1]
232         else:
233             self.authority = Xrn.hrn_auth_list(self.hrn)
234             name = Xrn.hrn_leaf(self.hrn)
235
236         authority_string = self.get_authority_urn()
237
238         if self.type == None:
239             urn = "+".join(['',authority_string,Xrn.unescape(name)])
240         else:
241             urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])
242         
243         self.urn = Xrn.URN_PREFIX + urn
244
245     def dump_string(self):
246         result="-------------------- XRN\n"
247         result += "URN=%s\n"%self.urn
248         result += "HRN=%s\n"%self.hrn
249         result += "TYPE=%s\n"%self.type
250         result += "LEAF=%s\n"%self.get_leaf()
251         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
252         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
253         return result
254