Added ReCreate. Also added try catch to api eval of rpc method.
[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.12.2.5 2007/07/20 19:44:11 faiyaza 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
45     # NOTE: this table is further populated with resource names and
46     # default amounts via the start() function below.  This probably
47     # should be changeg and these values should be obtained via the
48     # API to myplc.
49     }
50
51 start_requested = False  # set to True in order to request that all slivers be started
52
53 @database.synchronized
54 def GetSlivers(data, fullupdate=True):
55     """This function has two purposes.  One, convert GetSlivers() data
56     into a more convenient format.  Two, even if no updates are coming
57     in, use the GetSlivers() heartbeat as a cue to scan for expired
58     slivers."""
59
60     node_id = None
61     try:
62         f = open('/etc/planetlab/node_id')
63         try: node_id = int(f.read())
64         finally: f.close()
65     except: logger.log_exc()
66
67     if data.has_key('node_id') and data['node_id'] != node_id: return
68
69     if data.has_key('networks'):
70         for network in data['networks']:
71             if network['is_primary'] and network['bwlimit'] is not None:
72                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
73
74 ### Emulab-specific hack begins here
75 #    emulabdelegate = {
76 #        'instantiation': 'plc-instantiated',
77 #        'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
78  #       'name': 'utah_elab_delegate',
79  #       'timestamp': data['timestamp'],
80  #       'type': 'delegate',
81  #       'vref': None
82  #       }
83  #   database.db.deliver_record(emulabdelegate)
84 ### Emulab-specific hack ends here
85
86
87     initscripts_by_id = {}
88     for is_rec in data['initscripts']:
89         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
90    
91     for sliver in data['slivers']:
92         rec = sliver.copy()
93         rec.setdefault('timestamp', data['timestamp'])
94
95         # convert attributes field to a proper dict
96         attr_dict = {}
97         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
98
99         # squash keys
100         keys = rec.pop('keys')
101         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
102
103         # Handle nm controller here
104         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
105         if rec['instantiation'] == 'nm-controller':
106         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
107         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
108             rec['type'] = 'delegate'
109
110         rec.setdefault('vref', attr_dict.get('vref', 'default'))
111         is_id = attr_dict.get('plc_initscript_id')
112         if is_id is not None and is_id in initscripts_by_id:
113             rec['initscript'] = initscripts_by_id[is_id]
114         else:
115             rec['initscript'] = ''
116         rec.setdefault('delegations', attr_dict.get("delegations", []))
117
118         # extract the implied rspec
119         rspec = {}
120         rec['rspec'] = rspec
121         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
122             try: amt = int(attr_dict[resname])
123             except KeyError: amt = default_amt
124             except ValueError:
125                 if type(default_amt) is type('str'):
126                     amt = attr_dict[resname]
127                 else:
128                     amt = default_amt
129             rspec[resname] = amt
130
131         database.db.deliver_record(rec)
132     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
133     database.db.sync()
134     accounts.Startingup = False
135
136 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
137
138
139 def start(options, config):
140     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
141         DEFAULT_ALLOCATION[resname]=default_amt
142         
143     accounts.register_class(sliver_vs.Sliver_VS)
144     accounts.register_class(delegate.Delegate)
145     accounts.Startingup = options.startup
146     database.start()
147     api.deliver_ticket = deliver_ticket
148     api.start()