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