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

Sanity test #18

Merged
merged 4 commits into from
Jan 19, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions nutanix/ncp/plugins/module_utils/base_module.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Copyright: 2021, Ansible Project
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause )
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule


Expand Down
42 changes: 28 additions & 14 deletions nutanix/ncp/plugins/module_utils/entity.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Copyright: 2021, Ansible Project
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause )
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from base64 import b64encode
import time
import uuid
Expand Down Expand Up @@ -53,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 @@ -93,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 @@ -115,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 @@ -129,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 @@ -146,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 @@ -182,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 @@ -215,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 @@ -232,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 @@ -266,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
3 changes: 2 additions & 1 deletion nutanix/ncp/plugins/module_utils/prism/images.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# This file is part of Ansible
# 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
from .prism import Prism


Expand Down
4 changes: 2 additions & 2 deletions nutanix/ncp/plugins/module_utils/prism/subnets.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# This file is part of Ansible
# 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
from .prism import Prism


class Subnet(Prism):
kind = 'subnet'

18 changes: 12 additions & 6 deletions nutanix/ncp/plugins/module_utils/prism/vms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# This file is part of Ansible
# 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
from copy import deepcopy

from .prism import Prism
Expand All @@ -25,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 @@ -47,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 @@ -129,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 @@ -219,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
58 changes: 32 additions & 26 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 @@ -114,40 +116,44 @@
'''

RETURN = r'''

# CREATE /images
responses:
- default: Internal Error
- 202: Request Accepted

# UPDATE /images/{uuid}
responses:
- default: Internal Error
- 404: Invalid UUID provided
- 202: Request Accepted

# LIST /images/list
responses:
- default: Internal Error
- 200: Success

# DELETE /images/{uuid}
responses:
- default: Internal Error
- 404: Invalid UUID provided
- 202: Request Accepted
CREATE:
description: CREATE /images Response for nutanix imagese
returned: (for CREATE /images operation)
type: str
sample:
- default Internal Error
- 202 Request Accepted
UPDATE:
description: UPDATE /images/{uuid} Response for nutanix images
returned: (for UPDATE /images operation)
type: str
sample:
- default Internal Error
- 404 Invalid UUID provided
- 202 Request Accepted
LIST:
description: LIST /images/list Response for nutanix imagese
returned: (for LIST /images operation)
type: str
sample:
- default Internal Error
- 200 Success
DELETE:
description: DELETE /images/{uuid} Response for nutanix images
returned: (for DELETE /images operation)
type: str
sample:
- default Internal Error
- 404 Invalid UUID provided
- 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
57 changes: 32 additions & 25 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 @@ -98,33 +100,38 @@
'''

RETURN = r'''

# CREATE /subnets
responses:
- default: Internal Error
- 202: Request Accepted

# UPDATE /subnets/{uuid}
responses:
- default: Internal Error
- 404: Invalid UUID provided
- 202: Request Accepted

# LIST /subnets/list
responses:
- default: Internal Error
- 200: Success

# DELETE /subnets/{uuid}
responses:
- default: Internal Error
- 404: Invalid UUID provided
- 202: Request Accepted
CREATE:
description: CREATE /subnets Response for nutanix subnets
returned: (for CREATE /subnets operation)
type: str
sample:
- default Internal Error
- 202 Request Accepted
UPDATE:
description: UPDATE /subnets/{uuid} Response for nutanix subnets
returned: (for UPDATE /subnets operation)
type: str
sample:
- default Internal Error
- 404 Invalid UUID provided
- 202 Request Accepted
LIST:
description: LIST /subnets/list Response for nutanix subnets
returned: (for LIST /subnets operation)
type: str
sample:
- default Internal Error
- 200 Success
DELETE:
description: DELETE /subnets/{uuid} Response for nutanix subnets
returned: (for DELETE /subnets operation)
type: str
sample:
- default Internal Error
- 404 Invalid UUID provided
- 202 Request Accepted
'''

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


def run_module():
module = BaseModule()
Expand Down
Loading