Merge branch 'master' into senslab2
[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 import sys
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):
36     return Xrn(urn).get_sliver_id(slice_id, node_id, index)
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     URN_PREFIX = "urn:publicid:IDN"
96
97     ########## basic tools on URNs
98     @staticmethod
99     def urn_full (urn):
100         if urn.startswith(Xrn.URN_PREFIX): return urn
101         else: return Xrn.URN_PREFIX+urn
102     @staticmethod
103     def urn_meaningful (urn):
104         if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]
105         else: return urn
106     @staticmethod
107     def urn_split (urn):
108         return Xrn.urn_meaningful(urn).split('+')
109
110     ####################
111     # the local fields that are kept consistent
112     # self.urn
113     # self.hrn
114     # self.type
115     # self.path
116     # provide either urn, or (hrn + type)
117     def __init__ (self, xrn, type=None):
118         if not xrn: xrn = ""
119        
120         # user has specified xrn : guess if urn or hrn
121         if xrn.startswith(Xrn.URN_PREFIX):
122             self.hrn=None
123             self.urn=xrn
124             self.urn_to_hrn()
125             #print>>sys.stderr, " \r\n \r\n \t XRN.PY init  xrn.startswith(Xrn.URN_PREFIX) hrn %s urn %s type %s" %(  self.hrn,  self.urn, self.type)
126         else:
127             self.urn=None
128             self.hrn=xrn
129             self.type=type
130             self.hrn_to_urn()
131             #print>>sys.stderr, " \r\n \r\n \t XRN.PY init ELSE hrn %s urn %s type %s" %(  self.hrn,  self.urn, self.type)
132 # happens all the time ..
133 #        if not type:
134 #            debug_logger.debug("type-less Xrn's are not safe")
135
136     def __repr__ (self):
137         result="<XRN u=%s h=%s"%(self.urn,self.hrn)
138         if hasattr(self,'leaf'): result += " leaf=%s"%self.leaf
139         if hasattr(self,'authority'): result += " auth=%s"%self.authority
140         result += ">"
141         return result
142
143     def get_urn(self): return self.urn
144     def get_hrn(self): return self.hrn
145     def get_type(self): return self.type
146     def get_hrn_type(self): return (self.hrn, self.type)
147
148     def _normalize(self):
149         #print>>sys.stderr, " \r\n \r\n \t XRN.PY _normalize self.hrn %s ",self.hrn
150         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
151         if not hasattr(self,'leaf'): 
152             self.leaf=Xrn.hrn_split(self.hrn)[-1]
153         # self.authority keeps a list
154         if not hasattr(self,'authority'): 
155             self.authority=Xrn.hrn_auth_list(self.hrn)
156         #print>>sys.stderr, " \r\n \r\n \t XRN.PY _normalize self.hrn %s leaf %s authority %s"%(self.hrn, self.leaf,  self.authority)
157        
158        
159     def get_leaf(self):
160         self._normalize()
161         return self.leaf
162
163     def get_authority_hrn(self):
164         self._normalize()
165         return '.'.join( self.authority )
166     
167     def get_authority_urn(self): 
168         self._normalize()
169         return ':'.join( [Xrn.unescape(x) for x in self.authority] )
170    
171     def get_sliver_id(self, slice_id, node_id, index=0):
172         self._normalize()
173         return ":".join(map(str, [self.get_urn(), slice_id, node_id, index])) 
174  
175     def urn_to_hrn(self):
176         """
177         compute tuple (hrn, type) from urn
178         """
179         
180 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
181         if not self.urn.startswith(Xrn.URN_PREFIX):
182             raise SfaAPIError, "Xrn.urn_to_hrn"
183
184         parts = Xrn.urn_split(self.urn)
185         type=parts.pop(2)
186         # Remove the authority name (e.g. '.sa')
187         if type == 'authority':
188             name = parts.pop()
189             # Drop the sa. This is a bad hack, but its either this
190             # or completely change how record types are generated/stored   
191             if name != 'sa':
192                 type = type + "+" + name
193             name =""
194         else:
195             name = parts.pop(len(parts)-1)
196         # convert parts (list) into hrn (str) by doing the following
197         # 1. remove blank parts
198         # 2. escape dots inside parts
199         # 3. replace ':' with '.' inside parts
200         # 3. join parts using '.'
201         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part])
202         # dont replace ':' in the name section
203         if name:
204             hrn += '.%s' % Xrn.escape(name) 
205
206         self.hrn=str(hrn)
207         self.type=str(type)
208     
209     def hrn_to_urn(self):
210         """
211         compute urn from (hrn, type)
212         """
213
214 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
215         if self.hrn.startswith(Xrn.URN_PREFIX):
216             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
217
218         if self.type and self.type.startswith('authority'):
219             self.authority = Xrn.hrn_split(self.hrn)
220             type_parts = self.type.split("+")
221             self.type = type_parts[0]
222             name = 'sa'
223             if len(type_parts) > 1:
224                 name = type_parts[1]
225         else:
226             self.authority = Xrn.hrn_auth_list(self.hrn)
227             name = Xrn.hrn_leaf(self.hrn)
228
229         authority_string = self.get_authority_urn()
230
231         if self.type == None:
232             urn = "+".join(['',authority_string,Xrn.unescape(name)])
233         else:
234             urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])
235         
236         self.urn = Xrn.URN_PREFIX + urn
237
238     def dump_string(self):
239         result="-------------------- XRN\n"
240         result += "URN=%s\n"%self.urn
241         result += "HRN=%s\n"%self.hrn
242         result += "TYPE=%s\n"%self.type
243         result += "LEAF=%s\n"%self.get_leaf()
244         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
245         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
246         return result
247