12 from account import Account
14 import plnode.bwlimit as bwlimit
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',
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',
38 class Sliver_Libvirt(Account):
43 def getConnection(sliver_type):
45 returns a connection to the underlying libvirt service
46 a single connection is created and shared among slivers
47 this call ensures the connection is alive
48 and will reconnect if it appears to be necessary
50 # sliver_type comes from rec['type'] and is of the form sliver.{LXC,QEMU}
51 # so we need to lower case to lxc/qemu
52 vtype = sliver_type.split('.')[1].lower()
54 if uri not in connections:
56 conn = libvirt.open(uri)
57 connections[uri] = conn
60 # connection already available : check for health
61 conn = connections[uri]
62 # see if a reconnection is needed
64 numDomains = conn.numOfDomains()
66 logger.log("libvirt connection to {} looks broken - reconnecting".format(uri))
67 conn = libvirt.open(uri)
68 # if this fails then an expection is thrown outside of this function
69 numDomains = conn.numOfDomains()
72 def __init__(self, rec):
73 self.name = rec['name']
74 logger.verbose ('sliver_libvirt: {} init'.format(self.name))
76 # Assume the directory with the image and config files
81 self.slice_id = rec['slice_id']
83 self.conn = Sliver_Libvirt.getConnection(rec['type'])
84 self.xid = bwlimit.get_xid(self.name)
88 dom = self.conn.lookupByName(self.name)
90 logger.log('sliver_libvirt: Domain {} does not exist. ' \
91 'Will try to create it again.'.format(self.name))
92 self.__class__.create(rec['name'], rec)
93 dom = self.conn.lookupByName(self.name)
97 def dom_details (dom):
99 output += " id={} - OSType={}".format(dom.ID(), dom.OSType())
100 # calling state() seems to be working fine
101 (state, reason) = dom.state()
102 output += " state={}, reason={}".format(STATES.get(state, state),
103 REASONS.get(reason, reason))
105 # try to use info() - this however does not work for some reason on f20
106 # info cannot get info operation failed: Cannot read cputime for domain
107 [state, maxmem, mem, ncpu, cputime] = dom.info()
108 output += " [info: state={}, maxmem = {}, mem = {}, ncpu = {}, cputime = {}]"\
109 .format(STATES.get(state, state), maxmem, mem, ncpu, cputime)
111 # too bad but libvirt.py prints out stuff on stdout when this fails, don't know how to get rid of that..
112 output += " [info: not available]"
116 ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
117 output = "Domain {}".format(self.name)
120 output += " [no attached dom ?!?]"
122 output += Sliver_Libvirt.dom_details (dom)
125 # Thierry : I am not quite sure if /etc/libvirt/lxc/<>.xml holds a reliably up-to-date
126 # copy of the sliver XML config; I feel like issuing a virsh dumpxml first might be safer
127 def repair_veth(self):
128 # See workaround email, 2-14-2014, "libvirt 1.2.1 rollout"
129 xmlfilename = "/etc/libvirt/lxc/{}.xml".format(self.name)
130 with open(xmlfilename) as xmlfile:
132 veths = re.findall("<target dev='veth[0-9]*'/>", xml)
133 veths = [x[13:-3] for x in veths]
135 command = ["ip", "link", "delete", veth]
136 logger.log_call(command)
138 logger.log("trying to redefine the VM")
139 command = [ "virsh", "define", xmlfilename ]
140 logger.log_call(command)
142 def start(self, delay=0):
143 '''Just start the sliver'''
144 logger.verbose('sliver_libvirt: {} start'.format(self.name))
146 # Check if it's running to avoid throwing an exception if the
147 # domain was already running
148 if not self.is_running():
150 # create actually means start
153 # XXX smbaker: attempt to resolve slivers that are stuck in
154 # "failed to allocate free veth".
155 if "ailed to allocate free veth" in str(e):
156 logger.log("failed to allocate free veth on {}".format(self.name))
158 logger.log("trying dom.create again")
163 logger.verbose('sliver_libvirt: sliver {} already started'.format(self.name))
165 # After the VM is started... we can play with the virtual interface
166 # Create the ebtables rule to mark the packets going out from the virtual
167 # interface to the actual device so the filter canmatch against the mark
168 bwlimit.ebtables("-A INPUT -i veth{} -j mark --set-mark {}"
169 .format(self.xid, self.xid))
172 logger.verbose('sliver_libvirt: {} stop'.format(self.name))
174 # Remove the ebtables rule before stopping
175 bwlimit.ebtables("-D INPUT -i veth{} -j mark --set-mark {}"
176 .format(self.xid, self.xid))
181 logger.log_exc("in sliver_libvirt.stop", name=self.name)
183 def is_running(self):
184 ''' Return True if the domain is running '''
185 (state, _) = self.dom.state()
186 result = (state == libvirt.VIR_DOMAIN_RUNNING)
187 logger.verbose('sliver_libvirt.is_running: {} => {}'
188 .format(self, result))
191 def configure(self, rec):
193 #sliver.[LXC/QEMU] tolower case
194 #sliver_type = rec['type'].split('.')[1].lower()
196 #BASE_DIR = '/cgroup/libvirt/{}/{}/'.format(sliver_type, self.name)
199 # No way through cgroups... figure out how to do that with user/dir quotas.
200 # There is no way to do quota per directory. Chown-ing would create
201 # problems as username namespaces are not yet implemented (and thus, host
202 # and containers share the same name ids
204 # Btrfs support quota per volumes
206 if rec.has_key("rspec") and rec["rspec"].has_key("tags"):
207 if cgroups.get_cgroup_path(self.name) == None:
208 # If configure is called before start, then the cgroups won't exist
209 # yet. NM will eventually re-run configure on the next iteration.
210 # TODO: Add a post-start configure, and move this stuff there
211 logger.log("Configure: postponing tag check on {} as cgroups are not yet populated"
214 tags = rec["rspec"]["tags"]
215 # It will depend on the FS selection
216 if tags.has_key('disk_max'):
217 disk_max = tags['disk_max']
222 # limit to certain number
226 if tags.has_key('memlock_hard'):
227 mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
228 cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
229 if tags.has_key('memlock_soft'):
230 mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
231 cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
234 # Only cpu_shares until figure out how to provide limits and guarantees
236 if tags.has_key('cpu_share'):
237 cpu_share = tags['cpu_share']
238 cgroups.write(self.name, 'cpu.shares', cpu_share)
240 # Call the upper configure method (ssh keys...)
241 Account.configure(self, rec)
244 def get_unique_vif():
245 return 'veth{}'.format(random.getrandbits(32))
247 # A placeholder until we get true VirtualInterface objects
249 def get_interfaces_xml(rec):
251 <interface type='network'>
252 <source network='default'/>
255 """.format(Sliver_Libvirt.get_unique_vif())
257 tags = rec['rspec']['tags']
258 if 'interface' in tags:
259 interfaces = eval(tags['interface'])
260 if not isinstance(interfaces, (list, tuple)):
261 # if interface is not a list, then make it into a singleton list
262 interfaces = [interfaces]
264 for interface in interfaces:
265 if 'vlan' in interface:
266 vlanxml = "<vlan><tag id='{}'/></vlan>".format(interface['vlan'])
269 if 'bridge' in interface:
270 tag_xml = tag_xml + """
271 <interface type='bridge'>
272 <source bridge='{}'/>
274 <virtualport type='openvswitch'/>
277 """.format(interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
279 tag_xml = tag_xml + """
280 <interface type='network'>
281 <source network='default'/>
284 """.format(Sliver_Libvirt.get_unique_vif())
287 logger.log('sliver_libvirty.py: interface XML is: {}'.format(xml))
290 logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice {}'.format(rec['name']))
291 logger.log('sliver_libvirt.py: tag value: {}'.format(tags['interface']))