1# -*- coding: utf-8 -*-
2#
3# Copyright: (c) 2019, Sandeep Kasargod <sandeep@vexata.com>
4# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
5
6from __future__ import (absolute_import, division, print_function)
7__metaclass__ = type
8
9
10HAS_VEXATAPI = True
11try:
12    from vexatapi.vexata_api_proxy import VexataAPIProxy
13except ImportError:
14    HAS_VEXATAPI = False
15
16from ansible.module_utils.common.text.converters import to_native
17from ansible.module_utils.basic import env_fallback
18
19VXOS_VERSION = None
20
21
22def get_version(iocs_json):
23    if not iocs_json:
24        raise Exception('Invalid IOC json')
25    active = filter(lambda x: x['mgmtRole'], iocs_json)
26    if not active:
27        raise Exception('Unable to detect active IOC')
28    active = active[0]
29    ver = active['swVersion']
30    if ver[0] != 'v':
31        raise Exception('Illegal version string')
32    ver = ver[1:ver.find('-')]
33    ver = map(int, ver.split('.'))
34    return tuple(ver)
35
36
37def get_array(module):
38    """Return storage array object or fail"""
39    global VXOS_VERSION
40    array = module.params['array']
41    user = module.params.get('user', None)
42    password = module.params.get('password', None)
43    validate = module.params.get('validate_certs')
44
45    if not HAS_VEXATAPI:
46        module.fail_json(msg='vexatapi library is required for this module. '
47                             'To install, use `pip install vexatapi`')
48
49    if user and password:
50        system = VexataAPIProxy(array, user, password, verify_cert=validate)
51    else:
52        module.fail_json(msg='The user/password are required to be passed in to '
53                             'the module as arguments or by setting the '
54                             'VEXATA_USER and VEXATA_PASSWORD environment variables.')
55    try:
56        if system.test_connection():
57            VXOS_VERSION = get_version(system.iocs())
58            return system
59        else:
60            module.fail_json(msg='Test connection to array failed.')
61    except Exception as e:
62        module.fail_json(msg='Vexata API access failed: {0}'.format(to_native(e)))
63
64
65def argument_spec():
66    """Return standard base dictionary used for the argument_spec argument in AnsibleModule"""
67    return dict(
68        array=dict(type='str',
69                   required=True),
70        user=dict(type='str',
71                  fallback=(env_fallback, ['VEXATA_USER'])),
72        password=dict(type='str',
73                      no_log=True,
74                      fallback=(env_fallback, ['VEXATA_PASSWORD'])),
75        validate_certs=dict(type='bool',
76                            required=False,
77                            default=False),
78    )
79
80
81def required_together():
82    """Return the default list used for the required_together argument to AnsibleModule"""
83    return [['user', 'password']]
84
85
86def size_to_MiB(size):
87    """Convert a '<integer>[MGT]' string to MiB, return -1 on error."""
88    quant = size[:-1]
89    exponent = size[-1]
90    if not quant.isdigit() or exponent not in 'MGT':
91        return -1
92    quant = int(quant)
93    if exponent == 'G':
94        quant <<= 10
95    elif exponent == 'T':
96        quant <<= 20
97    return quant
98