c166400ef06a34ee7e825dd4217093701d34772a
[sfa.git] / sfa / util / xrn.py
1 import re
2
3 from sfa.util.faults import *
4
5 # for convenience and smoother translation - we should get rid of these functions eventually 
6 def get_leaf(hrn): return Xrn(hrn).get_leaf()
7 def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
8 def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
9 def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn
10
11 def urn_to_sliver_id(urn, slice_id, node_id, index=0):
12     urn = urn.replace('+slice+', '+sliver+')    
13     return ":".join([urn, str(slice_id), str(node_id), str(index)])
14
15 class Xrn:
16
17     ########## basic tools on HRNs
18     # split a HRN-like string into pieces
19     # this is like split('.') except for escaped (backslashed) dots
20     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
21     @staticmethod
22     def hrn_split(hrn):
23         return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]
24
25     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
26     @staticmethod
27     def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]
28
29     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
30     @staticmethod
31     def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]
32     
33     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
34     @staticmethod
35     def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))
36     
37     # e.g. escape ('a.b') -> 'a\.b'
38     @staticmethod
39     def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)
40     # e.g. unescape ('a\.b') -> 'a.b'
41     @staticmethod
42     def unescape(token): return token.replace('\\.','.')
43         
44     URN_PREFIX = "urn:publicid:IDN"
45
46     ########## basic tools on URNs
47     @staticmethod
48     def urn_full (urn):
49         if urn.startswith(Xrn.URN_PREFIX): return urn
50         else: return Xrn.URN_PREFIX+URN
51     @staticmethod
52     def urn_meaningful (urn):
53         if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]
54         else: return urn
55     @staticmethod
56     def urn_split (urn):
57         return Xrn.urn_meaningful(urn).split('+')
58
59     ####################
60     # the local fields that are kept consistent
61     # self.urn
62     # self.hrn
63     # self.type
64     # self.path
65     # provide either urn, or (hrn + type)
66     def __init__ (self, xrn, type=None):
67         if not xrn: xrn = ""
68         # user has specified xrn : guess if urn or hrn
69         if xrn.startswith(Xrn.URN_PREFIX):
70             self.hrn=None
71             self.urn=xrn
72             self.urn_to_hrn()
73         else:
74             self.urn=None
75             self.hrn=xrn
76             self.type=type
77             self.hrn_to_urn()
78 # happens all the time ..
79 #        if not type:
80 #            debug_logger.debug("type-less Xrn's are not safe")
81
82     def get_urn(self): return self.urn
83     def get_hrn(self): return self.hrn
84     def get_type(self): return self.type
85     def get_hrn_type(self): return (self.hrn, self.type)
86
87     def _normalize(self):
88         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
89         if not hasattr(self,'leaf'): 
90             self.leaf=Xrn.hrn_split(self.hrn)[-1]
91         # self.authority keeps a list
92         if not hasattr(self,'authority'): 
93             self.authority=Xrn.hrn_auth_list(self.hrn)
94
95     def get_leaf(self):
96         self._normalize()
97         return self.leaf
98
99     def get_authority_hrn(self): 
100         self._normalize()
101         return '.'.join( self.authority )
102     
103     def get_authority_urn(self): 
104         self._normalize()
105         return ':'.join( [Xrn.unescape(x) for x in self.authority] )
106     
107     def urn_to_hrn(self):
108         """
109         compute tuple (hrn, type) from urn
110         """
111         
112 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
113         if not self.urn.startswith(Xrn.URN_PREFIX):
114             raise SfaAPIError, "Xrn.urn_to_hrn"
115
116         parts = Xrn.urn_split(self.urn)
117         type=parts.pop(2)
118         # Remove the authority name (e.g. '.sa')
119         if type == 'authority':
120             name = parts.pop()
121             # Drop the sa. This is a bad hack, but its either this
122             # or completely change how record types are generated/stored   
123             if name != 'sa':
124                 type = type + "+" + name
125
126         # convert parts (list) into hrn (str) by doing the following
127         # 1. remove blank parts
128         # 2. escape dots inside parts
129         # 3. replace ':' with '.' inside parts
130         # 3. join parts using '.' 
131         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) 
132
133         self.hrn=str(hrn)
134         self.type=str(type)
135     
136     def hrn_to_urn(self):
137         """
138         compute urn from (hrn, type)
139         """
140
141 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
142         if self.hrn.startswith(Xrn.URN_PREFIX):
143             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
144
145         if self.type and self.type.startswith('authority'):
146             self.authority = Xrn.hrn_split(self.hrn)
147             type_parts = self.type.split("+")
148             self.type = type_parts[0]
149             name = 'sa'
150             if len(type_parts) > 1:
151                 name = type_parts[1]
152         else:
153             self.authority = Xrn.hrn_auth_list(self.hrn)
154             name = Xrn.hrn_leaf(self.hrn)
155
156         authority_string = self.get_authority_urn()
157
158         if self.type == None:
159             urn = "+".join(['',authority_string,Xrn.unescape(name)])
160         else:
161             urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])
162         
163         self.urn = Xrn.URN_PREFIX + urn
164
165     def dump_string(self):
166         result="-------------------- XRN\n"
167         result += "URN=%s\n"%self.urn
168         result += "HRN=%s\n"%self.hrn
169         result += "TYPE=%s\n"%self.type
170         result += "LEAF=%s\n"%self.get_leaf()
171         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
172         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
173         return result
174