fix coresched locating cgroup and reduce verbosity
[nodemanager.git] / sliver_libvirt.py
1 """LibVirt slivers"""
2
3 import sys
4 import os, os.path
5 import re
6 import subprocess
7 import pprint
8 import random
9
10 import libvirt
11
12 from account import Account
13 import logger
14 import plnode.bwlimit as bwlimit
15 import cgroups
16
17 STATES = {
18     libvirt.VIR_DOMAIN_NOSTATE:  'no state',
19     libvirt.VIR_DOMAIN_RUNNING:  'running',
20     libvirt.VIR_DOMAIN_BLOCKED:  'blocked on resource',
21     libvirt.VIR_DOMAIN_PAUSED:   'paused by user',
22     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
23     libvirt.VIR_DOMAIN_SHUTOFF:  'shut off',
24     libvirt.VIR_DOMAIN_CRASHED:  'crashed',
25 }
26
27 REASONS = {
28     libvirt.VIR_CONNECT_CLOSE_REASON_ERROR: 'Misc I/O error',
29     libvirt.VIR_CONNECT_CLOSE_REASON_EOF: 'End-of-file from server',
30     libvirt.VIR_CONNECT_CLOSE_REASON_KEEPALIVE: 'Keepalive timer triggered',
31     libvirt.VIR_CONNECT_CLOSE_REASON_CLIENT: 'Client requested it',
32 }
33
34 connections = dict()
35
36 # Common Libvirt code
37
38 class Sliver_Libvirt(Account):
39
40     # Helper methods
41
42     @staticmethod
43     def getConnection(sliver_type):
44         # TODO: error checking
45         # vtype is of the form sliver.[LXC/QEMU] we need to lower case to lxc/qemu
46         vtype = sliver_type.split('.')[1].lower()
47         uri = vtype + '://'
48         return connections.setdefault(uri, libvirt.open(uri))
49
50     def __init__(self, rec):
51         self.name = rec['name']
52         logger.verbose ('sliver_libvirt: %s init'%(self.name))
53
54         # Assume the directory with the image and config files
55         # are in place
56
57         self.keys = ''
58         self.rspec = {}
59         self.slice_id = rec['slice_id']
60         self.enabled = True
61         self.conn = Sliver_Libvirt.getConnection(rec['type'])
62         self.xid = bwlimit.get_xid(self.name)
63
64         dom = None
65         try:
66             dom = self.conn.lookupByName(self.name)
67         except:
68             logger.log('sliver_libvirt: Domain %s does not exist. ' \
69                        'Will try to create it again.' % (self.name))
70             self.__class__.create(rec['name'], rec)
71             dom = self.conn.lookupByName(self.name)
72         self.dom = dom
73
74     @staticmethod
75     def dom_details (dom):
76         output=""
77         output += " id=%s - OSType=%s"%(dom.ID(),dom.OSType())
78         # calling state() seems to be working fine
79         (state,reason)=dom.state()
80         output += " state=%s, reason=%s"%(STATES.get(state,state),REASONS.get(reason,reason))
81         try:
82             # try to use info() - this however does not work for some reason on f20
83             # info cannot get info operation failed: Cannot read cputime for domain
84             [state, maxmem, mem, ncpu, cputime] = dom.info()
85             output += " [info: maxmem = %s, mem = %s, ncpu = %s, cputime = %s]" % (STATES.get(state, state), maxmem, mem, ncpu, cputime)
86         except:
87             # too bad but libvirt.py prints out stuff on stdout when this fails, don't know how to get rid of that..
88             output += " [info: not available]"
89         return output
90
91     def __repr__(self):
92         ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
93         output="Domain %s"%self.name
94         dom=self.dom
95         if dom is None: 
96             output += " [no attached dom ?!?]"
97         else:
98             output += Sliver_Libvirt.dom_details (dom)
99         return output
100
101     # Thierry : I am not quite sure if /etc/libvirt/lxc/<>.xml holds a reliably up-to-date
102     # copy of the sliver XML config; I feel like issuing a virsh dumpxml first might be safer
103     def repair_veth(self):
104         # See workaround email, 2-14-2014, "libvirt 1.2.1 rollout"
105         xml = open("/etc/libvirt/lxc/%s.xml" % self.name).read()
106         veths = re.findall("<target dev='veth[0-9]*'/>", xml)
107         veths = [x[13:-3] for x in veths]
108         for veth in veths:
109             command = ["ip", "link", "delete", veth]
110             logger.log_call(command)
111
112         logger.log("trying to redefine the VM")
113         command = ["virsh", "define", "/etc/libvirt/lxc/%s.xml" % self.name]
114         logger.log_call(command)
115
116     def start(self, delay=0):
117         '''Just start the sliver'''
118         logger.verbose('sliver_libvirt: %s start'%(self.name))
119
120         # Check if it's running to avoid throwing an exception if the
121         # domain was already running
122         if not self.is_running():
123             try:
124                 # create actually means start
125                 self.dom.create()
126             except Exception, e:
127                 # XXX smbaker: attempt to resolve slivers that are stuck in
128                 #   "failed to allocate free veth".
129                 if "ailed to allocate free veth" in str(e):
130                      logger.log("failed to allocate free veth on %s" % self.name)
131                      self.repair_veth()
132                      logger.log("trying dom.create again")
133                      self.dom.create()
134                 else:
135                     raise
136         else:
137             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
138
139         # After the VM is started... we can play with the virtual interface
140         # Create the ebtables rule to mark the packets going out from the virtual
141         # interface to the actual device so the filter canmatch against the mark
142         bwlimit.ebtables("-A INPUT -i veth%d -j mark --set-mark %d" % \
143             (self.xid, self.xid))
144
145     def stop(self):
146         logger.verbose('sliver_libvirt: %s stop'%(self.name))
147
148         # Remove the ebtables rule before stopping 
149         bwlimit.ebtables("-D INPUT -i veth%d -j mark --set-mark %d" % \
150             (self.xid, self.xid))
151
152         try:
153             self.dom.destroy()
154         except:
155             logger.log_exc("in sliver_libvirt.stop",name=self.name)
156
157     def is_running(self):
158         ''' Return True if the domain is running '''
159         (state,_) = self.dom.state()
160         result = (state == libvirt.VIR_DOMAIN_RUNNING)
161         logger.verbose('sliver_libvirt.is_running: %s => %s'%(self,result))
162         return result
163
164     def configure(self, rec):
165
166         #sliver.[LXC/QEMU] tolower case
167         #sliver_type = rec['type'].split('.')[1].lower() 
168
169         #BASE_DIR = '/cgroup/libvirt/%s/%s/'%(sliver_type, self.name)
170
171         # Disk allocation
172         # No way through cgroups... figure out how to do that with user/dir quotas.
173         # There is no way to do quota per directory. Chown-ing would create
174         # problems as username namespaces are not yet implemented (and thus, host
175         # and containers share the same name ids
176
177         # Btrfs support quota per volumes
178
179         if rec.has_key("rspec") and rec["rspec"].has_key("tags"):
180             if cgroups.get_cgroup_path(self.name) == None:
181                 # If configure is called before start, then the cgroups won't exist
182                 # yet. NM will eventually re-run configure on the next iteration.
183                 # TODO: Add a post-start configure, and move this stuff there
184                 logger.log("Configure: postponing tag check on %s as cgroups are not yet populated" % self.name)
185             else:
186                 tags = rec["rspec"]["tags"]
187                 # It will depend on the FS selection
188                 if tags.has_key('disk_max'):
189                     disk_max = tags['disk_max']
190                     if disk_max == 0:
191                         # unlimited
192                         pass
193                     else:
194                         # limit to certain number
195                         pass
196
197                 # Memory allocation
198                 if tags.has_key('memlock_hard'):
199                     mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
200                     cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
201                 if tags.has_key('memlock_soft'):
202                     mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
203                     cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
204
205                 # CPU allocation
206                 # Only cpu_shares until figure out how to provide limits and guarantees
207                 # (RT_SCHED?)
208                 if tags.has_key('cpu_share'):
209                     cpu_share = tags['cpu_share']
210                     cgroups.write(self.name, 'cpu.shares', cpu_share)
211
212         # Call the upper configure method (ssh keys...)
213         Account.configure(self, rec)
214
215     @staticmethod
216     def get_unique_vif():
217         return 'veth%s' % random.getrandbits(32)
218
219     # A placeholder until we get true VirtualInterface objects
220     @staticmethod
221     def get_interfaces_xml(rec):
222         xml = """
223     <interface type='network'>
224       <source network='default'/>
225       <target dev='%s'/>
226     </interface>
227 """ % (Sliver_Libvirt.get_unique_vif())
228         try:
229             tags = rec['rspec']['tags']
230             if 'interface' in tags:
231                 interfaces = eval(tags['interface'])
232                 if not isinstance(interfaces, (list, tuple)):
233                     # if interface is not a list, then make it into a singleton list
234                     interfaces = [interfaces]
235                 tag_xml = ""
236                 for interface in interfaces:
237                     if 'vlan' in interface:
238                         vlanxml = "<vlan><tag id='%s'/></vlan>" % interface['vlan']
239                     else:
240                         vlanxml = ""
241                     if 'bridge' in interface:
242                         tag_xml = tag_xml + """
243         <interface type='bridge'>
244           <source bridge='%s'/>
245           %s
246           <virtualport type='openvswitch'/>
247           <target dev='%s'/>
248         </interface>
249     """ % (interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
250                     else:
251                         tag_xml = tag_xml + """
252         <interface type='network'>
253           <source network='default'/>
254           <target dev='%s'/>
255         </interface>
256     """ % (Sliver_Libvirt.get_unique_vif())
257
258                 xml = tag_xml
259                 logger.log('sliver_libvirty.py: interface XML is: %s' % xml)
260
261         except:
262             logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice %s' % rec['name'])
263             logger.log('sliver_libvirt.py: tag value: %s' % tags['interface'])
264
265         return xml