├── requirements.txt ├── AUTHORS ├── setup.cfg ├── PKG-INFO ├── README.rst ├── python_lkvm ├── __init__.py └── lkvm.py ├── setup.py ├── ChangeLog ├── .gitignore └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | pbr>=1.6 2 | psutil>=1.1.1 3 | six>=1.9.0 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Munoz, Obed N 2 | Simental Magana, Marcos 3 | Victor Morales 4 | 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = python-lkvm 3 | summary = Library for lkvm 4 | description-file = 5 | README.rst 6 | author = Obed N Munoz 7 | author-email = obed.n.munoz@intel.com 8 | home-page = 9 | classifier = 10 | Intended Audience :: Information Technology 11 | Intended Audience :: System Administrators 12 | License :: OSI Approved :: Apache Software License 13 | Operating System :: POSIX :: Linux 14 | Programming Language :: Python :: 2 15 | Programming Language :: Python :: 2.7 16 | Programming Language :: Python :: 3 17 | Programming Language :: Python :: 3.3 18 | -------------------------------------------------------------------------------- /PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.1 2 | Name: python-lkvm 3 | Version: 0.5 4 | Summary: Library for lkvm 5 | Home-page: https://github.com/clearlinux/python-lkvm 6 | Author: Obed N Munoz 7 | Author-email: obed.n.munoz@intel.com 8 | License: Apache-2.0 9 | Description: python-lkvm is a python wrapper for lkvm command 10 | Platform: Unix 11 | Classifier: Intended Audience :: Information Technology 12 | Classifier: Intended Audience :: System Administrators 13 | Classifier: License :: OSI Approved :: Apache Software License 14 | Classifier: Operating System :: POSIX :: Linux 15 | Classifier: Programming Language :: Python :: 2 16 | Classifier: Programming Language :: Python :: 2.7 17 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Summary 2 | =========== 3 | 4 | **python-lkvm** is a python wrapper for lkvm command line which exposes its 5 | methods through a simple API. This allows other python applications to manage 6 | instances. 7 | 8 | 9 | Getting started 10 | --------------- 11 | 12 | As most of python modules, *python-lkvm* can be installed via setuptools: :: 13 | 14 | $ python setup.py install 15 | 16 | Once this module is installed, it can be used their method creating a client 17 | instance, for example, for listing existing instances: :: 18 | 19 | import lkvm 20 | 21 | client = lkvm.Client() 22 | 23 | for ins in client.list_instances(): 24 | print ins.name, ins.state 25 | -------------------------------------------------------------------------------- /python_lkvm/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2015 Intel Corporation 3 | # 4 | # Author: Munoz, Obed N 5 | # Author: Simental Magana, Marcos 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2015 Intel Corporation 3 | # 4 | # Author: Munoz, Obed N 5 | # Author: Simental Magana, Marcos 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | import setuptools 21 | 22 | setuptools.setup( 23 | setup_requires=['pbr>=1.8'], 24 | pbr=True, 25 | packages=[''], 26 | package_dir={'': 'python_lkvm'}) 27 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | CHANGES 2 | ======= 3 | 4 | * Fix Readme 5 | * Add license 6 | * Add python logging support 7 | * Implement function to get more information about the instances 8 | * Implement sandbox method 9 | * Implement setup method 10 | * Fix identation code 11 | * Add example into documentation 12 | * Send process to background (the hard way) 13 | * Change background process validation 14 | * Fix import module (for real) 15 | * Fix import lkvm module 16 | * Ignore build/ dir 17 | * Add setup.py install capability 18 | * Add the implementation of balloon method 19 | * Change root_helper to string variable 20 | * Add root helper property 21 | * Add draft is_support function 22 | * Add the implementation of stat method 23 | * Add the implementation of resume method 24 | * Add the implementation of pause method 25 | * Add the implementation of stop method 26 | * Add the implemention of run method 27 | * Add list_instance method implementation 28 | * Change name to list_instances 29 | * Initial structure 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/python,emacs,vim 3 | 4 | ### Python ### 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | env/ 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *,cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | 59 | # Sphinx documentation 60 | docs/_build/ 61 | 62 | # PyBuilder 63 | target/ 64 | 65 | 66 | ### Emacs ### 67 | # -*- mode: gitignore; -*- 68 | *~ 69 | \#*\# 70 | /.emacs.desktop 71 | /.emacs.desktop.lock 72 | *.elc 73 | auto-save-list 74 | tramp 75 | .\#* 76 | 77 | # Org-mode 78 | .org-id-locations 79 | *_archive 80 | 81 | # flymake-mode 82 | *_flymake.* 83 | 84 | # eshell files 85 | /eshell/history 86 | /eshell/lastdir 87 | 88 | # elpa packages 89 | /elpa/ 90 | 91 | # reftex files 92 | *.rel 93 | 94 | # AUCTeX auto folder 95 | /auto/ 96 | 97 | # cask packages 98 | .cask/ 99 | 100 | 101 | ### Vim ### 102 | [._]*.s[a-w][a-z] 103 | [._]s[a-w][a-z] 104 | *.un~ 105 | Session.vim 106 | .netrwhist 107 | *~ 108 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /python_lkvm/lkvm.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2015 Intel Corporation 3 | # 4 | # Author: Morales, Victor 5 | # Author: Munoz, Obed N 6 | # Author: Simental Magana, Marcos 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | 21 | import logging 22 | import os 23 | import psutil 24 | import six 25 | import subprocess 26 | import sys 27 | 28 | LKVM_PATH='/usr/bin/lkvm' 29 | 30 | logging.basicConfig(format='%(message)s', level=logging.INFO) 31 | LOG = logging.getLogger(__name__) 32 | 33 | class LKVMException(Exception): 34 | pass 35 | 36 | 37 | class LKVMInstance(object): 38 | pass 39 | 40 | 41 | class Client(object): 42 | 43 | def __init__(self): 44 | self._root_helper = None 45 | 46 | @property 47 | def root_helper(self): 48 | return self._root_helper 49 | 50 | @root_helper.setter 51 | def root_helper(self, value): 52 | self._root_helper = value 53 | 54 | def _get_instance_info(self, pid): 55 | if isinstance(pid, six.string_types): 56 | pid = int(pid) 57 | try: 58 | args = psutil.Process(pid).cmdline()[2:] 59 | except NoSuchProcess: 60 | raise LKVMException("PID %s not found" % pid) 61 | props = {args[i][2:]: args[i+1] for i in range(0, len(args), 2)} 62 | LOG.debug('Properties found : ' + str(props)) 63 | 64 | return type('LKVMInstance', (object,), props) 65 | 66 | def _execute(self, cmd, *args, **kwargs): 67 | """Helper method to shell out and execute a command through subprocess. 68 | 69 | :param cmd: Command 70 | :type cmd: string 71 | :param args: Arguments 72 | :type args: string 73 | 74 | """ 75 | 76 | if hasattr(os, 'geteuid') and os.geteuid() != 0 and not self._root_helper: 77 | return 78 | 79 | command = [LKVM_PATH] 80 | if self._root_helper: 81 | command = [self._root_helper] + command 82 | command.append(cmd) 83 | command.extend(*args) 84 | 85 | command = [str(c) for c in command] 86 | 87 | LOG.debug('Executing command : %s ', command) 88 | if kwargs.get('background'): 89 | command.insert(0, 'nohup') 90 | command = ' '.join(command) + ' >/dev/null 2>&1' 91 | subprocess.Popen(command, shell=True) 92 | else: 93 | _PIPE = subprocess.PIPE 94 | obj = subprocess.Popen(command, 95 | stdin=_PIPE, 96 | stdout=_PIPE, 97 | stderr=_PIPE) 98 | try: 99 | result = obj.communicate() 100 | obj.stdin.close() 101 | except OSError as err: 102 | if isinstance(err, ProcessExecutionError): 103 | err_msg = ('{e[description]}\ncommand: {e[cmd]}\n' 104 | 'exit code: {e[exit_code]}\nstdout: {e[stdout]}\n' 105 | 'stderr: {e[stderr]}').format(e=err) 106 | raise LKVMException(err_msg) 107 | if result[1]: 108 | raise LKVMException(result[1]) 109 | 110 | return result[0] 111 | 112 | def run(self, cpus, mem, shmem, console, kernel, params, 113 | network, name=None, disk=None, balloon=False, 114 | vnc=False, gtk=False, sdl=False, rng=False, 115 | plan9=False, dev=None, tty=None, sandbox=None, 116 | hugetlbs=None, initrd=None, firmware=None, 117 | no_dhcp=False): 118 | """Start the virtual machine 119 | 120 | :param name: Name of the guest 121 | :type name: string 122 | :param cpus: Number of CPUs 123 | :type cpus: integer 124 | :param mem: Virtual machine memory size in MiB. 125 | :type mem: integer 126 | :param shmem: Share host shmem with guest via pci device 127 | :type shmem: string 128 | :param disk: Disk image or rootfs directory 129 | :type disk: string 130 | :param balloon: Enable virtio balloon 131 | :type balloon: boolean 132 | :param vnc: Enable VNC framebuffer 133 | :type vnc: boolean 134 | :param gtk: Enable GTK framebuffer 135 | :type gtk: boolean 136 | :param sdl: Enable SDL framebuffer 137 | :type sdl: boolean 138 | :param rng: Enable virtio Random Number Generator 139 | :type rng: boolean 140 | :param plan9: Enable virtio 9p to share files between host and guest 141 | :type plan9: boolean 142 | :param console: Console to use 143 | :type console: string 144 | :param dev: KVM device file 145 | :type dev: string 146 | :param tty: Remap guest TTY into a pty on the host 147 | :type tty: string 148 | :param sandbox: Run this script when booting into custom rootfs 149 | :type sandbox: string 150 | :param hugetlbfs: Hugetlbfs path 151 | :type hugetlbfs: string 152 | :param kernel: Kernel to boot in virtual machine 153 | :type kernel: string 154 | :param initrd: Initial RAM disk image 155 | :type initrd: integer 156 | :param params: Kernel command line arguments 157 | :type params: string 158 | :param firmware: Firmware image to boot in virtual machine 159 | :type firmware: string 160 | :param network: Create a new guest NIC 161 | :type network: string 162 | :param no_dhcp: Disable kernel DHCP in rootfs mode 163 | :type no_dhcp: boolean 164 | 165 | """ 166 | 167 | _params = [] 168 | 169 | # Basic options 170 | 171 | 172 | _params.extend(['--cpus', cpus, 173 | '--mem', mem, 174 | '--shmem', shmem]) 175 | 176 | if name: 177 | _params.extend(['--name', name]) 178 | if console in ['serial', 'virtio', 'hv']: 179 | _params.extend(['--console', console]) 180 | if balloon: 181 | _params.append('--balloon') 182 | if vnc: 183 | _params.append('--vnc') 184 | if gtk: 185 | _params.append('--gtk') 186 | if sdl: 187 | _params.append('--sdl') 188 | if rng: 189 | _params.append('--rng') 190 | if plan9: 191 | _params.append('--9p') 192 | if disk: 193 | _params.extend(['--disk', disk]) 194 | if dev: 195 | _params.extend(['--dev', dev]) 196 | if tty: 197 | _params.extend(['--tty', tty]) 198 | if sandbox: 199 | _params.extend(['--sandbox', sandbox]) 200 | if hugetlbs: 201 | _params.extend(['--hugetlbs', hugetlbs]) 202 | 203 | # Kernel options 204 | 205 | _params.extend(['--kernel', kernel, 206 | '--params', '"%s"' % params]) 207 | 208 | if initrd: 209 | _params.extend(['--initrd', initrd]) 210 | if firmware: 211 | _params.extend(['--firmware', firmware]) 212 | 213 | # Networking options 214 | 215 | _params.extend(['--network', network]) 216 | 217 | if no_dhcp: 218 | _params.append('--no-dhcp') 219 | 220 | self._execute('run', _params, background=True) 221 | 222 | def setup(self, name): 223 | """ 224 | Setup a new virtual machine 225 | 226 | :param name: Instance name 227 | :type name: string 228 | 229 | """ 230 | params = ['--name', name] 231 | 232 | return self._execute('setup', params) 233 | 234 | def pause(self, all=False, name=None): 235 | """Pause the virtual machine 236 | 237 | :param all: Pause all instances 238 | :type all: boolean 239 | :param name: Instance name 240 | :type name: string 241 | 242 | """ 243 | params = [] 244 | if all: 245 | params.append('--all') 246 | elif name: 247 | params.extend(['--name', name]) 248 | else: 249 | return 250 | 251 | self._execute('pause', params) 252 | 253 | def resume(self, all=False, name=None): 254 | """Resume the virtual machine 255 | 256 | :param all: Resume all instances 257 | :type all: boolean 258 | :param name: Instance name 259 | :type name: string 260 | 261 | """ 262 | params = [] 263 | if all: 264 | params.append('--all') 265 | elif name: 266 | params.extend(['--name', name]) 267 | else: 268 | return 269 | 270 | self._execute('resume', params) 271 | 272 | def list_instances(self, run=True, rootfs=True): 273 | """Print a list of running instances on the host. 274 | 275 | :param run: List running instances 276 | :type cmd: boolean 277 | :param rootfs: List rootfs instances 278 | :type args: boolean 279 | 280 | """ 281 | params = [] 282 | if run: 283 | params.append('--run') 284 | if rootfs: 285 | params.append('--rootfs') 286 | 287 | output = self._execute('list', params) 288 | 289 | instances = [] 290 | if output: 291 | results = output.split('\n') 292 | if len(results) > 2 : 293 | for result in results[2:-1]: 294 | ins = result.split() 295 | instance = self._get_instance_info(ins[0]) 296 | instance.pid = ins[0] 297 | instance.name = ins[1] 298 | instance.state = ins[2] 299 | instances.append(instance) 300 | 301 | return instances 302 | 303 | def balloon(self, name, amount, balloon_options): 304 | """Inflate or deflate the virtio balloon 305 | 306 | :param name: Instance name 307 | :type name: string 308 | :param amount: Amount to inflate/deflate (in MB) 309 | :type amount: integer 310 | :param ballon_options: 311 | 312 | """ 313 | params = ['name', name] 314 | if balloon_options == 'inflate': 315 | params.extend(['--inflate', amount]) 316 | elif balloon_options == 'deflate': 317 | params.extend(['--deflate', amount]) 318 | 319 | self._execute('balloon', params) 320 | 321 | def stop(self, all=False, name=None): 322 | """Stop a running instance 323 | 324 | :param all: Stop all instances 325 | :type all: boolean 326 | :param name: Instance name 327 | :type name: string 328 | 329 | """ 330 | params = [] 331 | if all: 332 | params.append('--all') 333 | elif name: 334 | params.extend(['--name', name]) 335 | else: 336 | return 337 | 338 | self._execute('stop', params) 339 | 340 | def stat(self, memory=True, all=False, name=None): 341 | """Print statistics about a running instance 342 | 343 | :param memory: Display memory statistics 344 | :type memory: boolean 345 | :param all: All instances 346 | :type all: boolean 347 | :param name: Instance name 348 | :type name: string 349 | 350 | """ 351 | return # This method is not supported by lkvm client 352 | 353 | params = ['--memory'] 354 | if all: 355 | params.append('--all') 356 | elif name: 357 | params.extend(['--name', name]) 358 | else: 359 | return 360 | 361 | output = self._execute('stat', params) 362 | 363 | instances = [] 364 | if len(output) > 1: 365 | if len(results) > 2 : 366 | for result in results[2:-1]: 367 | ins = result.split() 368 | instance = KVMInstance(ins[0], ins[1], ins[2]) 369 | instances.append(instance) 370 | 371 | return instances 372 | 373 | def sandbox(self, cpus, mem, shmem, console, kernel, params, 374 | network, name=None, disk=None, balloon=False, 375 | vnc=False, gtk=False, sdl=False, rng=False, 376 | plan9=False, dev=None, tty=None, sandbox=None, 377 | hugetlbs=None, initrd=None, firmware=None, 378 | no_dhcp=False): 379 | """Run a command in a sandboxed guest 380 | 381 | :param name: Name of the guest 382 | :type name: string 383 | :param cpus: Number of CPUs 384 | :type cpus: integer 385 | :param mem: Virtual machine memory size in MiB. 386 | :type mem: integer 387 | :param shmem: Share host shmem with guest via pci device 388 | :type shmem: string 389 | :param disk: Disk image or rootfs directory 390 | :type disk: string 391 | :param balloon: Enable virtio balloon 392 | :type balloon: boolean 393 | :param vnc: Enable VNC framebuffer 394 | :type vnc: boolean 395 | :param gtk: Enable GTK framebuffer 396 | :type gtk: boolean 397 | :param sdl: Enable SDL framebuffer 398 | :type sdl: boolean 399 | :param rng: Enable virtio Random Number Generator 400 | :type rng: boolean 401 | :param plan9: Enable virtio 9p to share files between host and guest 402 | :type plan9: boolean 403 | :param console: Console to use 404 | :type console: string 405 | :param dev: KVM device file 406 | :type dev: string 407 | :param tty: Remap guest TTY into a pty on the host 408 | :type tty: string 409 | :param sandbox: Run this script when booting into custom rootfs 410 | :type sandbox: string 411 | :param hugetlbfs: Hugetlbfs path 412 | :type hugetlbfs: string 413 | :param kernel: Kernel to boot in virtual machine 414 | :type kernel: string 415 | :param initrd: Initial RAM disk image 416 | :type initrd: integer 417 | :param params: Kernel command line arguments 418 | :type params: string 419 | :param firmware: Firmware image to boot in virtual machine 420 | :type firmware: string 421 | :param network: Create a new guest NIC 422 | :type network: string 423 | :param no_dhcp: Disable kernel DHCP in rootfs mode 424 | :type no_dhcp: boolean 425 | 426 | """ 427 | 428 | _params = [] 429 | 430 | # Basic options 431 | 432 | 433 | _params.extend(['--cpus', cpus, 434 | '--mem', mem, 435 | '--shmem', shmem]) 436 | 437 | if name: 438 | _params.extend(['--name', name]) 439 | if console in ['serial', 'virtio', 'hv']: 440 | _params.extend(['--console', console]) 441 | if balloon: 442 | _params.append('--balloon') 443 | if vnc: 444 | _params.append('--vnc') 445 | if gtk: 446 | _params.append('--gtk') 447 | if sdl: 448 | _params.append('--sdl') 449 | if rng: 450 | _params.append('--rng') 451 | if plan9: 452 | _params.append('--9p') 453 | if disk: 454 | _params.extend(['--disk', disk]) 455 | if dev: 456 | _params.extend(['--dev', dev]) 457 | if tty: 458 | _params.extend(['--tty', tty]) 459 | if sandbox: 460 | _params.extend(['--sandbox', sandbox]) 461 | if hugetlbs: 462 | _params.extend(['--hugetlbs', hugetlbs]) 463 | 464 | # Kernel options 465 | 466 | _params.extend(['--kernel', kernel, 467 | '--params', '"%s"' % params]) 468 | 469 | if initrd: 470 | _params.extend(['--initrd', initrd]) 471 | if firmware: 472 | _params.extend(['--firmware', firmware]) 473 | 474 | # Networking options 475 | 476 | _params.extend(['--network', network]) 477 | 478 | if no_dhcp: 479 | _params.append('--no-dhcp') 480 | 481 | self._execute('sandbox', _params, background=True) 482 | 483 | def is_supported(self): 484 | return os.path.isfile(LKVM_PATH) 485 | --------------------------------------------------------------------------------