Skip to content

Commit

Permalink
pep8 and pylint test
Browse files Browse the repository at this point in the history
  • Loading branch information
alaa-bish committed Jan 19, 2022
1 parent 0198719 commit 2d4d3df
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 45 deletions.
40 changes: 26 additions & 14 deletions nutanix/ncp/plugins/module_utils/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,30 +55,35 @@ def parse_data(self):
def check_response(self):

if self.response.get("task_uuid") and self.wait:
task = self.validate_request(self.module, self.response.get("task_uuid"), self.netloc, self.wait_timeout)
task = self.validate_request(self.module, self.response.get(
"task_uuid"), self.netloc, self.wait_timeout)
self.result["task_information"] = task

if not self.response.get("status"):
if self.response.get("api_response_list"):
self.response["status"] = self.response.get("api_response_list")[0].get("api_response").get("status")
self.response["status"] = self.response.get("api_response_list")[
0].get("api_response").get("status")
elif "entities" in self.response:
if self.response["entities"]:
self.response["status"] = self.response.get("entities")[0].get("status")
self.response["status"] = self.response.get("entities")[
0].get("status")
else:
self.response["status"] = {"state": "complete"}

if self.response.get("status") and self.wait:
state = self.response.get("status").get("state")
if "pending" in state.lower() or "running" in state.lower():
task = self.validate_request(self.module,
self.response.get("status").get("execution_context").get("task_uuid"),
self.response.get("status").get(
"execution_context").get("task_uuid"),
self.netloc,
self.wait_timeout)
self.response["status"]["state"] = task.get("status")
self.result["task_information"] = task

self.result["changed"] = True
status = self.response.get("state") or self.response.get("status").get("state")
status = self.response.get(
"state") or self.response.get("status").get("state")
if status and status.lower() != "succeeded" or self.action == "list":
self.result["changed"] = False
if status.lower() != "complete":
Expand All @@ -95,7 +100,8 @@ def update(self):
self.url += "/" + str(uuid.UUID(item_uuid))
else:
self.url += "/" + str(uuid.UUID(item_uuid)) + "/file"
response = self.send_request(self.module, "get", self.url, self.data, self.username, self.password)
response = self.send_request(
self.module, "get", self.url, self.data, self.username, self.password)

if response.get("state") and response.get("state").lower() == "error":
self.result["changed"] = False
Expand All @@ -117,7 +123,7 @@ def list(self):
def send_request(module, method, req_url, req_data, username, password, timeout=30):
try:
credentials = bytes(username + ":" + password, encoding="ascii")
except:
except BaseException:
credentials = bytes(username + ":" + password).encode("ascii")

encoded_credentials = b64encode(credentials).decode("ascii")
Expand All @@ -131,7 +137,8 @@ def send_request(module, method, req_url, req_data, username, password, timeout=
resp, info = fetch_url(module=module, url=req_url, headers=headers,
method=method, data=module.jsonify(payload), timeout=timeout)
if not 300 > info['status'] > 199:
module.fail_json(msg="Fail: %s" % ("Status: " + str(info['msg']) + ", Message: " + str(info.get('body'))))
module.fail_json(msg="Fail: %s" % (
"Status: " + str(info['msg']) + ", Message: " + str(info.get('body'))))

body = resp.read() if resp else info.get("body")
try:
Expand All @@ -148,7 +155,8 @@ def validate_request(self, module, task_uuid, netloc, wait_timeout):
task_uuid = str(uuid.UUID(task_uuid))
url = self.generate_url_from_operations("tasks", netloc, [task_uuid])
while retries > 0 or not succeeded:
response = self.send_request(module, "get", url, None, self.username, self.password)
response = self.send_request(
module, "get", url, None, self.username, self.password)
if response.get("status"):
status = response.get("status")
if "running" not in status.lower() and "queued" not in status.lower():
Expand Down Expand Up @@ -184,9 +192,10 @@ def get_action(self):
if self.action in self.methods_of_actions.keys():
self.action = self.methods_of_actions[self.action]
elif self.action == 'present':
self.action = 'update' if self.data['metadata'].get('uuid') else 'create'
self.action = 'update' if self.data['metadata'].get(
'uuid') else 'create'
else:
raise ValueError("Wrong action: "+ self.action)
raise ValueError("Wrong action: " + self.action)

@staticmethod
def get_spec():
Expand Down Expand Up @@ -217,7 +226,8 @@ def clean_spec(self, spec):
list_key = obj.pop('list_key')
sub_spec_key = list_key.split('__')[-1]
if list_key:
value = self.get_attr_spec(sub_spec_key, getattr(self, list_key, None))
value = self.get_attr_spec(
sub_spec_key, getattr(self, list_key, None))
if value:
spec[key] = value
else:
Expand All @@ -234,7 +244,8 @@ def build(self):

self.parse_data()

self.url = self.generate_url_from_operations(self.module_name, self.netloc, self.operations)
self.url = self.generate_url_from_operations(
self.module_name, self.netloc, self.operations)

self.get_action()

Expand Down Expand Up @@ -268,7 +279,8 @@ def run_module(self, module):
self.credentials = self.auth.get("credentials")

if not self.url:
self.url = str(self.auth.get("ip_address")) + ":" + str(self.auth.get("port"))
self.url = str(self.auth.get("ip_address")) + \
":" + str(self.auth.get("port"))

self.netloc = self.url
self.module_name = module._name
Expand Down
1 change: 0 additions & 1 deletion nutanix/ncp/plugins/module_utils/prism/subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@

class Subnet(Prism):
kind = 'subnet'

16 changes: 10 additions & 6 deletions nutanix/ncp/plugins/module_utils/prism/vms.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def _get_api_spec(self, param_spec, **kwargs):
pass

def get_entity_by_name(self, name='', kind=''):
url = self.generate_url_from_operations(kind, netloc=self.url, ops=['list'])
url = self.generate_url_from_operations(
kind, netloc=self.url, ops=['list'])
data = {
'filter': 'name==%s' % name,
'length': 1
Expand All @@ -49,15 +50,16 @@ def get_entity_by_name(self, name='', kind=''):

class VMSpec():

@staticmethod
def get_default_spec(self):
raise NotImplementedError(
"Get Default Spec helper not implemented for {}".format(self.entity_type)
"Get Default Spec helper not implemented for {0}".format(
self.entity_type)
)

def _get_api_spec(self, param_spec, **kwargs):
raise NotImplementedError(
"Get Api Spec helper not implemented for {}".format(self.entity_type)
"Get Api Spec helper not implemented for {0}".format(
self.entity_type)
)

def remove_null_references(self, spec, parent_spec=None, spec_key=None):
Expand Down Expand Up @@ -131,7 +133,8 @@ def _get_api_spec(self, param_spec, **kwargs):
for disk_param in param_spec:
disk_final = self.get_default_spec()
if disk_param.get("clone_image"):
disk_final["data_source_reference"] = self.__get_image_ref(disk_param["clone_image"], **kwargs)
disk_final["data_source_reference"] = self.__get_image_ref(
disk_param["clone_image"], **kwargs)

disk_final["device_properties"]["device_type"] = disk_param["type"]
disk_final["device_properties"]["disk_address"]["adapter_type"] = disk_param["bus"]
Expand Down Expand Up @@ -221,7 +224,8 @@ def _get_api_spec(self, param_spec, **kwargs):
"uuid": v
}
elif k == "subnet_name" and not nic_param.get("subnet_uuid"):
nic_final["subnet_reference"] = self.__get_subnet_ref(v, **kwargs)
nic_final["subnet_reference"] = self.__get_subnet_ref(
v, **kwargs)

elif k == "ip_endpoint_list" and bool(v):
nic_final[k] = [{"ip": v[0]}]
Expand Down
6 changes: 2 additions & 4 deletions nutanix/ncp/plugins/modules/nutanix_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Copyright: (c) 2021
# 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)
from ..module_utils.prism.images import Image
from ..module_utils.base_module import BaseModule
__metaclass__ = type


Expand Down Expand Up @@ -146,16 +148,12 @@
- 202 Request Accepted
'''

from ..module_utils.base_module import BaseModule
from ..module_utils.prism.images import Image


def run_module():
module = BaseModule()
Image(module)



def main():
run_module()

Expand Down
5 changes: 2 additions & 3 deletions nutanix/ncp/plugins/modules/nutanix_subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Copyright: (c) 2021
# 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)
from ..module_utils.prism.subnets import Subnet
from ..module_utils.base_module import BaseModule
__metaclass__ = type


Expand Down Expand Up @@ -130,9 +132,6 @@
- 202 Request Accepted
'''

from ..module_utils.base_module import BaseModule
from ..module_utils.prism.subnets import Subnet


def run_module():
module = BaseModule()
Expand Down
42 changes: 25 additions & 17 deletions nutanix/ncp/plugins/modules/nutanix_vms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Copyright: (c) 2021
# 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)
from ..module_utils.prism.vms import VM
from ..module_utils.base_module import BaseModule

__metaclass__ = type

Expand Down Expand Up @@ -48,47 +50,51 @@
RETURN = r'''
'''

from ..module_utils.base_module import BaseModule
from ..module_utils.prism.vms import VM


def run_module():
BaseModule.argument_spec.update(dict(
spec__name=dict(type='str', required=False, aliases=['name']),
spec__description=dict(type='str', required=False, aliases=['desc', 'description']),
spec__description=dict(type='str', required=False, aliases=[
'desc', 'description']),
metadata__uuid=dict(type='str', aliases=['uuid'], required=False),
spec__resources__num_sockets=dict(type='int', default=1, aliases=['core_count', 'vcpus']),
spec__resources__num_sockets=dict(
type='int', default=1, aliases=['core_count', 'vcpus']),
spec__resources__num_threads_per_core=dict(type='int', # default=1,#will not provide
aliases=['threads_per_core']),
spec__resources__num_vcpus_per_socket=dict(type='int', default=1,
spec__resources__num_vcpus_per_socket=dict(type='int', default=1,
aliases=['num_vcpus_per_socket', 'cores_per_vcpu']),
cluster=dict(type='dict', default={}, options=dict(
spec__cluster_reference__uuid=dict(type='str', aliases=['cluster_uuid', 'uuid'], required=False),
spec__cluster_reference__name=dict(type='str', aliases=['cluster_name', 'name'], required=False),
spec__cluster_reference__uuid=dict(
type='str', aliases=['cluster_uuid', 'uuid'], required=False),
spec__cluster_reference__name=dict(
type='str', aliases=['cluster_name', 'name'], required=False),
spec__cluster_reference__kind=dict(type='str', aliases=['cluster_kind'], required=False,
default='cluster'), ),
),
),
spec__resources__nic_list=dict(type='list', aliases=['networks'], elements='dict', options=dict(
uuid=dict(type='str', aliases=['nic_uuid']),
subnet_uuid=dict(type='str'),
subnet_name=dict(type='str'),
subnet_kind=dict(type='str', default='subnet'),
is_connected=dict(type='bool', aliases=['connected'], default=False),
ip_endpoint_list=dict(type='list', aliases=['private_ip'], default=[]),
is_connected=dict(type='bool', aliases=[
'connected'], default=False),
ip_endpoint_list=dict(type='list', aliases=[
'private_ip'], default=[]),
nic_type=dict(type='str', default='NORMAL_NIC'),

), default=[]),
spec__resources__disk_list=dict(type='list', aliases=['disks'], options=dict(
type=dict(type='str'),
size_gb=dict(type='int'),
bus=dict(type='str'),
storage_config=dict(type=dict,aliases=['storage_container'], options=dict(
storage_config=dict(type=dict, aliases=['storage_container'], options=dict(
storage_container_name=dict(type='str'),
storage_container_uuid=dict(type='str',aliases=['uuid'])
storage_container_uuid=dict(type='str', aliases=['uuid'])
))

), default=[]),
spec__resources__hardware_clock_timezone=dict(type='str', default='UTC', aliases=['timezone']),
spec__resources__hardware_clock_timezone=dict(
type='str', default='UTC', aliases=['timezone']),
spec__resources__boot_config__boot_type=dict(type='str',
default='LEGACY',
aliases=['boot_type']),
Expand All @@ -100,10 +106,12 @@ def run_module():
], aliases=['boot_device_order_list']),
spec__resources__memory_overcommit_enabled=dict(
type='bool', default=False, aliases=['memory_overcommit_enabled']),
spec__resources__memory_size_mib=dict(type='int', default=1, aliases=['memory_size_mib', 'memory_gb']),
spec__resources__memory_size_mib=dict(type='int', default=1, aliases=[
'memory_size_mib', 'memory_gb']),
metadata__categories_mapping=dict(type='dict', aliases=['categories']),
metadata__use_categories_mapping=dict(type='bool', aliases=['use_categories_mapping'], default=False)
))
metadata__use_categories_mapping=dict(
type='bool', aliases=['use_categories_mapping'], default=False)
))

module = BaseModule()
if module.params.get('spec__resources__memory_size_mib'):
Expand Down

0 comments on commit 2d4d3df

Please sign in to comment.