PL utilities, useful for experiment designers
[nepi.git] / src / nepi / testbeds / planetlab / util.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from constants import TESTBED_ID, TESTBED_VERSION
5 from nepi.core import testbed_impl
6 from nepi.core.metadata import Parallel
7 from nepi.util.constants import TIME_NOW
8 from nepi.util.graphtools import mst
9 from nepi.util import ipaddr2
10 from nepi.util import environ
11 from nepi.util.parallel import ParallelRun
12 import sys
13 import os
14 import os.path
15 import time
16 import resourcealloc
17 import collections
18 import operator
19 import functools
20 import socket
21 import struct
22 import tempfile
23 import subprocess
24 import random
25 import shutil
26 import logging
27 import metadata
28 import weakref
29
30 def getAPI(user, pass_):
31     import plcapi
32     return plcapi.PLCAPI(username=user, password=pass_)
33
34 def getNodes(api, num, **constraints):
35     # Now do the backtracking search for a suitable solution
36     # First with existing slice nodes
37     reqs = []
38     nodes = []
39     
40     import node as Node
41         
42     for i in xrange(num):
43         node = Node.Node(api)
44         node.min_num_external_interface = 1
45         nodes.append(node)
46     
47     node = nodes[0]
48     candidates = node.find_candidates()
49     reqs = [candidates] * num
50
51     def pickbest(fullset, nreq, node=nodes[0]):
52         if len(fullset) > nreq:
53             fullset = zip(node.rate_nodes(fullset),fullset)
54             fullset.sort(reverse=True)
55             del fullset[nreq:]
56             return set(map(operator.itemgetter(1),fullset))
57         else:
58             return fullset
59     
60     solution = resourcealloc.alloc(reqs, sample=pickbest)
61     
62     # Do assign nodes
63     for node, node_id in zip(nodes, solution):
64         node.assign_node_id(node_id)
65     
66     return nodes
67
68 def getSpanningTree(nodes, root = None, maxbranching = 2, hostgetter = operator.attrgetter('hostname')):
69     if not root:
70         # Pick root (deterministically)
71         root = min(nodes, key=hostgetter)
72     
73     # Obtain all IPs in numeric format
74     # (which means faster distance computations)
75     for node in nodes:
76         node._ip = socket.gethostbyname(hostgetter(node))
77         node._ip_n = struct.unpack('!L', socket.inet_aton(node._ip))[0]
78     
79     # Compute plan
80     # NOTE: the plan is an iterator
81     plan = mst.mst(
82         nodes,
83         lambda a,b : ipaddr2.ipdistn(a._ip_n, b._ip_n),
84         root = root,
85         maxbranching = maxbranching)
86
87     return plan
88