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