| 622 | |
| 623 | == Annotating A Topology == |
| 624 | |
| 625 | The first step in out transformation is to take a topology and add attributes that will be used by other applications. In our example, the other applications will be further refinements in the same program. |
| 626 | |
| 627 | Here is a function that walks a topology, determines the degree of each computer, and adds an [TopdlLibrary#AttributeClass attribute] to each computer with that attribute in it. It demostrates editing a topology using the [TopdlLibrary#TopdlClassFeatures set_attribute] function common to topdl classes. |
| 628 | |
| 629 | {{{ |
| 630 | def annotate_degree(top): |
| 631 | ''' |
| 632 | Add an attribute (node_degree) to each Computer in the topology (top) that |
| 633 | lists its degree |
| 634 | ''' |
| 635 | for e in top.elements: |
| 636 | # Skip elements that are not computers |
| 637 | if not isinstance(e, topdl.Computer): continue |
| 638 | # degree is the number of interfaces |
| 639 | deg = len(e.interface) |
| 640 | # Save a string-valued attribute |
| 641 | e.set_attribute('node_degree', '%s' % deg) |
| 642 | return top |
| 643 | }}} |
| 644 | |
| 645 | == Adding Other Classes == |
| 646 | |
| 647 | This function takes a topology that has been through the {{{annotate_degree}}} function above and adds an [TopdlLibrary#OperatingSystemClass OperatingSystem nested object] to each Computer in the topology, based on the {{{node_degree}}} attribute. This demonstrates adding a nested object directly, rather rthan through [TopdlLibrary#TopdlClassFeatures set_attribute]. |
| 648 | |
| 649 | {{{ |
| 650 | def add_operating_system(top): |
| 651 | ''' |
| 652 | Add an OperatingSystem class to each computer in the topology (top). If |
| 653 | the node is a leaf (degree 1) make it Ubuntu Linux, otherwise make it |
| 654 | FreeBSD. annotate_degree() must have been called on the topology as this |
| 655 | routine uses the node_degree attribute to make decisions. |
| 656 | ''' |
| 657 | |
| 658 | for e in top.elements: |
| 659 | # Skip non-Computers |
| 660 | if not isinstance(e, topdl.Computer): continue |
| 661 | a = e.get_attribute('node_degree') |
| 662 | # if there is a node_degree attribute, assign an OS |
| 663 | if a: |
| 664 | # Covnert the string attribute into an integer |
| 665 | try: |
| 666 | deg = int(a) |
| 667 | except ValueError, e: |
| 668 | sys.exit('%s has a non-integer degree %s!?' % (e.name, a)) |
| 669 | # Assign the os - includes a distribution for Linux |
| 670 | if deg == 1: |
| 671 | e.os.append(topdl.OperatingSystem(name='Linux', |
| 672 | distribution='Ubuntu')) |
| 673 | else: |
| 674 | e.os.append(topdl.OperatingSystem(name='FreeBSD')) |
| 675 | return top |
| 676 | |
| 677 | }}} |