source: fedd/federation/topdl.py @ 29d5f7c

compt_changesinfo-ops
Last change on this file since 29d5f7c was 29d5f7c, checked in by Ted Faber <faber@…>, 12 years ago

More new Info stuff. Create, terminate, ftopo all work.

  • Property mode set to 100644
File size: 33.8 KB
RevLine 
[eec716b]1#!/usr/local/bin/python
2
[6c57fe9]3import re
[f9c2f63]4import xml.parsers.expat
[a914b1b]5from xml.sax.saxutils import escape
6from base64 import b64encode
7from string import join
[6c57fe9]8
[da2208a]9from fedid import fedid as fedid_class
10
[eec716b]11class base:
12    @staticmethod
13    def init_class(c, arg):
14        if isinstance(arg, dict):
[df783c1]15            try:
16                return c(**arg)
17            except:
18                print "%s" % arg
19                raise
[eec716b]20        elif isinstance(arg, c):
21            return arg
22        else:
23            return None
24
25    @staticmethod
26    def make_list(a):
27        if isinstance(a, basestring) or isinstance(a, dict): return [ a ]
28        elif getattr(a, '__iter__', None): return a
29        else: return [ a ]
30
[21b5434]31    @staticmethod
32    def init_string(s):
33        """
34        Force a string coercion for everything but a None.
35        """
36        if s is not None: return "%s" % s
37        else: return None
38
[69692a9]39    def remove_attribute(self, key):
40        to_del = None
41        attrs = getattr(self, 'attribute', [])
42        for i, a in enumerate(attrs):
43            if a.attribute == key:
44                to_del = i
45                break
46       
47        if to_del: del attrs[i]
48
[df783c1]49    def get_attribute(self, key):
50        rv = None
[db6b092]51        attrs = getattr(self, 'attribute', None)
[df783c1]52        if attrs:
53            for a in attrs:
54                if a.attribute == key:
55                    rv = a.value
56                    break
57        return rv
58
[6c57fe9]59    def set_attribute(self, key, value):
60        attrs = getattr(self, 'attribute', None)
61        if attrs is None:
62            return
63        for a in attrs:
64            if a.attribute == key: 
65                a.value = value
66                break
67        else:
68            attrs.append(Attribute(key, value))
[eec716b]69
70class ConsistencyError(RuntimeError): pass
[5b74b63]71class NamespaceError(RuntimeError): pass
[eec716b]72
73class Attribute(base):
74    def __init__(self, attribute, value):
[21b5434]75        self.attribute = self.init_string(attribute)
76        self.value = self.init_string(value)
[eec716b]77
[db6b092]78    def clone(self):
79        return Attribute(attribute=self.attribute, value=self.value)
80
[eec716b]81    def to_dict(self):
82        return { 'attribute': self.attribute, 'value': self.value }
[a914b1b]83    def to_xml(self):
84        return "<attribute>%s</attribute><value>%s</value>" % \
85                (escape(self.attribute), escape(self.value))
[eec716b]86
87class Capacity(base):
88    def __init__(self, rate, kind):
[cc8d8e9]89        self.rate = float(rate)
[21b5434]90        self.kind = self.init_string(kind)
[eec716b]91
[db6b092]92    def clone(self):
93        return Capacity(rate=self.rate, kind=self.kind)
94
[eec716b]95    def to_dict(self):
[cc8d8e9]96        return { 'rate': float(self.rate), 'kind': self.kind }
[eec716b]97
[a914b1b]98    def to_xml(self):
99        return "<rate>%f</rate><kind>%s</kind>" % (self.rate, self.kind)
100
[eec716b]101class Latency(base):
102    def __init__(self, time, kind):
[cc8d8e9]103        self.time = float(time)
[21b5434]104        self.kind = self.init_string(kind)
[eec716b]105
[db6b092]106    def clone(self):
107        return Latency(time=self.time, kind=self.kind)
108
[eec716b]109    def to_dict(self):
[cc8d8e9]110        return { 'time': float(self.time), 'kind': self.kind }
[eec716b]111
[a914b1b]112    def to_xml(self):
113        return "<time>%f</time><kind>%s</kind>" % (self.time, self.kind)
114
[f37e9bf]115class ServiceParam(base):
116    def __init__(self, name, type):
117        self.name = self.init_string(name)
118        self.type = self.init_string(type)
119
120    def clone(self):
121        return ServiceParam(self.name. self.type)
122
123    def to_dict(self):
124        return { 'name': name, 'type': type }
125
126    def to_xml(self):
127        return "<name>%s</name><type>%s</type>" % (self.name, self.type)
128
129class Service(base):
130    def __init__(self, name, importer=[], param=[], description=None, 
131            status=None):
132        self.name = self.init_string(name)
133        self.importer = [self.init_string(i) \
134                for i in self.make_list(importer)]
135        self.param = [ self.init_class(ServiceParam, p) \
136                for p in self.make_list(param) ]
137        self.description = self.init_string(description)
138        self.status = self.init_string(status)
139
140    def clone(self):
141        return Service(
142                name=self.name, 
143                importer=[ i for i in self.importer], 
144                param=[p.clone() for p in self.param], 
145                description=self.description,
146                status=self.status)
147
148    def to_dict(self):
149        rv = { }
150        if self.name is not None:
151            rv['name'] = self.name
152        if self.importer:
153            rv['importer'] = [ i for i in self.importer ]
154        if self.param:
155            rv['param'] = [ p.to_dict() for p in self.param ]
156        if self.description is not None:
157            rv['description'] = self.description
158        if self.status is not None:
159            rv['status'] = self.status
160        return rv
161
162    def to_xml(self):
163        rv = '' 
164        if self.name is not None:
165            rv += '<name>%s</name>' % self.name
166        if self.importer:
167            rv += join(['<importer>%s</importer>' % i \
168                    for i in self.importer],'')
169        if self.param:
[29d5f7c]170            rv += join(['<param>%s</param>' % p.to_xml() \
[f37e9bf]171                    for p in self.param], '')
172        if self.description is not None:
173            rv += '<description>%s</description>' % self.description
174        if self.status is not None:
175            rv += '<status>%s</status>' % self.status
176        return rv
177
[eec716b]178class Substrate(base):
[f37e9bf]179    def __init__(self, name, capacity=None, latency=None, attribute=[],
180            localname=[], status=None, service=[], operation=[]):
[21b5434]181        self.name = self.init_string(name)
[eec716b]182        self.capacity = self.init_class(Capacity, capacity)
183        self.latency = self.init_class(Latency, latency)
184        self.attribute = [ self.init_class(Attribute, a) \
185                for a in self.make_list(attribute) ]
[f37e9bf]186        self.localname = [ self.init_string(ln)\
187                for ln in self.make_list(localname) ]
188        self.status = self.init_string(status)
189        self.service = [ self.init_class(Service, s) \
190                for s in self.make_list(service)]
191        self.operation = [self.init_string(op) \
192                for op in self.make_list(operation)]
[eec716b]193        self.interfaces = [ ]
194
[db6b092]195    def clone(self):
196        if self.capacity: c = self.capacity.clone()
197        else: c = None
198
199        if self.latency: l = self.latency.clone()
200        else: l = None
201
202        return Substrate(name=self.name,
203                capacity=c,
204                latency=l,
[f37e9bf]205                attribute = [a.clone() for a in self.attribute],
206                localname = [ ln for ln in self.localname],
207                status = self.status,
[29d5f7c]208                service = [ s.clone() for s in self.service],
209                operation=[ op for op in self.operation])
[db6b092]210
[eec716b]211    def to_dict(self):
212        rv = { 'name': self.name }
213        if self.capacity:
214            rv['capacity'] = self.capacity.to_dict()
215        if self.latency:
216            rv['latency'] = self.latency.to_dict()
217        if self.attribute:
218            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
[f37e9bf]219        if self.localname:
220            rv['localname'] = [ ln for ln in self.localname ]
221        if self.status:
222            rv['status'] = self.status
223        if self.service:
224            rv['service'] = [s.to_dict() for s in self.service]
225        if self.operation:
226            rv['operation'] = [op for op in self.operation]
[eec716b]227        return rv
228
[a914b1b]229    def to_xml(self):
230        rv = "<name>%s</name>" % escape(self.name)
231        if self.capacity is not None:
232            rv += "<capacity>%s</capacity>" % self.capacity.to_xml()
233        if self.latency is not None:
234            rv += "<latency>%s</latency>" % self.latency.to_xml()
235       
236        if self.attribute:
237            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
238                    for a in self.attribute], "")
[f37e9bf]239        if self.localname:
[29d5f7c]240            rv += join(['<localname>%s</localname>' % ln \
[f37e9bf]241                    for ln in self.localname], '')
242        if self.status is not None:
243            rv += '<status>%s</status>' % self.status
244        if self.service:
245            rv += join(['<service>%s</service' % s.to_xml() \
246                    for s in self.service], '')
247        if self.operation:
248            rv += join(['<operation>%s</operation>' % op \
249                    for op in self.operation], '')
[a914b1b]250        return rv
251
[eec716b]252class CPU(base):
253    def __init__(self, type, attribute=[]):
[21b5434]254        self.type = self.init_string(type)
[eec716b]255        self.attribute = [ self.init_class(Attribute, a) for a in \
256                self.make_list(attribute) ]
257
[db6b092]258    def clone(self):
259        return CPU(type=self.type,
260                attribute = [a.clone() for a in self.attribute])
261
[eec716b]262    def to_dict(self):
263        rv = { 'type': self.type}
264        if self.attribute:
265            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
266        return rv
267
[a914b1b]268    def to_xml(self):
269        rv = "<type>%s</type>" % escape(self.type)
270        if self.attribute:
271            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
272                    for a in self.attribute], "")
273        return rv
274
275
[eec716b]276class Storage(base):
277    def __init__(self, amount, persistence, attribute=[]):
[cc8d8e9]278        self.amount = float(amount)
[21b5434]279        self.presistence = self.init_string(persistence)
[eec716b]280        self.attribute = [ self.init_class(Attribute, a) \
281                for a in self.make_list(attribute) ]
282
[db6b092]283    def clone(self):
284        return Storage(amount=self.amount, persistence=self.persistence, 
285                attribute = [a.clone() for a in self.attribute])
286
[eec716b]287    def to_dict(self):
288        rv = { 'amount': float(self.amount), 'persistence': self.persistence }
289        if self.attribute:
290            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
291        return rv
292
[a914b1b]293    def to_xml(self):
294        rv = "<amount>%f</amount><persistence>%s</persistence>" % \
295                (self.amount, escape(self.persistence))
296        if self.attribute:
297            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
298                    for a in self.attribute], "")
299        return rv
300
301
[eec716b]302class OperatingSystem(base):
[df783c1]303    def __init__(self, name=None, version=None, distribution=None,
[eec716b]304            distributionversion=None, attribute=[]):
[21b5434]305        self.name = self.init_string(name)
306        self.version = self.init_string(version)
307        self.distribution = self.init_string(distribution)
308        self.distributionversion = self.init_string(distributionversion)
[eec716b]309        self.attribute = [ self.init_class(Attribute, a) \
310                for a in self.make_list(attribute) ]
311
[db6b092]312    def clone(self):
313        return OperatingSystem(name=self.name,
314                version=self.version,
315                distribution=self.distribution,
316                distributionversion=self.distributionversion,
317                attribute = [ a.clone() for a in self.attribute])
318
[eec716b]319    def to_dict(self):
[df783c1]320        rv = { }
321        if self.name: rv['name'] = self.name
[eec716b]322        if self.version: rv['version'] = self.version
[a914b1b]323        if self.distribution: rv['distribution'] = self.distribution
324        if self.distributionversion: 
325            rv['distributionversion'] = self.distributionversion
[eec716b]326        if self.attribute:
327            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
328        return rv
329
[a914b1b]330    def to_xml(self):
331        rv = ""
332        if self.name: rv += "<name>%s</name>" % escape(self.name)
333        if self.version: rv += "<version>%s</version>" % escape(self.version)
334        if self.distribution: 
335            rv += "<distribution>%s</distribution>" % escape(self.distribution)
336        if self.distributionversion: 
337            rv += "<distributionversion>%s</distributionversion>" % \
338                    escape(self.distributionversion)
339       
340        if self.attribute:
341            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
342                    for a in self.attribute], "")
343        return rv
344
345
[eec716b]346class Software(base):
347    def __init__(self, location, install=None, attribute=[]):
[21b5434]348        self.location = self.init_string(location)
349        self.install = self.init_string(install)
[eec716b]350        self.attribute = [ self.init_class(Attribute, a)\
351                for a in self.make_list(attribute) ]
352
[db6b092]353    def clone(self):
354        return Software(location=self.location, install=self.install, 
355                attribute=[a.clone() for a in self.attribute])
356
[eec716b]357    def to_dict(self):
358        rv = { 'location': self.location }
359        if self.install: rv['install'] = self.install
360        if self.attribute:
361            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
362        return rv
363
[a914b1b]364    def to_xml(self):
365        rv = "<location>%s</location>" % escape(self.location)
366        if self.install: rv += "<install>%s</install>" % self.install
367        if self.attribute:
368            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
369                    for a in self.attribute], "")
370        return rv
371
372
[eec716b]373class Interface(base):
[5b74b63]374    def __init__(self, substrate, name=None, capacity=None, latency=None,
375            attribute=[], element=None):
[21b5434]376        self.name = self.init_string(name)
377
[cdb62d9]378        self.substrate = self.make_list(substrate)
[eec716b]379        self.capacity = self.init_class(Capacity, capacity)
380        self.latency = self.init_class(Latency, latency)
381        self.attribute = [ self.init_class(Attribute, a) \
382                for a in self.make_list(attribute) ]
383        self.element = element
384        self.subs = [ ]
385
[db6b092]386    def clone(self):
387        if self.capacity: c = self.capacity.clone()
388        else: c = None
389
390        if self.latency: l = self.latency.clone()
391        else: l = None
392
[d2471df]393        return Interface(substrate=[s for s in self.substrate], name=self.name,
[db6b092]394                capacity=c, latency=l,
395                attribute = [ a.clone() for a in self.attribute])
396
[eec716b]397    def to_dict(self):
[5b74b63]398        rv = { 'substrate': self.substrate, 'name': self.name }
[eec716b]399        if self.capacity:
400            rv['capacity'] = self.capacity.to_dict()
401        if self.latency:
402            rv['latency'] = self.latency.to_dict()
403        if self.attribute:
404            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
405        return rv
406
[a914b1b]407    def to_xml(self):
408        rv = join(["<substrate>%s</substrate>" % escape(s) \
409                for s in self.substrate], "")
410        rv += "<name>%s</name>" % self.name
411        if self.capacity:
412            rv += "<capacity>%s</capacity>" % self.capacity.to_xml()
413        if self.latency:
414            rv += "<latency>%s</latency>" % self.latency.to_xml()
415        if self.attribute:
416            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
417                    for a in self.attribute], "")
418        return rv
419
420
[6c57fe9]421class ID(base):
422    def __init__(self, fedid=None, uuid=None, uri=None, localname=None,
423            kerberosUsername=None):
[da2208a]424        self.fedid=fedid_class(hexstr="%s" % fedid)
[21b5434]425        self.uuid = self.init_string(uuid)
426        self.uri = self.init_string(uri)
427        self.localname =self.init_string( localname)
428        self.kerberosUsername = self.init_string(kerberosUsername)
[6c57fe9]429
430    def clone(self):
431        return ID(self.fedid, self.uuid, self.uri, self.localname,
[ecca6eb]432                self.kerberosUsername)
[6c57fe9]433
434    def to_dict(self):
435        rv = { }
436        if self.fedid: rv['fedid'] = self.fedid
437        if self.uuid: rv['uuid'] = self.uuid
438        if self.uri: rv['uri'] = self.uri
439        if self.localname: rv['localname'] = self.localname
440        if self.kerberosUsername: rv['kerberosUsername'] = self.kerberosUsername
441        return rv
442
[a914b1b]443    def to_xml(self):
444        if self.uuid: rv = "<uuid>%s</uuid>" % b64encode(self.uuid)
445        elif self.fedid: rv = "<fedid>%s</fedid>" % b64encode(self.fedid)
446        elif self.uri: rv = "<uri>%s</uri>" % escape(self.uri)
447        elif self.localname: 
448            rv = "<localname>%s</localname>" % escape(self.localname)
449        elif self.kerberosUsername: 
450            rv = "<kerberosUsername>%s</kerberosUsername>" % \
451                    escape(self.kerberosUsername)
452        return rv
453
[eec716b]454class Computer(base):
[822fd49]455    def __init__(self, name, cpu=[], os=[], software=[], storage=[],
[f37e9bf]456            interface=[], attribute=[], localname=[], status=None, service=[],
457            operation=[]):
[eec716b]458        def assign_element(i):
459            i.element = self
460
[21b5434]461        self.name = self.init_string(name)
[eec716b]462        self.cpu = [ self.init_class(CPU, c)  for c in self.make_list(cpu) ]
463        self.os = [ self.init_class(OperatingSystem, c) \
464                for c in self.make_list(os) ]
465        self.software = [ self.init_class(Software, c) \
466                for c in self.make_list(software) ]
467        self.storage = [ self.init_class(Storage, c) \
468                for c in self.make_list(storage) ]
469        self.interface = [ self.init_class(Interface, c) \
470                for c in self.make_list(interface) ]
471        self.attribute = [ self.init_class(Attribute, a) \
472                for a in self.make_list(attribute) ]
[f37e9bf]473        self.localname = [ self.init_string(ln)\
474                for ln in self.make_list(localname) ]
475        self.status = self.init_string(status)
476        self.service = [ self.init_class(Service, s) \
477                for s in self.make_list(service)]
478        self.operation = [self.init_string(op) \
479                for op in self.make_list(operation)]
[eec716b]480        map(assign_element, self.interface)
481
[db6b092]482    def clone(self):
[d2471df]483        # Copy the list of names
[1e7f268]484        return Computer(name=self.name,
[db6b092]485                cpu=[x.clone() for x in self.cpu],
486                os=[x.clone() for x in self.os],
487                software=[x.clone() for x in self.software],
488                storage=[x.clone() for x in self.storage],
489                interface=[x.clone() for x in self.interface],
[f37e9bf]490                attribute=[x.clone() for x in self.attribute],
[29d5f7c]491                localname =[ ln for ln in self.localname],
[f37e9bf]492                status = self.status,
493                service = [s.clone() for s in self.service],
494                operation = [op for op in self.operation])
[db6b092]495
[eec716b]496    def to_dict(self):
497        rv = { }
[db6b092]498        if self.name:
[6d7a024]499            rv['name'] = self.name
[eec716b]500        if self.cpu:
501            rv['cpu'] = [ c.to_dict() for  c in self.cpu ]
502        if self.os:
503            rv['os'] = [ o.to_dict() for o in self.os ]
504        if self.software:
505            rv['software'] = [ s.to_dict() for s in self.software ]
506        if self.storage:
507            rv['storage'] = [ s.to_dict for s in self.storage ]
508        if self.interface:
509            rv['interface'] = [ i.to_dict() for i in self.interface ]
510        if self.attribute:
511            rv['attribute'] = [ i.to_dict() for i in self.attribute ]
[f37e9bf]512        if self.localname:
513            rv['localname'] = [ ln for ln in self.localname ]
514        if self.status:
515            rv['status'] = self.status
516        if self.service:
517            rv['service'] = [s.to_dict() for s in self.service]
518        if self.operation:
519            rv['operation'] = [op for op in self.operation]
[cdb62d9]520        return { 'computer': rv }
[eec716b]521
[a914b1b]522    def to_xml(self):
523        rv = "<name>%s</name>" % escape(self.name)
524        if self.cpu:
525            rv += join(["<cpu>%s</cpu>" % c.to_xml() for c in self.cpu], "")
526        if self.os:
527            rv += join(["<os>%s</os>" % o.to_xml() for o in self.os], "")
528        if self.software:
529            rv += join(["<software>%s</software>" % s.to_xml() \
530                    for s in self.software], "")
531        if self.storage:
532            rv += join(["<stroage>%s</stroage>" % s.to_xml() \
533                    for s in self.stroage], "")
534        if self.interface:
535            rv += join(["<interface>%s</interface>" % i.to_xml() 
536                for i in self.interface], "")
537        if self.attribute:
538            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
539                    for a in self.attribute], "")
[f37e9bf]540        if self.localname:
[29d5f7c]541            rv += join(['<localname>%s</localname>' % ln \
[f37e9bf]542                    for ln in self.localname], '')
543        if self.status is not None:
544            rv += '<status>%s</status>' % self.status
545        if self.service:
546            rv += join(['<service>%s</service' % s.to_xml() \
547                    for s in self.service], '')
548        if self.operation:
549            rv += join(['<operation>%s</operation>' % op \
550                    for op in self.operation], '')
[a914b1b]551        return "<computer>%s</computer>" % rv
552
553
[6c57fe9]554
555class Testbed(base):
[f37e9bf]556    def __init__(self, uri, type, interface=[], attribute=[], localname=[],
557            status=None, service=[], operation=[]):
[21b5434]558        self.uri = self.init_string(uri)
559        self.type = self.init_string(type)
[6c57fe9]560        self.interface = [ self.init_class(Interface, c) \
561                for c in self.make_list(interface) ]
562        self.attribute = [ self.init_class(Attribute, c) \
563                for c in self.make_list(attribute) ]
[f37e9bf]564        self.localname = [ self.init_string(ln)\
565                for ln in self.make_list(localname) ]
566        self.status = self.init_string(status)
567        self.service = [ self.init_class(Service, s) \
568                for s in self.make_list(service)]
569        self.operation = [self.init_string(op) \
570                for op in self.make_list(operation)]
[6c57fe9]571
572    def clone(self):
573        return Testbed(self.uri, self.type,
574                interface=[i.clone() for i in self.interface],
[f37e9bf]575                attribute=[a.cone() for a in self.attribute],
576                localname = [ ln for ln in self.localname ],
577                status=self.status,
578                service=[s.clone() for s in self.service ],
579                operation = [ op for op in self.operation ])
[6c57fe9]580
581    def to_dict(self):
582        rv = { }
583        if self.uri: rv['uri'] = self.uri
584        if self.type: rv['type'] = self.type
585        if self.interface:
586            rv['interface'] = [ i.to_dict() for i in self.interface]
587        if self.attribute:
588            rv['attribute'] = [ a.to_dict() for a in self.attribute]
[f37e9bf]589        if self.localname:
590            rv['localname'] = [ ln for ln in self.localname ]
591        if self.status:
592            rv['status'] = self.status
593        if self.service:
594            rv['service'] = [s.to_dict() for s in self.service]
595        if self.operation:
596            rv['operation'] = [op for op in self.operation]
[6c57fe9]597        return { 'testbed': rv }
598
[a914b1b]599    def to_xml(self):
600        rv = "<uri>%s</uri><type>%s</type>" % \
601                (escape(self.uri), escape(self.type))
602        if self.interface:
603            rv += join(["<interface>%s</interface>" % i.to_xml() 
604                for i in self.interface], "")
605        if self.attribute:
606            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
607                    for a in self.attribute], "")
[f37e9bf]608        if self.localname:
[29d5f7c]609            rv += join(['<localname>%s</localname>' % ln \
[f37e9bf]610                    for ln in self.localname], '')
611        if self.status is not None:
612            rv += '<status>%s</status>' % self.status
613        if self.service:
614            rv += join(['<service>%s</service' % s.to_xml() \
615                    for s in self.service], '')
616        if self.operation:
617            rv += join(['<operation>%s</operation>' % op \
618                    for op in self.operation], '')
[a914b1b]619        return "<testbed>%s</testbed>" % rv
620
621       
622
[6c57fe9]623class Segment(base):
624    def __init__(self, id, type, uri, interface=[], attribute=[]):
625        self.id = self.init_class(ID, id)
[21b5434]626        self.type = self.init_string(type)
627        self.uri = self.init_string(uri)
[6c57fe9]628        self.interface = [ self.init_class(Interface, c) \
629                for c in self.make_list(interface) ]
630        self.attribute = [ self.init_class(Attribute, c) \
631                for c in self.make_list(attribute) ]
632
633    def clone(self):
634        return Segment(self.id.clone(), self.type, self.uri, 
635                interface=[i.clone() for i in self.interface], 
[ecca6eb]636                attribute=[a.clone() for a in self.attribute])
[6c57fe9]637
638    def to_dict(self):
639        rv = { }
640        if self.id: rv['id'] = self.id.to_dict()
641        if self.type: rv['type'] = self.type
642        if self.uri: rv['uri'] = self.uri
643        if self.interface:
644            rv['interface'] = [ i.to_dict() for i in self.interface ]
645        if self.attribute:
646            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
647        return { 'segment': rv }
648
[a914b1b]649    def to_xml(self):
650        rv = "<id>%s</id><uri>%s</uri><type>%s</type>" % \
651                (id.to_xml(), escape(self.uri), escape(self.type))
652        if self.interface:
653            rv += join(["<interface>%s</interface>" % i.to_xml() 
654                for i in self.interface], "")
655        if self.attribute:
656            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
657                    for a in self.attribute], "")
658        return "<segment>%s</segment>" % rv
[6c57fe9]659
[eec716b]660class Other(base):
661    def __init__(self, interface=[], attribute=[]):
662        self.interface = [ self.init_class(Interface, c) \
663                for c in self.make_list(interface) ]
664        self.attribute = [ self.init_class(Attribute, c) \
665                for c in self.make_list(attribute) ]
666
[db6b092]667    def clone(self):
668        return Other(interface=[i.clone() for i in self.interface], 
669                attribute=[a.clone() for a in attribute])
670
[eec716b]671    def to_dict(self):
[6c57fe9]672        rv = {}
[eec716b]673        if self.interface:
674            rv['interface'] = [ i.to_dict() for i in self.interface ]
675        if self.attribute:
676            rv['attribute'] = [ a.to_dict() for a in self.attribute ]
[6c57fe9]677        return {'other': rv }
[eec716b]678
[a914b1b]679    def to_xml(self):
680        rv = ""
681        if self.interface:
682            rv += join(["<interface>%s</interface>" % i.to_xml() 
683                for i in self.interface], "")
684        if self.attribute:
685            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
686                    for a in self.attribute], "")
687        return "<other>%s</other>" % rv
[eec716b]688
689class Topology(base):
[d69ce97]690    version = "1.0"
[eec716b]691    @staticmethod
692    def init_element(e):
693        """
694        e should be of the form { typename: args } where args is a dict full of
695        the right parameters to initialize the element.  e should have only one
696        key, but we walk e's keys in an arbitrary order and instantiate the
697        first key we know how to.
698        """
699        classmap = {
700                'computer': Computer,
[6c57fe9]701                'testbed': Testbed,
702                'segment': Segment,
[eec716b]703                'other': Other,
704            }
705
[db6b092]706        if isinstance(e, dict):
707            for k in e.keys():
708                cl = classmap.get(k, None)
709                if cl: return cl(**e[k])
710        else:
711            return e
[eec716b]712
[d69ce97]713    def __init__(self, substrates=[], elements=[], attribute=[], 
714            version=None):
715
716        if version is None: self.version = Topology.version
717        else: self.version = version
718
[eec716b]719        self.substrates = [ self.init_class(Substrate, s) \
720                for s in self.make_list(substrates) ]
721        self.elements = [ self.init_element(e) \
722                for e in self.make_list(elements) ]
[69692a9]723        self.attribute = [ self.init_class(Attribute, c) \
724                for c in self.make_list(attribute) ]
[db6b092]725        self.incorporate_elements()
726
[5b74b63]727    @staticmethod
728    def name_element_interfaces(e):
729        names = set([i.name for i in e.interface if i.name])
730        inum = 0
731        for i in [ i for i in e.interface if not i.name]:
732            while inum < 1000:
733                n = "inf%03d" % inum
734                inum += 1
735                if n not in names:
736                    i.name = n
737                    break
738            else:
739                raise NamespaceError("Cannot make new interface name")
740
741
742
743    def name_interfaces(self):
744        """
745        For any interface without a name attribute, assign a unique one within
746        its element.
747        """
748
749        for e in self.elements:
750            self.name_element_interfaces(e)
751
752
[db6b092]753    def incorporate_elements(self):
754
[eec716b]755        # Could to this init in one gulp, but we want to look for duplicate
756        # substrate names
757        substrate_map = { }
758        for s in self.substrates:
[db6b092]759            s.interfaces = [ ]
[eec716b]760            if not substrate_map.has_key(s.name):
761                substrate_map[s.name] = s
762            else:
763                raise ConsistencyError("Duplicate substrate name %s" % s.name)
764
765        for e in self.elements:
[5b74b63]766            self.name_element_interfaces(e)
[eec716b]767            for i in e.interface:
[db6b092]768                i.element = e
769                i.subs = [ ]
[eec716b]770                for sn in i.substrate:
771                    # NB, interfaces have substrate names in their substrate
772                    # attribute.
773                    if substrate_map.has_key(sn):
774                        sub = substrate_map[sn]
775                        i.subs.append(sub)
776                        sub.interfaces.append(i)
777                    else:
778                        raise ConsistencyError("No such substrate for %s" % sn)
779
[db6b092]780    def clone(self):
781        return Topology(substrates=[s.clone() for s in self.substrates], 
[69692a9]782                elements=[e.clone() for e in self.elements],
[d69ce97]783                attribute=[a.clone() for a in self.attribute],
784                version=self.version)
[db6b092]785
786
787    def make_indices(self):
788        sub_index = dict([(s.name, s) for s in self.substrates])
789        elem_index = dict([(n, e) for e in self.elements for n in e.name])
790
[eec716b]791    def to_dict(self):
792        rv = { }
[d69ce97]793        rv['version'] = self.version
[eec716b]794        if self.substrates:
795            rv['substrates'] = [ s.to_dict() for s in self.substrates ]
796        if self.elements:
797            rv['elements'] = [ s.to_dict() for s in self.elements ]
[69692a9]798        if self.attribute:
799            rv['attribute'] = [ s.to_dict() for s in self.attribute]
[eec716b]800        return rv
801
[a914b1b]802    def to_xml(self):
[d69ce97]803        rv = "<version>%s</version>" % escape(self.version)
[a914b1b]804        if self.substrates:
805            rv += join(["<substrates>%s</substrates>" % s.to_xml() \
806                    for s in self.substrates], "")
807        if self.elements:
808            rv += join(["<elements>%s</elements>" % e.to_xml() \
809                    for e in self.elements], "")
810        if self.attribute:
811            rv += join(["<attribute>%s</attribute>" % a.to_xml() \
812                    for a in self.attribute], "")
813        return rv
814
815
[db6b092]816def topology_from_xml(string=None, file=None, filename=None, top="topology"):
[eec716b]817    class parser:
[f1550c8]818        def __init__(self, top):
[eec716b]819            self.stack = [ ]
820            self.chars = ""
821            self.key = ""
822            self.have_chars = False
823            self.current = { }
824            self.in_cdata = False
[f1550c8]825            self.in_top = False
826            self.top = top
[eec716b]827       
828        def start_element(self, name, attrs):
829            self.chars = ""
830            self.have_chars = False
831            self.key = str(name)
[f1550c8]832
833            if name == self.top:
834                self.in_top = True
835
836            if self.in_top:
837                self.stack.append((self.current, self.key))
838                self.current = { }
[eec716b]839
840        def end_element(self, name):
[f1550c8]841            if self.in_top:
842                if self.have_chars:
843                    self.chars = self.chars.strip()
844                    if len(self.chars) >0:
845                        addit = self.chars
846                    else:
847                        addit = self.current
[eec716b]848                else:
849                    addit = self.current
850
[f1550c8]851                parent, key = self.stack.pop()
852                if parent.has_key(key):
853                    if isinstance(parent[key], list):
854                        parent[key].append(addit)
855                    else:
856                        parent[key] = [parent[key], addit]
[eec716b]857                else:
[f1550c8]858                    parent[key] = addit
859                self.current = parent
860                self.key = key
[eec716b]861
862            self.chars = ""
863            self.have_chars = False
864
[f1550c8]865            if name == self.top:
866                self.in_top= False
867
[eec716b]868        def char_data(self, data):
[f1550c8]869            if self.in_top:
870                self.have_chars = True
871                self.chars += data
[eec716b]872
[f1550c8]873    p = parser(top=top)
[eec716b]874    xp = xml.parsers.expat.ParserCreate()
875
876    xp.StartElementHandler = p.start_element
877    xp.EndElementHandler = p.end_element
878    xp.CharacterDataHandler = p.char_data
879
[db6b092]880    num_set = len([ x for x in (string, filename, file)\
881            if x is not None ])
882
883    if num_set != 1:
884        raise RuntimeError("Exactly one one of file, filename and string " + \
885                "must be set")
886    elif filename:
887        f = open(filename, "r")
[df783c1]888        xp.ParseFile(f)
[cc8d8e9]889        f.close()
[db6b092]890    elif file:
891        xp.ParseFile(file)
[df783c1]892    elif string:
893        xp.Parse(string, isfinal=True)
894    else:
895        return None
[eec716b]896
897    return Topology(**p.current[top])
898
[9252414]899def topology_from_startsegment(req):
900    """
901    Generate a topology from a StartSegment request to an access controller.
902    This is a little helper to avoid some gross looking syntax.  It accepts
903    either a request enclosed in the StartSegmentRequestBody, or one with that
904    outer dict removed.
905    """
906
907    if 'StartSegmentRequestBody' in req: r = req['StartSegmentRequestBody']
908    else: r = req
909   
910    if 'segmentdescription' in r and \
911            'topdldescription' in r['segmentdescription']:
912        return Topology(**r['segmentdescription']['topdldescription'])
913    else:
914        return None
915
[eec716b]916def topology_to_xml(t, top=None):
917    """
[a914b1b]918    Print the topology as XML, recursively using the internal classes to_xml()
919    methods.
[eec716b]920    """
921
[a914b1b]922    if top: return "<%s>%s</%s>" % (top, t.to_xml(), top)
923    else: return t.to_xml()
[eec716b]924
[db6b092]925def topology_to_vtopo(t):
926    nodes = [ ]
927    lans = [ ]
[eec716b]928
[db6b092]929    for eidx, e in enumerate(t.elements):
[4a53c72]930        if e.name: name = e.name
[db6b092]931        else: name = "unnamed_node%d" % eidx
932       
933        ips = [ ]
[cc8d8e9]934        for idx, i in enumerate(e.interface):
[db6b092]935            ip = i.get_attribute('ip4_address')
936            ips.append(ip)
937            port = "%s:%d" % (name, idx)
938            for idx, s in enumerate(i.subs):
939                bw = 100000
940                delay = 0.0
941                if s.capacity:
942                    bw = s.capacity.rate
943                if i.capacity:
944                    bw = i.capacity.rate
945
946                if s.latency:
947                    delay = s.latency.time
948                if i.latency:
949                    bw = i.latency.time
950
951                lans.append({
952                    'member': port,
953                    'vname': s.name,
954                    'ip': ip,
955                    'vnode': name,
956                    'delay': delay,
957                    'bandwidth': bw,
958                    })
959        nodes.append({
960            'ips': ":".join(ips),
961            'vname': name,
962            })
963
[cc8d8e9]964    return { 'node': nodes, 'lan': lans }
965
[6c57fe9]966def to_tcl_name(n):
[8483f24]967    t = re.sub('-(\d+)', '(\\1)', n)
[6c57fe9]968    return t
969
[69692a9]970def generate_portal_command_filter(cmd, add_filter=None):
[ecca6eb]971    def rv(e):
972        s =""
973        if isinstance(e, Computer):
974            gw = e.get_attribute('portal')
[69692a9]975            if add_filter and callable(add_filter):
976                add = add_filter(e)
977            else:
978                add = True
979            if gw and add:
[1e7f268]980                s = "%s ${%s}\n" % (cmd, to_tcl_name(e.name))
[ecca6eb]981        return s
982    return rv
983
[6c57fe9]984def generate_portal_image_filter(image):
985    def rv(e):
986        s =""
987        if isinstance(e, Computer):
988            gw = e.get_attribute('portal')
989            if gw:
[1e7f268]990                s = "tb-set-node-os ${%s} %s\n" % (to_tcl_name(e.name), image)
[6c57fe9]991        return s
992    return rv
993
[ecca6eb]994def generate_portal_hardware_filter(type):
[6c57fe9]995    def rv(e):
996        s =""
997        if isinstance(e, Computer):
998            gw = e.get_attribute('portal')
999            if gw:
[1e7f268]1000                s = "tb-set-hardware ${%s} %s\n" % (to_tcl_name(e.name), type)
[6c57fe9]1001        return s
1002    return rv
1003
1004
[d46b1d5]1005def topology_to_ns2(t, filters=[], routing="Manual"):
[cc8d8e9]1006    out = """
1007set ns [new Simulator]
1008source tb_compat.tcl
1009
1010"""
[6c57fe9]1011
[cc8d8e9]1012    for e in t.elements:
1013        rpms = ""
1014        tarfiles = ""
1015        if isinstance(e, Computer):
[1e7f268]1016            name = to_tcl_name(e.name)
[cc8d8e9]1017            out += "set %s [$ns node]\n" % name
1018            if e.os and len(e.os) == 1:
1019                osid = e.os[0].get_attribute('osid')
1020                if osid:
[d46b1d5]1021                    out += "tb-set-node-os ${%s} %s\n" % (name, osid)
[ecca6eb]1022            hw = e.get_attribute('type')
1023            if hw:
[d46b1d5]1024                out += "tb-set-hardware ${%s} %s\n" % (name, hw)
[cc8d8e9]1025            for s in e.software:
1026                if s.install:
1027                    tarfiles += "%s %s " % (s.install, s.location)
1028                else:
1029                    rpms += "%s " % s.location
1030            if rpms:
[d46b1d5]1031                out += "tb-set-node-rpms ${%s} %s\n" % (name, rpms)
[cc8d8e9]1032            if tarfiles:
[d46b1d5]1033                out += "tb-set-node-tarfiles ${%s} %s\n" % (name, tarfiles)
[cc8d8e9]1034            startcmd = e.get_attribute('startup')
1035            if startcmd:
[d46b1d5]1036                out+= 'tb-set-node-startcmd ${%s} "%s"\n' % (name, startcmd)
[6c57fe9]1037            for f in filters:
1038                out += f(e)
[cc8d8e9]1039            out+= "\n"
1040   
1041    for idx, s in enumerate(t.substrates):
1042        loss = s.get_attribute('loss')
[df3179c]1043        if s.latency: delay = s.latency.time
1044        else: delay = 0
1045
1046        if s.capacity: rate = s.capacity.rate
1047        else: rate = 100000
[6c57fe9]1048        name = to_tcl_name(s.name or "sub%d" % idx)
[cc8d8e9]1049
1050        if len(s.interfaces) > 2:
1051            # Lan
[4a53c72]1052            members = [ to_tcl_name("${%s}") % i.element.name \
[6c57fe9]1053                    for i in s.interfaces]
1054            out += 'set %s [$ns make-lan "%s" %fkb %fms ]\n' % \
[5767b20]1055                    (name, " ".join([to_tcl_name(m) for m in members]),
1056                            rate, delay)
[cc8d8e9]1057            if loss:
[d46b1d5]1058                "tb-set-lan-loss ${%s} %f\n" % (name, float(loss))
[cc8d8e9]1059
1060            for i in s.interfaces:
1061                e = i.element
[1da6a23]1062                ip = i.get_attribute("ip4_address")
[cc8d8e9]1063                if ip:
[d46b1d5]1064                    out += "tb-set-ip-lan ${%s} ${%s} %s\n" % \
[4a53c72]1065                            (to_tcl_name(e.name), name, ip)
[df3179c]1066                if i.capacity and i.capacity.rate != rate:
[d46b1d5]1067                    out += "tb-set-node-lan-bandwidth ${%s} ${%s} %fkb\n" % \
[4a53c72]1068                            (to_tcl_name(e.name), name, i.capacity.rate)
[cc8d8e9]1069                if i.latency and i.latency.time != delay:
[d46b1d5]1070                    out += "tb-set-node-lan-delay ${%s} ${%s} %fms\n" % \
[4a53c72]1071                            (to_tcl_name(e.name), name, i.latency.time)
[cc8d8e9]1072                iloss = i.get_attribute('loss')
1073                if loss and iloss != loss :
[d46b1d5]1074                    out += "tb-set-node-lan-loss ${%s} ${%s} %f\n" % \
[4a53c72]1075                            (to_tcl_name(e.name), name, float(loss))
[cc8d8e9]1076            out+= "\n"
1077        elif len(s.interfaces) == 2:
1078            f = s.interfaces[0]
1079            t = s.interfaces[1]
1080
[d46b1d5]1081            out += "set %s [$ns duplex-link ${%s} ${%s} %fkb %fms DropTail]\n" %\
[4a53c72]1082                    (name, to_tcl_name(f.element.name), 
[df3179c]1083                            to_tcl_name(t.element.name), rate, delay)
[cc8d8e9]1084            if loss:
[d46b1d5]1085                out += "tb-set-link-loss ${%s} %f\n" % (name, float(loss))
[cc8d8e9]1086
1087            for i in s.interfaces:
1088                lloss = i.get_attribute("loss")
1089                cap_override = i.capacity and \
[df3179c]1090                        i.capacity.rate != rate
[cc8d8e9]1091                delay_override = i.latency and \
1092                        i.latency.time != delay
1093                loss_override = lloss and lloss != loss
1094                if cap_override or delay_override or loss_override:
1095                    if i.capacity: cap = i.capacity.rate
[df3179c]1096                    else: cap = rate
[cc8d8e9]1097
1098                    if i.latency: delay = i.latency.time
1099
1100                    if lloss: loss = lloss
1101                    else: loss = loss or 0.0
1102
[d46b1d5]1103                    out += "tb-set-link-simplex-params ${%s} ${%s} %fms %fkb %f\n"\
[4a53c72]1104                            % (name, to_tcl_name(i.element.name),
[6c57fe9]1105                                    delay, cap, loss)
[1da6a23]1106                ip = i.get_attribute('ip4_address')
1107                if ip:
[d46b1d5]1108                    out += "tb-set-ip-link ${%s} ${%s} %s\n" % \
[4a53c72]1109                            (to_tcl_name(i.element.name), name, ip)
[cc8d8e9]1110            out+= "\n"
[6c57fe9]1111        for f in filters:
1112            out+= f(s)
[1da6a23]1113    out+="$ns rtproto %s" % routing
[cc8d8e9]1114    out+="""
1115$ns run
1116"""
1117    return out
[2fdf4b3]1118
1119def topology_to_rspec(t, filters=[]):
1120    out = '<?xml version="1.0" encoding="UTF-8"?>\n' + \
1121        '<rspec xmlns="http://www.protogeni.net/resources/rspec/0.1"\n' + \
1122        '\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n' + \
1123        '\txsi:schemaLocation="http://www.protogeni.net/resources/rspec/0.1 '+ \
1124        'http://www.protogeni.net/resources/rspec/0.1/request.xsd"\n' + \
1125        '\ttype="request" >\n'
1126
1127    ifname = { }
1128    ifnode = { }
1129
1130    for e in [e for e in t.elements if isinstance(e, Computer)]:
[1e7f268]1131        name = e.name
[2fdf4b3]1132        virt_type = e.get_attribute("virtualization_type") or "emulab-vnode"
1133        exclusive = e.get_attribute("exclusive") or "1"
1134        hw = e.get_attribute("type") or "pc";
1135        slots = e.get_attribute("slots") or "1";
1136        startup = e.get_attribute("startup")
1137
1138        extras = ""
1139        if startup: extras += '\t\tstartup_command="%s"\n' % startup
1140        out += '\t<node virtual_id="%s"\n\t\tvirtualization_type="%s"\n' % \
1141                (name, virt_type)
1142        out += '\t\texclusive="%s"' % exclusive
1143        if extras: out += '\n%s' % extras
1144        out += '>\n'
1145        out += '\t\t<node_type type_name="%s" slots="%s"/>\n' % (hw, slots)
1146        for i, ii in enumerate(e.interface):
[5b74b63]1147            out += '\t\t<interface virtual_id="%s"/>\n' % ii.name
[2fdf4b3]1148            ifnode[ii] = name
1149        for f in filters:
[8aaf8f8]1150            out += f(e)
[2fdf4b3]1151        out += '\t</node>\n'
1152
1153    for i, s in enumerate(t.substrates):
[f81aba7]1154        if len(s.interfaces) == 0: 
1155            continue
1156        out += '\t<link virtual_id="%s" link_type="ethernet">\n' % s.name
[2fdf4b3]1157        if s.capacity and s.capacity.kind == "max":
[f81aba7]1158            bwout = True
1159            out += '\t\t<bandwidth>%d</bandwidth>\n' % s.capacity.rate
1160        else:
1161            bwout = False
[2fdf4b3]1162        if s.latency and s.latency.kind == "max":
[f81aba7]1163            out += '\t\t<latency>%d</latency>\n' % s.latency.time
1164        elif bwout:
1165            out += '\t\t<latency>0</latency>\n'
[2fdf4b3]1166        for ii in s.interfaces:
[6d07908]1167            out += ('\t\t<interface_ref virtual_node_id="%s" ' + \
[5b74b63]1168                    'virtual_interface_id="%s"/>\n') % (ifnode[ii], ii.name)
[2fdf4b3]1169        for f in filters:
1170            out += f(s)
1171        out += '\t</link>\n'
1172    out += '</rspec>\n'
1173    return out
1174
Note: See TracBrowser for help on using the repository browser.