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