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