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