Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

virt: PEP8 compliancy and doc fixes #30917

Merged
merged 1 commit into from
Sep 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
162 changes: 74 additions & 88 deletions lib/ansible/modules/cloud/misc/virt.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright 2007, 2012 Red Hat, Inc
# Copyright: (c) 2007, 2012 Red Hat, Inc
# Michael DeHaan <michael.dehaan@gmail.com>
# Seth Vidal <skvidal@fedoraproject.org>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}


DOCUMENTATION = '''
---
module: virt
Expand All @@ -29,46 +26,35 @@
- name of the guest VM being managed. Note that VM must be previously
defined with xml.
required: true
default: null
aliases: []
state:
description:
- Note that there may be some lag for state requests like C(shutdown)
since these refer only to VM states. After starting a guest, it may not
be immediately accessible.
required: false
choices: [ "running", "shutdown", "destroyed", "paused" ]
default: "no"
choices: [ destroyed, paused, running, shutdown ]
command:
description:
- in addition to state management, various non-idempotent commands are available. See examples
required: false
choices: ["create","status", "start", "stop", "pause", "unpause",
"shutdown", "undefine", "destroy", "get_xml",
"freemem", "list_vms", "info", "nodeinfo", "virttype", "define"]
- In addition to state management, various non-idempotent commands are available.
choices: [ create, define, destroy, freemem, get_xml, info, list_vms, nodeinfo, pause, shutdown, start, status, stop, undefine, unpause, virttype ]
autostart:
description:
- start VM at host startup
choices: [True, False]
- start VM at host startup.
type: bool
version_added: "2.3"
default: null
uri:
description:
- libvirt connection uri
required: false
- libvirt connection uri.
default: qemu:///system
xml:
description:
- XML document used with the define command
required: false
default: null
- XML document used with the define command.
requirements:
- "python >= 2.6"
- "libvirt-python"
- python >= 2.6
- libvirt-python
author:
- "Ansible Core Team"
- "Michael DeHaan"
- "Seth Vidal"
- Ansible Core Team
- Michael DeHaan
- Seth Vidal
'''

EXAMPLES = '''
Expand Down Expand Up @@ -131,28 +117,29 @@

VIRT_FAILED = 1
VIRT_SUCCESS = 0
VIRT_UNAVAILABLE=2
VIRT_UNAVAILABLE = 2

ALL_COMMANDS = []
VM_COMMANDS = ['create','status', 'start', 'stop', 'pause', 'unpause',
'shutdown', 'undefine', 'destroy', 'get_xml', 'define']
HOST_COMMANDS = ['freemem', 'list_vms', 'info', 'nodeinfo', 'virttype']
VM_COMMANDS = ['create', 'define', 'destroy', 'get_xml', 'pause', 'shutdown', 'status', 'start', 'stop' 'undefine', 'unpause']
HOST_COMMANDS = ['freemem', 'info', 'list_vms', 'nodeinfo', 'virttype']
ALL_COMMANDS.extend(VM_COMMANDS)
ALL_COMMANDS.extend(HOST_COMMANDS)

VIRT_STATE_NAME_MAP = {
0 : "running",
1 : "running",
2 : "running",
3 : "paused",
4 : "shutdown",
5 : "shutdown",
6 : "crashed"
0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed',
}


class VMNotFound(Exception):
pass


class LibvirtConnection(object):

def __init__(self, uri, module):
Expand Down Expand Up @@ -230,11 +217,11 @@ def undefine(self, vmid):

def get_status2(self, vm):
state = vm.info()[0]
return VIRT_STATE_NAME_MAP.get(state,"unknown")
return VIRT_STATE_NAME_MAP.get(state, "unknown")

def get_status(self, vmid):
state = self.find_vm(vmid).info()[0]
return VIRT_STATE_NAME_MAP.get(state,"unknown")
return VIRT_STATE_NAME_MAP.get(state, "unknown")

def nodeinfo(self):
return self.conn.getInfo()
Expand Down Expand Up @@ -288,7 +275,7 @@ def state(self):
state = []
for vm in vms:
state_blurb = self.conn.get_status(vm)
state.append("%s %s" % (vm,state_blurb))
state.append("%s %s" % (vm, state_blurb))
return state

def info(self):
Expand All @@ -301,31 +288,30 @@ def info(self):
# This throws exceptions, so convert them to strings here and
# assume the other end of the xmlrpc connection can figure things
# out or doesn't care.
info[vm] = {
"state" : VIRT_STATE_NAME_MAP.get(data[0],"unknown"),
"maxMem" : str(data[1]),
"memory" : str(data[2]),
"nrVirtCpu" : data[3],
"cpuTime" : str(data[4]),
}
info[vm]["autostart"] = self.conn.get_autostart(vm)
info[vm] = dict(
state=VIRT_STATE_NAME_MAP.get(data[0], "unknown"),
maxMem=str(data[1]),
memory=str(data[2]),
nrVirtCpu=data[3],
cpuTime=str(data[4]),
autostart=self.conn.get_autostart(vm),
)

return info

def nodeinfo(self):
self.__get_conn()
info = dict()
data = self.conn.nodeinfo()
info = {
"cpumodel" : str(data[0]),
"phymemory" : str(data[1]),
"cpus" : str(data[2]),
"cpumhz" : str(data[3]),
"numanodes" : str(data[4]),
"sockets" : str(data[5]),
"cpucores" : str(data[6]),
"cputhreads" : str(data[7])
}
info = dict(
cpumodel=str(data[0]),
phymemory=str(data[1]),
cpus=str(data[2]),
cpumhz=str(data[3]),
numanodes=str(data[4]),
sockets=str(data[5]),
cpucores=str(data[6]),
cputhreads=str(data[7])
)
return info

def list_vms(self, state=None):
Expand Down Expand Up @@ -366,7 +352,6 @@ def shutdown(self, vmid):
self.conn.shutdown(vmid)
return 0


def pause(self, vmid):
""" Pause the machine with the given vmid. """

Expand Down Expand Up @@ -441,27 +426,28 @@ def define(self, xml):
self.__get_conn()
return self.conn.define_from_xml(xml)


def core(module):

state = module.params.get('state', None)
autostart = module.params.get('autostart', None)
guest = module.params.get('name', None)
command = module.params.get('command', None)
uri = module.params.get('uri', None)
xml = module.params.get('xml', None)
state = module.params.get('state', None)
autostart = module.params.get('autostart', None)
guest = module.params.get('name', None)
command = module.params.get('command', None)
uri = module.params.get('uri', None)
xml = module.params.get('xml', None)

v = Virt(uri, module)
res = {}
res = dict()

if state and command=='list_vms':
if state and command == 'list_vms':
res = v.list_vms(state=state)
if not isinstance(res, dict):
res = { command: res }
res = {command: res}
return VIRT_SUCCESS, res

if state:
if not guest:
module.fail_json(msg = "state change requires a guest specified")
module.fail_json(msg="state change requires a guest specified")

if state == 'running':
if v.status(guest) is 'paused':
Expand Down Expand Up @@ -493,10 +479,10 @@ def core(module):
if command:
if command in VM_COMMANDS:
if not guest:
module.fail_json(msg = "%s requires 1 argument: guest" % command)
module.fail_json(msg="%s requires 1 argument: guest" % command)
if command == 'define':
if not xml:
module.fail_json(msg = "define requires xml argument")
module.fail_json(msg="define requires xml argument")
try:
v.get_vm(guest)
except VMNotFound:
Expand All @@ -505,43 +491,43 @@ def core(module):
return VIRT_SUCCESS, res
res = getattr(v, command)(guest)
if not isinstance(res, dict):
res = { command: res }
res = {command: res}
return VIRT_SUCCESS, res

elif hasattr(v, command):
res = getattr(v, command)()
if not isinstance(res, dict):
res = { command: res }
res = {command: res}
return VIRT_SUCCESS, res

else:
module.fail_json(msg="Command %s not recognized" % command)

module.fail_json(msg="expected state or command parameter to be specified")

def main():

module = AnsibleModule(argument_spec=dict(
name = dict(aliases=['guest']),
state = dict(choices=['running', 'shutdown', 'destroyed', 'paused']),
autostart = dict(type='bool'),
command = dict(choices=ALL_COMMANDS),
uri = dict(default='qemu:///system'),
xml = dict(),
))
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', aliases=['guest']),
state=dict(type='str', choices=['destroyed', 'pause', 'running', 'shutdown']),
autostart=dict(type='bool'),
command=dict(type='str', choices=ALL_COMMANDS),
uri=dict(type='str', default='qemu:///system'),
xml=dict(type='str'),
),
)

if not HAS_VIRT:
module.fail_json(
msg='The `libvirt` module is not importable. Check the requirements.'
)
module.fail_json(msg='The `libvirt` module is not importable. Check the requirements.')

rc = VIRT_SUCCESS
try:
rc, result = core(module)
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())

if rc != 0: # something went wrong emit the msg
if rc != 0: # something went wrong emit the msg
module.fail_json(rc=rc, msg=result)
else:
module.exit_json(**result)
Expand Down
1 change: 0 additions & 1 deletion test/sanity/pep8/legacy-files.txt
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ lib/ansible/modules/cloud/lxd/lxd_profile.py
lib/ansible/modules/cloud/misc/ovirt.py
lib/ansible/modules/cloud/misc/rhevm.py
lib/ansible/modules/cloud/misc/serverless.py
lib/ansible/modules/cloud/misc/virt.py
lib/ansible/modules/cloud/misc/virt_net.py
lib/ansible/modules/cloud/misc/virt_pool.py
lib/ansible/modules/cloud/misc/xenserver_facts.py
Expand Down