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