svn kwds
[nodemanager.git] / slivermanager.py
1 #
2 """Sliver manager.
3
4 The sliver manager has several functions.  It is responsible for
5 creating, resource limiting, starting, stopping, and destroying
6 slivers.  It provides an API for users to access these functions and
7 also to make inter-sliver resource loans.  The sliver manager is also
8 responsible for handling delegation accounts.
9 """
10
11 import string,re
12 import time
13
14 import logger
15 import api, api_calls
16 import database
17 import accounts
18 import controller
19 import sliver_vs
20
21 try: from bwlimit import bwmin, bwmax
22 except ImportError: bwmin, bwmax = 8, 1000*1000*1000
23
24 priority=10
25
26
27 DEFAULT_ALLOCATION = {
28     'enabled': 1,
29     # CPU parameters
30     'cpu_pct': 0, # percent CPU reserved
31     'cpu_share': 1, # proportional share
32     # bandwidth parameters
33     'net_min_rate': bwmin / 1000, # kbps
34     'net_max_rate': bwmax / 1000, # kbps
35     'net_share': 1, # proportional share
36     # bandwidth parameters over routes exempt from node bandwidth limits
37     'net_i2_min_rate': bwmin / 1000, # kbps
38     'net_i2_max_rate': bwmax / 1000, # kbps
39     'net_i2_share': 1, # proportional share
40     'net_max_kbyte' : 10546875, #Kbyte
41     'net_thresh_kbyte': 9492187, #Kbyte
42     'net_i2_max_kbyte': 31640625,
43     'net_i2_thresh_kbyte': 28476562,
44     # disk space limit
45     'disk_max': 10000000, # bytes
46     # capabilities
47     'capabilities': '',
48     # IP addresses
49     'ip_addresses': '0.0.0.0',
50
51     # NOTE: this table is further populated with resource names and
52     # default amounts via the start() function below.  This probably
53     # should be changeg and these values should be obtained via the
54     # API to myplc.
55     }
56
57 start_requested = False  # set to True in order to request that all slivers be started
58
59 # check leases and adjust the 'reservation_alive' field in slivers
60 # this is not expected to be saved as it will change for the next round
61 def adjustReservedSlivers (data):
62     """
63     On reservable nodes, tweak the 'reservation_alive' field to instruct cyclic loop
64     about what to do with slivers.
65     """
66     # only impacts reservable nodes
67     if 'reservation_policy' not in data: return
68     policy=data['reservation_policy'] 
69     if policy not in ['lease_or_idle', 'lease_or_shared']:
70         logger.log ("unexpected reservation_policy %(policy)s"%locals())
71         return
72
73     logger.log("slivermanager.adjustReservedSlivers")
74     now=int(time.time())
75     # scan leases that are expected to show in ascending order
76     active_lease=None
77     for lease in data['leases']:
78         if lease['t_from'] <= now and now <= lease['t_until']:
79             active_lease=lease
80             break
81
82     def is_system_sliver (sliver):
83         for d in sliver['attributes']:
84             if d['tagname']=='system' and d['value']:
85                 return True
86         return False
87
88     # mark slivers as appropriate
89     for sliver in data['slivers']:
90         # system slivers must be kept alive
91         if is_system_sliver(sliver):
92             sliver['reservation_alive']=True
93             continue
94         
95         # regular slivers
96         if not active_lease:
97             # with 'idle_or_shared', just let the field out, behave like a shared node
98             # otherwise, mark all slivers as being turned down
99             if policy == 'lease_or_idle':
100                 sliver['reservation_alive']=False
101         else:
102             # there is an active lease, mark it alive and the other not
103             sliver['reservation_alive'] = sliver['name']==active_lease['name']
104
105 @database.synchronized
106 def GetSlivers(data, config = None, plc=None, fullupdate=True):
107     """This function has two purposes.  One, convert GetSlivers() data
108     into a more convenient format.  Two, even if no updates are coming
109     in, use the GetSlivers() heartbeat as a cue to scan for expired
110     slivers."""
111
112     logger.verbose("slivermanager: Entering GetSlivers with fullupdate=%r"%fullupdate)
113     for key in data.keys():
114         logger.verbose('slivermanager: GetSlivers key : ' + key)
115
116     node_id = None
117     try:
118         f = open('/etc/planetlab/node_id')
119         try: node_id = int(f.read())
120         finally: f.close()
121     except: logger.log_exc("slivermanager: GetSlivers failed to read /etc/planetlab/node_id")
122
123     if data.has_key('node_id') and data['node_id'] != node_id: return
124
125     if data.has_key('networks'):
126         for network in data['networks']:
127             if network['is_primary'] and network['bwlimit'] is not None:
128                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
129
130     # Take initscripts (global) returned by API, make dict
131     if 'initscripts' not in data:
132         logger.log_missing_data("slivermanager.GetSlivers",'initscripts')
133         return
134     initscripts = {}
135     for is_rec in data['initscripts']:
136         logger.verbose("slivermanager: initscript: %s" % is_rec['name'])
137         initscripts[str(is_rec['name'])] = is_rec['script']
138
139     adjustReservedSlivers (data)
140     for sliver in data['slivers']:
141         logger.verbose("slivermanager: %s: slivermanager.GetSlivers in slivers loop"%sliver['name'])
142         rec = sliver.copy()
143         rec.setdefault('timestamp', data['timestamp'])
144
145         # convert attributes field to a proper dict
146         attributes = {}
147         for attr in rec.pop('attributes'): attributes[attr['tagname']] = attr['value']
148         rec.setdefault("attributes", attributes)
149
150         # squash keys
151         keys = rec.pop('keys')
152         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
153
154         ## 'Type' isn't returned by GetSlivers() for whatever reason.  We're overloading
155         ## instantiation here, but i suppose its the same thing when you think about it. -FA
156         # Handle nm-controller here
157         if rec['instantiation'].lower() == 'nm-controller':
158             rec.setdefault('type', attributes.get('type', 'controller.Controller'))
159         else:
160             rec.setdefault('type', attributes.get('type', 'sliver.VServer'))
161
162         # set the vserver reference.  If none, set to default.
163         rec.setdefault('vref', attributes.get('vref', 'default'))
164
165         # set initscripts.  first check if exists, if not, leave empty.
166         is_name = attributes.get('initscript')
167         if is_name is not None and is_name in initscripts:
168             rec['initscript'] = initscripts[is_name]
169         else:
170             rec['initscript'] = ''
171
172         # set delegations, if none, set empty
173         rec.setdefault('delegations', attributes.get("delegations", []))
174
175         # extract the implied rspec
176         rspec = {}
177         rec['rspec'] = rspec
178         for resname, default_amount in DEFAULT_ALLOCATION.iteritems():
179             try:
180                 t = type(default_amount)
181                 amt = t.__new__(t, attributes[resname])
182             except (KeyError, ValueError): amt = default_amount
183             rspec[resname] = amt
184
185         # add in sysctl attributes into the rspec
186         for key in attributes.keys():
187             if key.find("sysctl.") == 0:
188                 rspec[key] = attributes[key]
189
190         database.db.deliver_record(rec)
191     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
192     # slivers are created here.
193     database.db.sync()
194
195 def deliver_ticket(data):
196     return GetSlivers(data, fullupdate=False)
197
198 def start():
199     for resname, default_amount in sliver_vs.DEFAULT_ALLOCATION.iteritems():
200         DEFAULT_ALLOCATION[resname]=default_amount
201
202     accounts.register_class(sliver_vs.Sliver_VS)
203     accounts.register_class(controller.Controller)
204     database.start()
205     api_calls.deliver_ticket = deliver_ticket
206     api.start()