Uses rspec to calculate bwlimits. Respects sirius loans. Also uses min defaults...
[nodemanager.git] / sm.py
1 """Sliver manager.
2
3 The sliver manager has several functions.  It is responsible for
4 creating, resource limiting, starting, stopping, and destroying
5 slivers.  It provides an API for users to access these functions and
6 also to make inter-sliver resource loans.  The sliver manager is also
7 responsible for handling delegation accounts.
8 """
9
10 try: from bwlimit import bwmin, bwmax
11 except ImportError: bwmin, bwmax = 8, 1000*1000*1000
12 import accounts
13 import api
14 import database
15 import delegate
16 import logger
17 import sliver_vs
18
19
20 DEFAULT_ALLOCATION = {
21     'enabled': 1,
22     # CPU parameters
23     'cpu_min': 0, # ms/s
24     'cpu_share': 32, # proportional share
25     # bandwidth parameters
26     'net_min_rate': bwmin / 1000, # kbps
27     'net_max_rate': bwmax / 1000, # kbps
28     'net_share': 1, # proportional share
29     # bandwidth parameters over routes exempt from node bandwidth limits
30     'net_i2_min_rate': bwmin / 1000, # kbps
31     'net_i2_max_rate': bwmax / 1000, # kbps
32     'net_i2_share': 1, # proportional share
33     'net_max_kbyte' : 5662310, #Kbyte
34     'net_thresh_kbyte': 4529848, #Kbyte
35     'net_i2_max_kbyte': 17196646,
36     'net_i2_thresh_kbyte': 13757316,
37     'disk_max': 5000000 # bytes
38     }
39
40 start_requested = False  # set to True in order to request that all slivers be started
41
42
43 @database.synchronized
44 def GetSlivers(data, fullupdate=True):
45     """This function has two purposes.  One, convert GetSlivers() data
46     into a more convenient format.  Two, even if no updates are coming
47     in, use the GetSlivers() heartbeat as a cue to scan for expired
48     slivers."""
49
50     node_id = None
51     try:
52         f = open('/etc/planetlab/node_id')
53         try: node_id = int(f.read())
54         finally: f.close()
55     except: logger.log_exc()
56
57     if data.has_key('node_id') and data['node_id'] != node_id: return
58
59     if data.has_key('networks'):
60         for network in data['networks']:
61             if network['is_primary'] and network['bwlimit'] is not None:
62                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
63
64 ### Emulab-specific hack begins here
65     emulabdelegate = {
66         'instantiation': 'plc-instantiated',
67         'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
68         'name': 'utah_elab_delegate',
69         'timestamp': data['timestamp'],
70         'type': 'delegate',
71         'vref': None
72         }
73     database.db.deliver_record(emulabdelegate)
74 ### Emulab-specific hack ends here
75
76
77     initscripts_by_id = {}
78     for is_rec in data['initscripts']:
79         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
80
81     for sliver in data['slivers']:
82         rec = sliver.copy()
83         rec.setdefault('timestamp', data['timestamp'])
84
85         # convert attributes field to a proper dict
86         attr_dict = {}
87         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
88
89         # squash keys
90         keys = rec.pop('keys')
91         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
92
93         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
94         rec.setdefault('vref', attr_dict.get('vref', 'default'))
95         is_id = attr_dict.get('plc_initscript_id')
96         if is_id is not None and is_id in initscripts_by_id:
97             rec['initscript'] = initscripts_by_id[is_id]
98         else:
99             rec['initscript'] = ''
100         rec.setdefault('delegations', [])  # XXX - delegation not yet supported
101
102         # extract the implied rspec
103         rspec = {}
104         rec['rspec'] = rspec
105         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
106             try: amt = int(attr_dict[resname])
107             except (KeyError, ValueError): amt = default_amt
108             rspec[resname] = amt
109         database.db.deliver_record(rec)
110     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
111     database.db.sync()
112
113     # handle requested startup
114     global start_requested
115     if start_requested:
116         start_requested = False
117         cumulative_delay = 0
118         for name in database.db.iterkeys():
119             accounts.get(name).start(delay=cumulative_delay)
120             cumulative_delay += 3
121
122 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
123
124
125 def start(options, config):
126     accounts.register_class(sliver_vs.Sliver_VS)
127     accounts.register_class(delegate.Delegate)
128     global start_requested
129     start_requested = options.startup
130     database.start()
131     api.deliver_ticket = deliver_ticket
132     api.start()