11 from account import Account
13 import plnode.bwlimit as bwlimit
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',
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',
37 class Sliver_Libvirt(Account):
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()
47 return connections.setdefault(uri, libvirt.open(uri))
49 def __init__(self, rec):
50 self.name = rec['name']
51 logger.verbose ('sliver_libvirt: %s init'%(self.name))
53 # Assume the directory with the image and config files
58 self.slice_id = rec['slice_id']
60 self.conn = Sliver_Libvirt.getConnection(rec['type'])
61 self.xid = bwlimit.get_xid(self.name)
65 dom = self.conn.lookupByName(self.name)
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)
74 ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
75 output="Domain %s"%self.name
78 output += " [no attached dom ?!?]"
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))
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)
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]"
95 def start(self, delay=0):
96 ''' Just start the sliver '''
97 logger.verbose('sliver_libvirt: %s start'%(self.name))
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():
104 logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
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))
113 logger.verbose('sliver_libvirt: %s stop'%(self.name))
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))
122 logger.log_exc("in sliver_libvirt.stop",name=self.name)
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))
131 def configure(self, rec):
133 #sliver.[LXC/QEMU] tolower case
134 #sliver_type = rec['type'].split('.')[1].lower()
136 #BASE_DIR = '/cgroup/libvirt/%s/%s/'%(sliver_type, self.name)
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
144 # Btrfs support quota per volumes
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)
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']
161 # limit to certain number
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")
173 # Only cpu_shares until figure out how to provide limits and guarantees
175 if tags.has_key('cpu_share'):
176 cpu_share = tags['cpu_share']
177 cgroups.write(self.name, 'cpu.shares', cpu_share)
179 # Call the upper configure method (ssh keys...)
180 Account.configure(self, rec)
183 def get_unique_vif():
184 return 'veth%s' % random.getrandbits(32)
186 # A placeholder until we get true VirtualInterface objects
188 def get_interfaces_xml(rec):
190 <interface type='network'>
191 <source network='default'/>
194 """ % (Sliver_Libvirt.get_unique_vif())
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]
203 for interface in interfaces:
204 if 'vlan' in interface:
205 vlanxml = "<vlan><tag id='%s'/></vlan>" % interface['vlan']
208 if 'bridge' in interface:
209 tag_xml = tag_xml + """
210 <interface type='bridge'>
211 <source bridge='%s'/>
213 <virtualport type='openvswitch'/>
216 """ % (interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
218 tag_xml = tag_xml + """
219 <interface type='network'>
220 <source network='default'/>
223 """ % (Sliver_Libvirt.get_unique_vif())
226 logger.log('sliver_libvirty.py: interface XML is: %s' % xml)
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'])