df79c523507efa2c9f266ed3d8d140db45ddceb1
[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 # $Id: sm.py,v 1.28 2007/07/27 18:02:36 dhozac Exp $
11
12 try: from bwlimit import bwmin, bwmax
13 except ImportError: bwmin, bwmax = 8, 1000*1000*1000
14 import accounts
15 import api
16 import database
17 import delegate
18 import logger
19 import sliver_vs
20 import string,re
21
22
23 DEFAULT_ALLOCATION = {
24     'enabled': 1,
25     # CPU parameters
26     'cpu_min': 0, # ms/s
27     'cpu_share': 32, # proportional share
28     # bandwidth parameters
29     'net_min_rate': bwmin / 1000, # kbps
30     'net_max_rate': bwmax / 1000, # kbps
31     'net_share': 1, # proportional share
32     # bandwidth parameters over routes exempt from node bandwidth limits
33     'net_i2_min_rate': bwmin / 1000, # kbps
34     'net_i2_max_rate': bwmax / 1000, # kbps
35     'net_i2_share': 1, # proportional share
36     'net_max_kbyte' : 5662310, #Kbyte
37     'net_thresh_kbyte': 4529848, #Kbyte
38     'net_i2_max_kbyte': 17196646,
39     'net_i2_thresh_kbyte': 13757316,
40     # disk space limit
41     'disk_max': 5000000, # bytes
42     # capabilities
43     'capabilities': '',
44     # IP addresses
45     'ip_addresses': '0.0.0.0',
46
47     # NOTE: this table is further populated with resource names and
48     # default amounts via the start() function below.  This probably
49     # should be changeg and these values should be obtained via the
50     # API to myplc.
51     }
52
53 start_requested = False  # set to True in order to request that all slivers be started
54
55 @database.synchronized
56 def GetSlivers(data, fullupdate=True):
57     """This function has two purposes.  One, convert GetSlivers() data
58     into a more convenient format.  Two, even if no updates are coming
59     in, use the GetSlivers() heartbeat as a cue to scan for expired
60     slivers."""
61
62     node_id = None
63     try:
64         f = open('/etc/planetlab/node_id')
65         try: node_id = int(f.read())
66         finally: f.close()
67     except: logger.log_exc()
68
69     if data.has_key('node_id') and data['node_id'] != node_id: return
70
71     if data.has_key('networks'):
72         for network in data['networks']:
73             if network['is_primary'] and network['bwlimit'] is not None:
74                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
75
76 ### Emulab-specific hack begins here
77 #    emulabdelegate = {
78 #        'instantiation': 'plc-instantiated',
79 #        'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
80  #       'name': 'utah_elab_delegate',
81  #       'timestamp': data['timestamp'],
82  #       'type': 'delegate',
83  #       'vref': None
84  #       }
85  #   database.db.deliver_record(emulabdelegate)
86 ### Emulab-specific hack ends here
87
88
89     initscripts_by_id = {}
90     for is_rec in data['initscripts']:
91         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
92
93     for sliver in data['slivers']:
94         rec = sliver.copy()
95         rec.setdefault('timestamp', data['timestamp'])
96
97         # convert attributes field to a proper dict
98         attr_dict = {}
99         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
100
101         # squash keys
102         keys = rec.pop('keys')
103         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
104
105         # Handle nm controller here
106         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
107         if rec['instantiation'] == 'nm-controller':
108         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
109         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
110             rec['type'] = 'delegate'
111
112         rec.setdefault('vref', attr_dict.get('vref', 'default'))
113         is_id = attr_dict.get('plc_initscript_id')
114         if is_id is not None and is_id in initscripts_by_id:
115             rec['initscript'] = initscripts_by_id[is_id]
116         else:
117             rec['initscript'] = ''
118         rec.setdefault('delegations', attr_dict.get("delegations", []))
119
120         # extract the implied rspec
121         rspec = {}
122         rec['rspec'] = rspec
123         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
124             try:
125                 t = type(default_amt)
126                 amt = t.__new__(t, attr_dict[resname])
127             except (KeyError, ValueError): amt = default_amt
128             rspec[resname] = amt
129
130         database.db.deliver_record(rec)
131     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
132     database.db.sync()
133     accounts.Startingup = False
134
135 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
136
137
138 def start(options, config):
139     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
140         DEFAULT_ALLOCATION[resname]=default_amt
141         
142     accounts.register_class(sliver_vs.Sliver_VS)
143     accounts.register_class(delegate.Delegate)
144     accounts.Startingup = options.startup
145     database.start()
146     api.deliver_ticket = deliver_ticket
147     api.start()