Support for the plc_initscript_id attribute.
[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     'disk_max': 5000000 # bytes
34     }
35
36 start_requested = False  # set to True in order to request that all slivers be started
37
38
39 @database.synchronized
40 def GetSlivers(data, fullupdate=True):
41     """This function has two purposes.  One, convert GetSlivers() data
42     into a more convenient format.  Two, even if no updates are coming
43     in, use the GetSlivers() heartbeat as a cue to scan for expired
44     slivers."""
45
46     node_id = None
47     try:
48         f = open('/etc/planetlab/node_id')
49         try: node_id = int(f.read())
50         finally: f.close()
51     except: logger.log_exc()
52
53     if data.has_key('node_id') and data['node_id'] != node_id: return
54
55     if data.has_key('networks'):
56         for network in data['networks']:
57             if network['is_primary'] and network['bwlimit'] is not None:
58                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
59
60 ### Emulab-specific hack begins here
61     emulabdelegate = {
62         'instantiation': 'plc-instantiated',
63         'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
64         'name': 'utah_elab_delegate',
65         'timestamp': data['timestamp'],
66         'type': 'delegate',
67         'vref': None
68         }
69     database.db.deliver_record(emulabdelegate)
70 ### Emulab-specific hack ends here
71
72
73     initscripts_by_id = {}
74     for is_rec in data['initscripts']:
75         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
76
77     for sliver in data['slivers']:
78         rec = sliver.copy()
79         rec.setdefault('timestamp', data['timestamp'])
80
81         # convert attributes field to a proper dict
82         attr_dict = {}
83         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
84
85         # squash keys
86         keys = rec.pop('keys')
87         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
88
89         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
90         rec.setdefault('vref', attr_dict.get('vref', 'default'))
91         is_id = attr_dict.get('plc_initscript_id')
92         if is_id is not None and is_id in initscripts_by_id:
93             rec['initscript'] = initscripts_by_id[is_id]
94         else:
95             rec['initscript'] = ''
96         rec.setdefault('delegations', [])  # XXX - delegation not yet supported
97
98         # extract the implied rspec
99         rspec = {}
100         rec['rspec'] = rspec
101         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
102             try: amt = int(attr_dict[resname])
103             except (KeyError, ValueError): amt = default_amt
104             rspec[resname] = amt
105         database.db.deliver_record(rec)
106     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
107     database.db.sync()
108
109     # handle requested startup
110     global start_requested
111     if start_requested:
112         start_requested = False
113         cumulative_delay = 0
114         for name in database.db.iterkeys():
115             accounts.get(name).start(delay=cumulative_delay)
116             cumulative_delay += 3
117
118 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
119
120
121 def start(options, config):
122     accounts.register_class(sliver_vs.Sliver_VS)
123     accounts.register_class(delegate.Delegate)
124     global start_requested
125     start_requested = options.startup
126     database.start()
127     api.deliver_ticket = deliver_ticket
128     api.start()