merging with geni-api branch
[sfa.git] / sfa / util / namespace.py
1 ### $Id$
2 ### $URL$
3
4 from sfa.util.faults import *
5
6 URN_PREFIX = "urn:publicid:IDN"
7
8 def get_leaf(hrn):
9     parts = hrn.split(".")
10     return ".".join(parts[-1:])
11
12 def get_authority(xrn):
13     hrn, type = urn_to_hrn(xrn)
14     if type and type == 'authority':
15         return hrn
16     
17     parts = hrn.split(".")
18     return ".".join(parts[:-1])
19
20 def hrn_to_pl_slicename(hrn):
21     parts = hrn.split(".")
22     return parts[-2] + "_" + parts[-1]
23
24 # assuming hrn is the hrn of an authority, return the plc authority name
25 def hrn_to_pl_authname(hrn):
26     parts = hrn.split(".")
27     return parts[-1]
28
29 # assuming hrn is the hrn of an authority, return the plc login_base
30 def hrn_to_pl_login_base(hrn):
31     return hrn_to_pl_authname(hrn)
32
33 def hostname_to_hrn(auth_hrn, login_base, hostname):
34     """
35     Convert hrn to plantelab name.
36     """
37     sfa_hostname = ".".join([auth_hrn, login_base, hostname.split(".")[0]])
38     return sfa_hostname
39
40 def slicename_to_hrn(auth_hrn, slicename):
41     """
42     Convert hrn to planetlab name.
43     """
44     parts = slicename.split("_")
45     slice_hrn = ".".join([auth_hrn, parts[0]]) + "." + "_".join(parts[1:])
46
47     return slice_hrn
48
49 def email_to_hrn(auth_hrn, email):
50     parts = email.split("@")
51     username = parts[0]
52     username = username.replace(".", "_").replace("+", "_") 
53     person_hrn = ".".join([auth_hrn, username])
54     
55     return person_hrn 
56
57 def urn_to_hrn(urn):
58     """
59     convert a urn to hrn
60     return a tuple (hrn, type)
61     """
62
63     # if this is already a hrn dont do anything
64     if not urn or not urn.startswith(URN_PREFIX):
65         return urn, None
66
67     name = urn[len(URN_PREFIX):]
68     hrn_parts = name.split("+")
69     
70     # type is always the second to last element in the list
71     type = hrn_parts.pop(-2)
72
73     # convert hrn_parts (list) into hrn (str) by doing the following    
74     # remove blank elements
75     # replace ':' with '.'
76     # join list elements using '.'
77     hrn = '.'.join([part.replace(':', '.') for part in hrn_parts if part]) 
78    
79     return str(hrn), str(type) 
80     
81     
82 def hrn_to_urn(hrn, type=None):
83     """
84     convert an hrn and type to a urn string
85     """
86     # if  this is already a urn dont do anything 
87     if not hrn or hrn.startswith(URN_PREFIX):
88         return hrn
89
90     authority = get_authority(hrn)
91     name = get_leaf(hrn)
92     
93     if authority.startswith("plc"):
94         if type == None:
95             urn = "+".join(['',authority.replace('.',':'),name])
96         else:
97             urn = "+".join(['',authority.replace('.',':'),type,name])
98
99     else:
100         urn = "+".join(['',authority,type,name])
101         
102     return URN_PREFIX + urn