Cut out unneeded stuff
[nodemanager.git] / slivermanager.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 import string,re
11 import time
12
13 import logger
14 import api, api_calls
15 import database
16 import account
17 import controller
18
19 try:
20     import sliver_lxc
21     implementation='lxc'
22     sliver_default_type='sliver.LXC'
23     sliver_class_to_register = sliver_lxc.Sliver_LXC
24     sliver_password_shell = sliver_lxc.Sliver_LXC.SHELL
25 except:
26     import sliver_vs
27     implementation='vs'
28     sliver_default_type='sliver.VServer'
29     sliver_class_to_register = sliver_vs.Sliver_VS
30     sliver_password_shell = sliver_vs.Sliver_VS.SHELL
31
32 # just being safe
33 try : from plnode.bwlimit import bwmin, bwmax
34 except: bwmin, bwmax = 8, 1000*1000*1000
35
36 priority=10
37
38
39 DEFAULT_ALLOCATION = {
40     'enabled': 1,
41     # CPU parameters
42     'cpu_pct': 0, # percent CPU reserved
43     'cpu_share': 1, # proportional share
44     'cpu_cores': "0b", # reserved cpu cores <num_cores>[b]
45     'cpu_freezable': 0, # freeze processes if cpu_cores is 0
46     # bandwidth parameters
47     'net_min_rate': bwmin / 1000, # kbps
48     'net_max_rate': bwmax / 1000, # kbps
49     'net_share': 1, # proportional share
50     # bandwidth parameters over routes exempt from node bandwidth limits
51     'net_i2_min_rate': bwmin / 1000, # kbps
52     'net_i2_max_rate': bwmax / 1000, # kbps
53     'net_i2_share': 1, # proportional share
54     'net_max_kbyte' : 10546875, #Kbyte
55     'net_thresh_kbyte': 9492187, #Kbyte
56     'net_i2_max_kbyte': 31640625,
57     'net_i2_thresh_kbyte': 28476562,
58     # disk space limit
59     'disk_max': 10000000, # bytes
60     # capabilities
61     'capabilities': '',
62     # IP addresses
63     'ip_addresses': '0.0.0.0',
64
65     # NOTE: this table is further populated with resource names and
66     # default amounts via the start() function below.  This probably
67     # should be changeg and these values should be obtained via the
68     # API to myplc.
69     }
70
71 start_requested = False  # set to True in order to request that all slivers be started
72
73 # check leases and adjust the 'reservation_alive' field in slivers
74 # this is not expected to be saved as it will change for the next round
75 def adjustReservedSlivers (data):
76     """
77     On reservable nodes, tweak the 'reservation_alive' field to instruct cyclic loop
78     about what to do with slivers.
79     """
80     # only impacts reservable nodes
81     if 'reservation_policy' not in data: return
82     policy=data['reservation_policy'] 
83     if policy not in ['lease_or_idle', 'lease_or_shared']:
84         if policy is not None:
85             logger.log ("unexpected reservation_policy %(policy)s"%locals())
86         return
87
88     logger.log("slivermanager.adjustReservedSlivers")
89     now=int(time.time())
90     # scan leases that are expected to show in ascending order
91     active_lease=None
92     for lease in data['leases']:
93         if lease['t_from'] <= now and now <= lease['t_until']:
94             active_lease=lease
95             break
96
97     def is_system_sliver (sliver):
98         for d in sliver['attributes']:
99             if d['tagname']=='system' and d['value']:
100                 return True
101         return False
102
103     # mark slivers as appropriate
104     for sliver in data['slivers']:
105         # system slivers must be kept alive
106         if is_system_sliver(sliver):
107             sliver['reservation_alive']=True
108             continue
109
110         # regular slivers
111         if not active_lease:
112             # with 'idle_or_shared', just let the field out, behave like a shared node
113             # otherwise, mark all slivers as being turned down
114             if policy == 'lease_or_idle':
115                 sliver['reservation_alive']=False
116         else:
117             # there is an active lease, mark it alive and the other not
118             sliver['reservation_alive'] = sliver['name']==active_lease['name']
119
120 @database.synchronized
121 def GetSlivers(data, config = None, plc=None, fullupdate=True):
122     """This function has two purposes.  One, convert GetSlivers() data
123     into a more convenient format.  Two, even if no updates are coming
124     in, use the GetSlivers() heartbeat as a cue to scan for expired
125     slivers."""
126
127     logger.verbose("slivermanager: Entering GetSlivers with fullupdate=%r"%fullupdate)
128     for key in data.keys():
129         logger.verbose('slivermanager: GetSlivers key : ' + key)
130
131     node_id = None
132     try:
133         f = open('/etc/planetlab/node_id')
134         try: node_id = int(f.read())
135         finally: f.close()
136     except: logger.log_exc("slivermanager: GetSlivers failed to read /etc/planetlab/node_id")
137
138     if data.has_key('node_id') and data['node_id'] != node_id: return
139
140     if data.has_key('networks'):
141         for network in data['networks']:
142             if network['is_primary'] and network['bwlimit'] is not None:
143                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
144
145     # Take initscripts (global) returned by API, build a hash scriptname->code
146     iscripts_hash = {}
147     if 'initscripts' not in data:
148         logger.log_missing_data("slivermanager.GetSlivers",'initscripts')
149         return
150     for initscript_rec in data['initscripts']:
151         logger.verbose("slivermanager: initscript: %s" % initscript_rec['name'])
152         iscripts_hash[str(initscript_rec['name'])] = initscript_rec['script']
153
154     adjustReservedSlivers (data)
155     for sliver in data['slivers']:
156         logger.verbose("slivermanager: %s: slivermanager.GetSlivers in slivers loop"%sliver['name'])
157         rec = sliver.copy()
158         rec.setdefault('timestamp', data['timestamp'])
159
160         # convert attributes field to a proper dict
161         attributes = {}
162         for attr in rec.pop('attributes'): attributes[attr['tagname']] = attr['value']
163         rec.setdefault("attributes", attributes)
164
165         # squash keys
166         keys = rec.pop('keys')
167         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
168
169         ## 'Type' isn't returned by GetSlivers() for whatever reason.  We're overloading
170         ## instantiation here, but i suppose its the same thing when you think about it. -FA
171         # Handle nm-controller here
172         if rec['instantiation'].lower() == 'nm-controller':
173             rec.setdefault('type', attributes.get('type', 'controller.Controller'))
174         else:
175             rec.setdefault('type', attributes.get('type', sliver_default_type))
176
177         # set the vserver reference.  If none, set to default.
178         rec.setdefault('vref', attributes.get('vref', 'default'))
179
180         ### set initscripts; set empty rec['initscript'] if not
181         # if tag 'initscript_code' is set, that's what we use
182         iscode = attributes.get('initscript_code','')
183         if iscode:
184             rec['initscript']=iscode
185         else:
186             isname = attributes.get('initscript')
187             if isname is not None and isname in iscripts_hash:
188                 rec['initscript'] = iscripts_hash[isname]
189             else:
190                 rec['initscript'] = ''
191
192         # set delegations, if none, set empty
193         rec.setdefault('delegations', attributes.get("delegations", []))
194
195         # extract the implied rspec
196         rspec = {}
197         rec['rspec'] = rspec
198         for resname, default_amount in DEFAULT_ALLOCATION.iteritems():
199             try:
200                 t = type(default_amount)
201                 amount = t.__new__(t, attributes[resname])
202             except (KeyError, ValueError): amount = default_amount
203             rspec[resname] = amount
204
205         # add in sysctl attributes into the rspec
206         for key in attributes.keys():
207             if key.find("sysctl.") == 0:
208                 rspec[key] = attributes[key]
209
210         # also export tags in rspec so they make it to the sliver_vs.start call
211         rspec['tags']=attributes
212
213         database.db.deliver_record(rec)
214     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
215     # slivers are created here.
216     database.db.sync()
217
218 def deliver_ticket(data):
219     return GetSlivers(data, fullupdate=False)
220
221 def start():
222     # No default allocation values for LXC yet, think if its necessary given
223     # that they are also default allocation values in this module
224     if implementation == 'vs':
225         for resname, default_amount in sliver_vs.DEFAULT_ALLOCATION.iteritems():
226             DEFAULT_ALLOCATION[resname]=default_amount
227
228     account.register_class(sliver_class_to_register)
229     account.register_class(controller.Controller)
230     database.start()
231     api_calls.deliver_ticket = deliver_ticket
232     api.start()
233
234 ### check if a sliver is running
235 ### a first step to a unified code for codemux
236 def is_running (name):
237     if implementation=='vs':
238         import vserver
239         return vserver.VServer(name).is_running()
240     else:
241         import libvirt
242         running = False
243         try:
244             conn = libvirt.open('lxc://')
245             dom  = conn.lookupByName(name)
246             running = dom.info()[0] == libvirt.VIR_DOMAIN_RUNNING
247         finally:
248             conn.close()
249         return running