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))
171 ### this is confusing, because it seems it is not used in fact
173 logger.verbose('sliver_libvirt: {} stop'.format(self.name))
175 # Remove the ebtables rule before stopping
176 bwlimit.ebtables("-D INPUT -i veth{} -j mark --set-mark {}"
177 .format(self.xid, self.xid))
182 logger.log_exc("in sliver_libvirt.stop", name=self.name)
184 def is_running(self):
185 ''' Return True if the domain is running '''
186 (state, _) = self.dom.state()
187 result = (state == libvirt.VIR_DOMAIN_RUNNING)
188 logger.verbose('sliver_libvirt.is_running: {} => {}'
189 .format(self, result))
192 def configure(self, rec):
194 #sliver.[LXC/QEMU] tolower case
195 #sliver_type = rec['type'].split('.')[1].lower()
197 #BASE_DIR = '/cgroup/libvirt/{}/{}/'.format(sliver_type, self.name)
200 # No way through cgroups... figure out how to do that with user/dir quotas.
201 # There is no way to do quota per directory. Chown-ing would create
202 # problems as username namespaces are not yet implemented (and thus, host
203 # and containers share the same name ids
205 # Btrfs support quota per volumes
207 if rec.has_key("rspec") and rec["rspec"].has_key("tags"):
208 if cgroups.get_cgroup_path(self.name) == None:
209 # If configure is called before start, then the cgroups won't exist
210 # yet. NM will eventually re-run configure on the next iteration.
211 # TODO: Add a post-start configure, and move this stuff there
212 logger.log("Configure: postponing tag check on {} as cgroups are not yet populated"
215 tags = rec["rspec"]["tags"]
216 # It will depend on the FS selection
217 if tags.has_key('disk_max'):
218 disk_max = tags['disk_max']
223 # limit to certain number
227 if tags.has_key('memlock_hard'):
228 mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
229 cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
230 if tags.has_key('memlock_soft'):
231 mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
232 cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
235 # Only cpu_shares until figure out how to provide limits and guarantees
237 if tags.has_key('cpu_share'):
238 cpu_share = tags['cpu_share']
239 cgroups.write(self.name, 'cpu.shares', cpu_share)
241 # Call the upper configure method (ssh keys...)
242 Account.configure(self, rec)
245 def get_unique_vif():
246 return 'veth{}'.format(random.getrandbits(32))
248 # A placeholder until we get true VirtualInterface objects
250 def get_interfaces_xml(rec):
252 <interface type='network'>
253 <source network='default'/>
256 """.format(Sliver_Libvirt.get_unique_vif())
258 tags = rec['rspec']['tags']
259 if 'interface' in tags:
260 interfaces = eval(tags['interface'])
261 if not isinstance(interfaces, (list, tuple)):
262 # if interface is not a list, then make it into a singleton list
263 interfaces = [interfaces]
265 for interface in interfaces:
266 if 'vlan' in interface:
267 vlanxml = "<vlan><tag id='{}'/></vlan>".format(interface['vlan'])
270 if 'bridge' in interface:
271 tag_xml = tag_xml + """
272 <interface type='bridge'>
273 <source bridge='{}'/>
275 <virtualport type='openvswitch'/>
278 """.format(interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
280 tag_xml = tag_xml + """
281 <interface type='network'>
282 <source network='default'/>
285 """.format(Sliver_Libvirt.get_unique_vif())
288 logger.log('sliver_libvirty.py: interface XML is: {}'.format(xml))
291 logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice {}'.format(rec['name']))
292 logger.log('sliver_libvirt.py: tag value: {}'.format(tags['interface']))