abbcaec9f484618c5109f3345714f93618e8d387
[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_pct': 0, # percent CPU reserved
27     'cpu_share': 1, # 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     logger.verbose("Entering sm:GetSlivers with fullupdate=%r"%fullupdate)
63     for key in data.keys():
64         logger.verbose('GetSlivers key : ' + key)
65
66     node_id = None
67     try:
68         f = open('/etc/planetlab/node_id')
69         try: node_id = int(f.read())
70         finally: f.close()
71     except: logger.log_exc()
72
73     if data.has_key('node_id') and data['node_id'] != node_id: return
74
75     if data.has_key('networks'):
76         for network in data['networks']:
77             if network['is_primary'] and network['bwlimit'] is not None:
78                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
79
80     # Take intscripts (global) returned by API, make dict
81     initscripts = {}
82     for is_rec in data['initscripts']:
83         logger.verbose("initscript: %s" % is_rec['name'])
84         initscripts[str(is_rec['name'])] = is_rec['script']
85
86     for sliver in data['slivers']:
87         logger.verbose("sm:GetSlivers in slivers loop")
88         rec = sliver.copy()
89         rec.setdefault('timestamp', data['timestamp'])
90
91         # convert attributes field to a proper dict
92         attr_dict = {}
93         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
94
95         # squash keys
96         keys = rec.pop('keys')
97         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
98
99         # Handle nm controller here
100         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
101         if rec['instantiation'] == 'nm-controller':
102         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
103         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
104             rec['type'] = 'delegate'
105
106         # set the vserver reference.  If none, set to default.
107         rec.setdefault('vref', attr_dict.get('vref', 'default'))
108
109         # set initscripts.  first check if exists, if not, leave empty.
110         is_name = attr_dict.get('initscript')
111         if is_name is not None and is_name in initscripts:
112             rec['initscript'] = initscripts[is_name]
113         else:
114             rec['initscript'] = ''
115
116         # set delegations, if none, set empty
117         rec.setdefault('delegations', attr_dict.get("delegations", []))
118
119         # extract the implied rspec
120         rspec = {}
121         rec['rspec'] = rspec
122         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
123             try:
124                 t = type(default_amt)
125                 amt = t.__new__(t, attr_dict[resname])
126             except (KeyError, ValueError): amt = default_amt
127             rspec[resname] = amt
128
129         database.db.deliver_record(rec)
130     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
131     database.db.sync()
132     accounts.Startingup = False
133
134 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
135
136
137 def start(options, config):
138     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
139         DEFAULT_ALLOCATION[resname]=default_amt
140         
141     accounts.register_class(sliver_vs.Sliver_VS)
142     accounts.register_class(delegate.Delegate)
143     accounts.Startingup = options.startup
144     database.start()
145     api.deliver_ticket = deliver_ticket
146     api.start()