Generates linkspecs and ifspecs from the topology list.
[nodemanager-topo.git] / create-topo-attributes.py
1 # $Id$
2 # $URL$
3
4 """
5 Scan the VINI Central database and create topology "rspec" attributes for
6 slices that have an EGRE key.  This script to be run from a cron job.
7 """
8
9 import string
10 import socket
11 import sys
12 import optparse
13
14 parser = optparse.OptionParser()
15 parser.add_option('-l', '--linkspec', action='store', dest='genlinkspec', default=False, help='Generate linkspec dict.')
16 (options, args) = parser.parse_args()
17
18 """
19 Links in the physical topology, gleaned from looking at the Internet2
20 and NLR topology maps.  Link (a, b) connects sites with IDs a and b.
21 """
22 links = [(2, 12),  # I2 Princeton - New York 
23          (4, 5),   # NLR Chicago - Houston
24          (4, 6),   # NLR Chicago - Atlanta
25          (4, 7),   # NLR Chicago - Seattle
26          (4, 9),   # NLR Chicago - New York
27          (4, 10),  # NLR Chicago - Wash DC
28          (5, 6),   # NLR Houston - Atlanta
29          (5, 8),   # NLR Houston - Los Angeles
30          (6, 10),  # NLR Atlanta - Wash DC
31          (7, 8),   # NLR Seattle - Los Angeles
32          (9, 10),  # NLR New York - Wash DC
33          (11, 13), # I2 Chicago - Wash DC
34          (11, 15), # I2 Chicago - Atlanta
35          (11, 16), # I2 Chicago - CESNET
36          (11, 17), # I2 Chicago - Kansas City
37          (12, 13), # I2 New York - Wash DC
38          (13, 15), # I2 Wash DC - Atlanta
39          (15, 19), # I2 Atlanta - Houston
40          (17, 19), # I2 Kansas City - Houston
41          (17, 22), # I2 Kansas City - Salt Lake City
42          (19, 20), # I2 Houston - Los Angeles
43          (20, 21), # I2 Los Angeles - Seattle
44          (20, 22), # I2 Los Angeles - Salt Lake City
45          (21, 22)] # I2 Seattle - Salt Lake City
46
47
48 def gen_adjacencies(links):
49     """
50     Generate site adjacency map from list of links
51     """
52     adj = {}
53     for (a, b) in links:
54         if a in adj:
55             adj[a].append(b)
56         else:
57             adj[a] = [a, b]
58         if b in adj:
59             adj[b].append(a)
60         else:
61             adj[b] = [b, a]
62     return adj
63
64
65 def is_adjacent(adjacencies, s1, s2):
66     """
67     Test whether two sites are adjacent to each other in the adjacency graph.
68     """
69     set1 = set(adjacencies[s1])
70     set2 = set(adjacencies[s2])
71
72     if s1 in set2 and s2 in set1:
73         return True
74     elif not s1 in set2 and not s2 in set1:
75         return False
76     else:
77         raise Exception("Adjacency mismatch, sites %d and %d." % (s1, s2))
78
79
80 def check_adjacencies(adjacencies):
81     """
82     Check the adjacency graph for discrepancies.
83     """
84     for site in adjacencies:
85         for adj in adjacencies[site]:
86             try:
87                 test = is_adjacent(adjacencies, site, adj)
88             except Exception, e:
89                 print "Error: ", e, " Fix adjacencies!"
90     return
91
92
93 def get_site(nodeid):
94     if nodes[nodeid]:
95         return nodes[nodeid]['site_id']
96     raise Exception("Nodeid %s not found." % nodeid)
97
98
99 def get_ipaddr(nodeid):
100     if nodes[nodeid]:
101         return socket.gethostbyname(nodes[nodeid]['hostname'])
102     raise Exception("Nodeid %s not found." % nodeid)
103
104
105 def get_sitenodes(siteid):
106     if sites[siteid]:
107         return sites[siteid]['node_ids']
108     raise Exception("Siteid %s not found." % siteid)
109
110
111 def get_virt_ip(myid, nodeid):
112     """
113     Find the IP address assigned to a virtual interface in the topology
114     (for creating /etc/hosts)
115     """
116     if myid < nodeid:
117         virtip = "10.%d.%d.2" % (myid, nodeid)
118     else:
119         virtip = "10.%d.%d.3" % (nodeid, myid)
120     return virtip
121
122
123 def get_sites():
124     """
125     Create a dictionary of site records keyed by site ID
126     """
127     tmp = []
128     for site in GetSites():
129         t = site['site_id'], site
130         tmp.append(t)
131     return dict(tmp)
132
133
134 def get_nodes():
135     """
136     Create a dictionary of node records keyed by node ID
137     """
138     tmp = []
139     for node in GetNodes():
140         t = node['node_id'], node
141         tmp.append(t)
142     return dict(tmp)
143
144
145 def toDict(a,b):
146     """
147     Return dict with keys from [a] w/ vals from [b]
148     """
149     if len(a) == len(b):
150         c = {}
151         for i in range(0,len(a)):
152             c[a[i]] = b[i]
153     else: 
154         except Exception("Length error.")
155     return c
156
157
158 def ifSpecDict(nodedict):
159     """
160     Generate ifspec dict for given node dict.
161     """
162     ifspecattrs = ['name',
163                 'addr',
164                 'type', 
165                 'init_params', 
166                 'bw', 
167                 'min_alloc', 
168                 'max_alloc', 
169                 'ip_spoof']
170     ifspecs= []
171     nodenetworks = GetNodeNetworks(nodedict['nodenetwork_ids'])
172     # some nodes have more than 1 public interface.
173     for nodenetwork in nodenetworks:
174         ifspecs.append( toDict(ifspecattrs,
175                                 [nodenetwork['hostname'],
176                                 nodenetwork['ip'],
177                                 nodenetwork['type'],
178                                 None, '0', '1Gbps', False]))
179     return ifspecs
180
181
182 def linkSpecDict():
183     """
184     Create dict for physical topology.
185     """
186     # list of attributes in the LinkSpec 
187     # (https://svn.planet-lab.org/svn/geniwrapper/trunk/rspec/model/planetlab.{ecore,xsd})
188     linkspecattrs = ['type', 
189                 'init_params', 
190                 'bw', 
191                 'min_alloc', 
192                 'max_alloc', 
193                 'endpoint', # <-- ifspec(S)?
194                 'start_time', 
195                 'duration']
196     nodes = get_nodes
197     for (i, j) in links:
198        ifSpecDict(nodes[i]) 
199
200
201 adjacencies = gen_adjacencies(links)    
202 check_adjacencies(adjacencies)
203     
204 """ Need global topology information """
205 sites = get_sites()
206 nodes = get_nodes()
207         
208
209 def main():
210    
211     for slice in GetSlices():
212         """ Create dictionary of the slice's attributes """
213         attrs ={}
214         topo_attr = {}
215         for attribute in GetSliceAttributes(slice['slice_attribute_ids']):
216             attrs[attribute['name']] = attribute['slice_attribute_id']
217             if attribute['name'] == 'topo_rspec' and attribute['node_id']:
218                 topo_attr[attribute['node_id']] = attribute['slice_attribute_id']
219                 
220         if 'egre_key' in attrs:
221             #print "Virtual topology for %s:" % slice['name']
222             slicenodes = set(slice['node_ids'])
223             hosts = "127.0.0.1\t\tlocalhost\n"
224             """
225             For each node in the slice, check whether nodes at adjacent sites
226             are also in the slice's node set.  If so, add a virtual link to 
227             the rspec.  
228             """
229             for node in slicenodes:
230                 topo = []
231                 for adj in adjacencies[get_site(node)]:
232                     for adj_node in get_sitenodes(adj):
233                         if node != adj_node and adj_node in slicenodes:
234                             link = adj_node, get_ipaddr(adj_node), "1Mbit"
235                             topo.append(link)
236                             shortname = nodes[node]['hostname'].replace('.vini-veritas.net', '')
237                             hosts += "%s\t\t%s\n" % (get_virt_ip(node, adj_node),
238                                                       shortname)
239                 topo_str = "%s" % topo
240                 #print node, topo_str
241                 if node in topo_attr:
242                     UpdateSliceAttribute(topo_attr[node], topo_str)
243                     del topo_attr[node]
244                 else:
245                     id = slice['slice_id']
246                     AddSliceAttribute(id, 'topo_rspec', topo_str, node)
247     
248             #print hosts
249             if 'hosts' in attrs:
250                 UpdateSliceAttribute(attrs['hosts'], hosts)
251             else:
252                 id = slice['slice_id']
253                 AddSliceAttribute(id, 'hosts', hosts)
254         #else:
255             #print "No EGRE key for %s" % slice['name']
256     
257         """ Remove old topo_rspec entries """
258         for node in topo_attr:
259             DeleteSliceAttribute(topo_attr[node])
260     
261    
262
263 if __name__ == '__main__':
264     if options.genlinkspec: linkspec()
265     else: main()
266
267