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